All files decoratorRegistry.ts

98.23% Statements 111/113
94.93% Branches 75/79
97.22% Functions 35/36
98.11% Lines 104/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 3672x 2x 2x                                                                                     12x       12x 2x           25x 1x     24x 18x     6x             7x 1x     6x                     37x 30x 13x 9x       5x     4x           22x 20x     2x 2x       21x   20x 20x   20x 21x 21x     20x       22x 1x     21x 21x       10x                 21x 21x     21x 21x           2x       19x   21x     25x             11x             12x                       22x 22x 1x     21x 21x 21x   21x 22x 22x   21x 21x     21x           2x 2x   2x       2x 2x                   2x           21x 6x   6x       6x 5x                           25x 15x 14x     25x 6x 4x     25x           11x 4x 4x     11x 1x 1x     11x           12x 6x 6x     12x         12x               29x 29x   26x 1x             25x 2x             23x                             30x 30x   30x             30x 30x 15x   15x         2x     21x    
import { immutableClone } from './clone';
import { createSnapshot } from './snapshot';
import { symbolMetadata } from './symbolMetadata';
import type {
  AccessorDecoratorFactory,
  AnyFunction,
  Constructor,
  CreateDecoratorRegistryOptions,
  DecorationKind,
  DecorationRecord,
  DecoratorRegistry,
  DecoratorSchema,
  DirectKeyedMetadataArgs,
  MetadataArgs,
  MetadataOf,
  MethodDecoratorFactory,
  PropertyDecoratorFactory,
  PublicMemberKey,
  RegistryMetadataSnapshot,
  RegistryReadOptions,
  ScopedDecoratorBuilder,
  StandardClassDecorator,
  StringKeyOf,
  TargetOf,
  UnscopedClassDecoratorFactory,
} from './types';
 
type DecoratorMetadataObject = object;
 
type ClassOrMemberContext =
  | ClassDecoratorContext
  | ClassFieldDecoratorContext
  | ClassMethodDecoratorContext
  | ClassAccessorDecoratorContext
  | ClassGetterDecoratorContext
  | ClassSetterDecoratorContext;
 
type MemberContext = Exclude<ClassOrMemberContext, ClassDecoratorContext>;
 
type ParsedDecoratorArgs = {
  readonly key?: PublicMemberKey;
  readonly metadata: unknown;
};
 
function isPropertyKey(value: unknown): value is PublicMemberKey {
  return typeof value === 'string' || typeof value === 'symbol';
}
 
function assertPropertyKey(value: unknown, decoratorName: string): PublicMemberKey {
  if (isPropertyKey(value)) return value;
  throw new TypeError(
    `Decorator "${decoratorName}" expected a string or symbol member key, but received ${typeof value}.`,
  );
}
 
function parseDirectArgs(args: readonly unknown[], decoratorName: string): ParsedDecoratorArgs {
  if (args.length === 0) {
    return { metadata: undefined };
  }
 
  if (args.length === 1) {
    return { metadata: args[0] };
  }
 
  return {
    key: assertPropertyKey(args[0], decoratorName),
    metadata: args[1],
  };
}
 
function parseOnArgs(args: readonly unknown[], decoratorName: string): ParsedDecoratorArgs {
  if (args.length === 0) {
    throw new TypeError(`Decorator "${decoratorName}.on" requires a member key.`);
  }
 
  return {
    key: assertPropertyKey(args[0], `${decoratorName}.on`),
    metadata: args.length > 1 ? args[1] : undefined,
  };
}
 
function assertContextKind(
  expectedKind: DecorationKind,
  decoratorName: string,
  context: ClassOrMemberContext,
): void {
  if (expectedKind === 'class' && context.kind === 'class') return;
  if (expectedKind === 'property' && context.kind === 'field') return;
  if (expectedKind === 'method' && context.kind === 'method') return;
  if (
    expectedKind === 'accessor' &&
    (context.kind === 'accessor' || context.kind === 'getter' || context.kind === 'setter')
  ) {
    return;
  }
 
  throw new TypeError(
    `Decorator "${decoratorName}" can only be used on ${expectedKind} targets, but was used on ${context.kind}.`,
  );
}
 
function getTargetConstructor(target: Constructor | object): Constructor | undefined {
  if (typeof target === 'function') {
    return target as Constructor;
  }
 
  const constructor = target.constructor;
  return typeof constructor === 'function' ? (constructor as Constructor) : undefined;
}
 
function getConstructorChain(constructor: Constructor, includeInherited: boolean): Constructor[] {
  if (!includeInherited) return [constructor];
 
  const chain: Constructor[] = [];
  let current: unknown = constructor;
 
  while (typeof current === 'function' && current !== Function.prototype) {
    chain.push(current as Constructor);
    current = Object.getPrototypeOf(current);
  }
 
  return chain.reverse();
}
 
function getOwnMetadataObject(constructor: Constructor): DecoratorMetadataObject | undefined {
  if (!Object.prototype.hasOwnProperty.call(constructor, symbolMetadata)) {
    return undefined;
  }
 
  const metadata = (constructor as unknown as Record<PropertyKey, unknown>)[symbolMetadata];
  return typeof metadata === 'object' && metadata !== null ? metadata : undefined;
}
 
function samePropertyKey(left: PublicMemberKey, right: PublicMemberKey): boolean {
  return left === right;
}
 
class ModernDecoratorRegistry<TSchema extends DecoratorSchema>
  implements DecoratorRegistry<TSchema>
{
  public readonly namespace: string;
  public readonly allowPrivateMembers: boolean;
 
  private nextOrder = 0;
  private readonly recordsByMetadata = new WeakMap<DecoratorMetadataObject, DecorationRecord[]>();
 
  public constructor(options: CreateDecoratorRegistryOptions = {}) {
    this.namespace = options.namespace ?? 'default';
    this.allowPrivateMembers = options.allowPrivateMembers ?? false;
  }
 
  public class<K extends StringKeyOf<TSchema['class']>>(
    name: K,
  ): UnscopedClassDecoratorFactory<MetadataOf<TSchema['class'][K]>> {
    return this.createClassFactory(String(name));
  }
 
  public for<TContract>(): ScopedDecoratorBuilder<TSchema, TContract> {
    return Object.freeze({
      class: <K extends StringKeyOf<TSchema['class']>>(name: K) =>
        this.createScopedClassFactory<TContract, MetadataOf<TSchema['class'][K]>>(String(name)),
 
      property: <K extends StringKeyOf<TSchema['property']>>(name: K) =>
        this.createPropertyFactory<
          TContract,
          TargetOf<TSchema['property'][K]>,
          MetadataOf<TSchema['property'][K]>
        >(String(name)),
 
      method: <K extends StringKeyOf<TSchema['method']>>(name: K) =>
        this.createMethodFactory<
          TContract,
          Extract<TargetOf<TSchema['method'][K]>, AnyFunction>,
          MetadataOf<TSchema['method'][K]>
        >(String(name)),
 
      accessor: <K extends StringKeyOf<TSchema['accessor']>>(name: K) =>
        this.createAccessorFactory<
          TContract,
          TargetOf<TSchema['accessor'][K]>,
          MetadataOf<TSchema['accessor'][K]>
        >(String(name)),
    });
  }
 
  public read(
    target: Constructor | object,
    options: RegistryReadOptions = {},
  ): RegistryMetadataSnapshot {
    const constructor = getTargetConstructor(target);
    if (constructor === undefined) {
      return createSnapshot([]);
    }
 
    const includeInherited = options.includeInherited ?? true;
    const constructors = getConstructorChain(constructor, includeInherited);
    const records: DecorationRecord[] = [];
 
    for (const current of constructors) {
      const metadata = getOwnMetadataObject(current);
      if (metadata === undefined) continue;
 
      const ownRecords = this.recordsByMetadata.get(metadata);
      Eif (ownRecords !== undefined) records.push(...ownRecords);
    }
 
    return createSnapshot(records);
  }
 
  private createClassFactory<TMetadata>(
    decoratorName: string,
  ): UnscopedClassDecoratorFactory<TMetadata> {
    const factory = (<TExpected = unknown>(...args: MetadataArgs<TMetadata>) => {
      const metadata = args.length === 0 ? undefined : args[0];
 
      return <TClass extends Constructor<TExpected>>(
        _value: TClass,
        context: ClassDecoratorContext<TClass>,
      ): void => {
        assertContextKind('class', decoratorName, context);
        this.register(context.metadata, {
          kind: 'class',
          decorator: decoratorName,
          metadata,
          static: false,
          private: false,
        });
      };
    }) as UnscopedClassDecoratorFactory<TMetadata>;
 
    return factory;
  }
 
  private createScopedClassFactory<TContract, TMetadata>(
    decoratorName: string,
  ): StandardClassDecorator<TContract, TMetadata> {
    return ((...args: MetadataArgs<TMetadata>) => {
      const metadata = args.length === 0 ? undefined : args[0];
 
      return <TClass extends Constructor<TContract>>(
        _value: TClass,
        context: ClassDecoratorContext<TClass>,
      ): void => {
        assertContextKind('class', decoratorName, context);
        this.register(context.metadata, {
          kind: 'class',
          decorator: decoratorName,
          metadata,
          static: false,
          private: false,
        });
      };
    }) as StandardClassDecorator<TContract, TMetadata>;
  }
 
  private createPropertyFactory<TContract, TTarget, TMetadata>(
    decoratorName: string,
  ): PropertyDecoratorFactory<TContract, TTarget, TMetadata> {
    const factory = ((...args: unknown[]) => {
      const parsed = parseDirectArgs(args, decoratorName);
      return this.createMemberDecorator('property', decoratorName, parsed);
    }) as unknown as PropertyDecoratorFactory<TContract, TTarget, TMetadata>;
 
    factory.on = ((...args: unknown[]) => {
      const parsed = parseOnArgs(args, decoratorName);
      return this.createMemberDecorator('property', decoratorName, parsed);
    }) as PropertyDecoratorFactory<TContract, TTarget, TMetadata>['on'];
 
    return factory;
  }
 
  private createMethodFactory<TContract, TTarget extends AnyFunction, TMetadata>(
    decoratorName: string,
  ): MethodDecoratorFactory<TContract, TTarget, TMetadata> {
    const factory = ((...args: unknown[]) => {
      const parsed = parseDirectArgs(args, decoratorName);
      return this.createMemberDecorator('method', decoratorName, parsed);
    }) as unknown as MethodDecoratorFactory<TContract, TTarget, TMetadata>;
 
    factory.on = ((...args: unknown[]) => {
      const parsed = parseOnArgs(args, decoratorName);
      return this.createMemberDecorator('method', decoratorName, parsed);
    }) as MethodDecoratorFactory<TContract, TTarget, TMetadata>['on'];
 
    return factory;
  }
 
  private createAccessorFactory<TContract, TTarget, TMetadata>(
    decoratorName: string,
  ): AccessorDecoratorFactory<TContract, TTarget, TMetadata> {
    const factory = ((...args: unknown[]) => {
      const parsed = parseDirectArgs(args, decoratorName);
      return this.createMemberDecorator('accessor', decoratorName, parsed);
    }) as unknown as AccessorDecoratorFactory<TContract, TTarget, TMetadata>;
 
    factory.on = ((...args: unknown[]) => {
      const parsed = parseOnArgs(args, decoratorName);
      return this.createMemberDecorator('accessor', decoratorName, parsed);
    }) as AccessorDecoratorFactory<TContract, TTarget, TMetadata>['on'];
 
    return factory;
  }
 
  private createMemberDecorator(
    kind: Exclude<DecorationKind, 'class'>,
    decoratorName: string,
    parsed: ParsedDecoratorArgs,
  ) {
    return (_value: unknown, context: MemberContext): void => {
      assertContextKind(kind, decoratorName, context);
 
      if (context.private && !this.allowPrivateMembers) {
        throw new Error(
          `Decorator "${decoratorName}" cannot be used on private member "${String(
            context.name,
          )}" unless allowPrivateMembers is true.`,
        );
      }
 
      if (parsed.key !== undefined && !samePropertyKey(parsed.key, context.name)) {
        throw new Error(
          `Decorator "${decoratorName}" was keyed for "${String(
            parsed.key,
          )}" but applied to "${String(context.name)}".`,
        );
      }
 
      this.register(context.metadata, {
        kind,
        decorator: decoratorName,
        metadata: parsed.metadata,
        memberName: context.name,
        static: context.static,
        private: context.private,
      });
    };
  }
 
  private register(
    metadataObject: DecoratorMetadataObject,
    record: Omit<DecorationRecord, 'id' | 'order'>,
  ): void {
    const order = this.nextOrder;
    this.nextOrder += 1;
 
    const immutableRecord = Object.freeze({
      ...record,
      id: `${this.namespace}:${record.kind}:${record.decorator}:${order}`,
      order,
      metadata: immutableClone(record.metadata),
    }) as DecorationRecord;
 
    const existing = this.recordsByMetadata.get(metadataObject);
    if (existing === undefined) {
      this.recordsByMetadata.set(metadataObject, [immutableRecord]);
    } else {
      existing.push(immutableRecord);
    }
  }
}
 
export function createDecoratorRegistry<TSchema extends DecoratorSchema>(
  options: CreateDecoratorRegistryOptions = {},
): DecoratorRegistry<TSchema> {
  return new ModernDecoratorRegistry<TSchema>(options);
}