All files / src/utils get-injectors.mts

93.05% Statements 67/72
82.85% Branches 29/35
94.11% Functions 16/17
93.05% Lines 67/72

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 367 368 369 370 371 372                                                                                                                                                                                                                                                                                                              143x         1349x 1349x 1349x     467x         467x     143x 143x             310x         310x 143x 143x 143x         143x   167x 167x         167x 167x     160x 160x       7x     167x       310x       410x     300x     310x 310x   310x                     12x 1x         11x     12x 12x 11x       11x         542x 681x 681x 681x 681x                   681x 140x   681x 681x 681x       681x 681x                         301x   301x 1x           300x 300x             301x     301x 17x       282x 7x   275x 135x       140x 140x       140x                                       4x 4x     1x       143x               143x    
import type { z, ZodObject, ZodType } from 'zod/v4'
 
import type {
  Factorable,
  FactorableWithArgs,
} from '../interfaces/factory.interface.mjs'
import type { ServiceInitializationContext } from '../internal/context/service-initialization-context.mjs'
import type {
  BoundInjectionToken,
  ClassType,
  ClassTypeWithArgument,
  ClassTypeWithoutArguments,
  FactoryInjectionToken,
  InjectionToken,
  InjectionTokenSchemaType,
} from '../token/injection-token.mjs'
import type {
  InjectRequest,
  InjectState,
  Join,
  UnionToArray,
} from './types.mjs'
 
import { withoutResolutionContext } from '../internal/context/resolution-context.mjs'
import { InjectableTokenMeta } from '../symbols/index.mjs'
 
export interface Injectors {
  // #1 Simple class
  asyncInject<T extends ClassTypeWithoutArguments>(
    token: T,
  ): InstanceType<T> extends Factorable<infer R>
    ? Promise<R>
    : Promise<InstanceType<T>>
  asyncInject<Args, T extends ClassTypeWithArgument<Args>>(
    token: T,
    args: Args,
  ): Promise<InstanceType<T>>
  asyncInject<
    Schema extends InjectionTokenSchemaType,
    R,
    T extends FactorableWithArgs<R, Schema>,
  >(
    token: T,
    args: z.input<Schema>,
  ): Promise<R>
 
  // #2 Token with required Schema
  asyncInject<T, S extends InjectionTokenSchemaType>(
    token: InjectionToken<T, S>,
    args: z.input<S>,
  ): Promise<T>
  // #3 Token with optional Schema
  asyncInject<T, S extends InjectionTokenSchemaType, R extends boolean>(
    token: InjectionToken<T, S, R>,
  ): R extends false
    ? Promise<T>
    : S extends ZodType<infer Type>
      ? `Error: Your token requires args: ${Join<
          UnionToArray<keyof Type>,
          ', '
        >}`
      : 'Error: Your token requires args'
  // #4 Token with no Schema
  asyncInject<T>(token: InjectionToken<T, undefined>): Promise<T>
  asyncInject<T>(token: BoundInjectionToken<T, any>): Promise<T>
  asyncInject<T>(token: FactoryInjectionToken<T, any>): Promise<T>
 
  inject<T extends ClassTypeWithoutArguments>(
    token: T,
  ): InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>
  inject<Args, T extends ClassTypeWithArgument<Args>>(
    token: T,
    args: Args,
  ): InstanceType<T>
  inject<
    Schema extends InjectionTokenSchemaType,
    R,
    T extends FactorableWithArgs<R, Schema>,
  >(
    token: T,
    args: z.input<Schema>,
  ): R
 
  inject<T, S extends InjectionTokenSchemaType>(
    token: InjectionToken<T, S>,
    args: z.input<S>,
  ): T
  // #3 Token with optional Schema
  inject<T, S extends InjectionTokenSchemaType, R extends boolean>(
    token: InjectionToken<T, S, R>,
  ): R extends false
    ? T
    : S extends ZodType<infer Type>
      ? `Error: Your token requires args: ${Join<
          UnionToArray<keyof Type>,
          ', '
        >}`
      : 'Error: Your token requires args'
  inject<T>(token: InjectionToken<T, undefined>): T
  inject<T>(token: BoundInjectionToken<T, any>): T
  inject<T>(token: FactoryInjectionToken<T, any>): T
 
  /**
   * Optional injection that returns null if the service fails to initialize
   * or is not available. This is useful when you want to inject a service
   * that may not be configured or may fail gracefully.
   *
   * @example
   * ```ts
   * class MyService {
   *   constructor() {
   *     const optionalService = optional(OptionalServiceToken)
   *     // optionalService will be null if initialization fails
   *     if (optionalService) {
   *       optionalService.doSomething()
   *     }
   *   }
   * }
   * ```
   */
  optional<T extends ClassType>(
    token: T,
  ): (InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>) | null
  optional<T, S extends InjectionTokenSchemaType>(
    token: InjectionToken<T, S>,
    args: z.input<S>,
  ): T | null
  optional<T, S extends InjectionTokenSchemaType, R extends boolean>(
    token: InjectionToken<T, S, R>,
  ): R extends false
    ? T | null
    : S extends ZodType<infer Type>
      ? `Error: Your token requires args: ${Join<
          UnionToArray<keyof Type>,
          ', '
        >}`
      : 'Error: Your token requires args'
  optional<T>(token: InjectionToken<T, undefined>): T | null
  optional<T>(token: BoundInjectionToken<T, any>): T | null
  optional<T>(token: FactoryInjectionToken<T, any>): T | null
 
  wrapSyncInit(
    cb: () => any,
  ): (injectState?: InjectState) => [any, Promise<any>[], InjectState]
 
  provideFactoryContext(
    context: ServiceInitializationContext | null,
  ): ServiceInitializationContext | null
}
 
export function getInjectors() {
  let currentFactoryContext: ServiceInitializationContext | null = null
 
  function provideFactoryContext(
    context: ServiceInitializationContext | null,
  ): ServiceInitializationContext | null {
    const original = currentFactoryContext
    currentFactoryContext = context
    return original
  }
  function getFactoryContext(): ServiceInitializationContext {
    Iif (!currentFactoryContext) {
      throw new Error(
        '[Injector] Trying to access injection context outside of a injectable context',
      )
    }
    return currentFactoryContext
  }
 
  let promiseCollector: null | ((promise: Promise<any>) => void) = null
  let injectState: InjectState | null = null
 
  function getRequest(
    token: InjectionToken<any>,
    args?: unknown,
    skipCycleTracking = false,
  ) {
    Iif (!injectState) {
      throw new Error(
        '[Injector] Trying to make a request outside of a injectable context',
      )
    }
    if (injectState.isFrozen) {
      const idx = injectState.currentIndex++
      const request = injectState.requests[idx]
      Iif (request.token !== token) {
        throw new Error(
          `[Injector] Wrong token order. Expected ${request.token.toString()} but got ${token.toString()}`,
        )
      }
      return request
    }
    let result: any = null
    let error: Error | null = null
 
    // For async inject, we run outside the resolution context to skip cycle tracking.
    // This is because asyncInject returns a promise that doesn't block the constructor,
    // so it cannot cause a deadlock even with circular dependencies.
    const doInject = () =>
      getFactoryContext()
        .inject(token as any, args as any)
        .then((r) => {
          result = r
          return r
        })
        .catch((e) => {
          // We don't throw here because we have a mechanism to handle errors
          error = e
        })
 
    const promise = skipCycleTracking
      ? withoutResolutionContext(doInject)
      : doInject()
 
    const request: InjectRequest = {
      token,
      promise,
      get result() {
        return result
      },
      get error() {
        return error
      },
    }
    injectState.requests.push(request)
    injectState.currentIndex++
 
    return request
  }
 
  function asyncInject(
    token:
      | ClassType
      | InjectionToken<any>
      | BoundInjectionToken<any, any>
      | FactoryInjectionToken<any, any>,
    args?: unknown,
  ) {
    if (!injectState) {
      throw new Error(
        '[Injector] Trying to access inject outside of a injectable context',
      )
    }
    // @ts-expect-error In case we have a class
    const realToken = token[InjectableTokenMeta] ?? token
    // Pass skipCycleTracking=true because asyncInject returns a promise that doesn't
    // block the constructor, so it cannot cause a deadlock even with circular dependencies.
    const request = getRequest(realToken, args, true)
    return request.promise.then((result) => {
      Iif (request.error) {
        // We throw here because we want to fail the asyncInject call if the dependency fails to initialize
        throw request.error
      }
      return result
    })
  }
 
  function wrapSyncInit(cb: () => any) {
    return (previousState?: InjectState) => {
      const promises: Promise<any>[] = []
      const originalPromiseCollector = promiseCollector
      const originalInjectState = injectState
      injectState = previousState
        ? {
            ...previousState,
            currentIndex: 0,
          }
        : {
            currentIndex: 0,
            isFrozen: false,
            requests: [],
          }
      promiseCollector = (promise) => {
        promises.push(promise)
      }
      const result = cb()
      promiseCollector = originalPromiseCollector
      const newInjectState = {
        ...injectState,
        isFrozen: true,
      }
      injectState = originalInjectState
      return [result, promises, newInjectState]
    }
  }
 
  function inject<
    T,
    Token extends
      | InjectionToken<T>
      | BoundInjectionToken<T, any>
      | FactoryInjectionToken<T, any>,
    S extends ZodObject | unknown = Token['schema'],
  >(token: Token, args?: S extends ZodObject ? z.input<S> : never): T {
    // @ts-expect-error In case we have a class
    const realToken = token[InjectableTokenMeta] ?? token
 
    if (!injectState) {
      throw new Error(
        '[Injector] Trying to access inject outside of a injectable context',
      )
    }
 
    // Try to get cached instance synchronously (only on first run, not frozen replay)
    const ctx = getFactoryContext()
    const cachedInstance = !injectState.isFrozen
      ? ctx.container.tryGetSync(realToken, args)
      : null
 
    // getRequest handles both frozen replay and first run:
    // - Frozen: validates token order and returns cached request
    // - First run: creates new request with ctx.inject promise
    const request = getRequest(realToken, args)
 
    // If we have a cached instance, return it directly
    if (cachedInstance) {
      return cachedInstance as unknown as T
    }
 
    // Check for errors or already-resolved results
    if (request.error) {
      throw request.error
    }
    if (request.result) {
      return request.result as T
    }
 
    // Collect promise for awaiting (first run only, frozen state already has results)
    Eif (promiseCollector && !injectState.isFrozen) {
      promiseCollector(request.promise)
    }
 
    // Return a proxy that throws if accessed before initialization
    return new Proxy(
      {},
      {
        get() {
          throw new Error(
            `[Injector] Trying to access ${realToken.toString()} before it's initialized, please move the code to a onServiceInit method`,
          )
        },
      },
    ) as unknown as T
  }
 
  function optional<
    T,
    Token extends
      | InjectionToken<T>
      | BoundInjectionToken<T, any>
      | FactoryInjectionToken<T, any>,
    S extends ZodObject | unknown = Token['schema'],
  >(token: Token, args?: S extends ZodObject ? z.input<S> : never): T | null {
    try {
      return inject(token, args)
    } catch {
      // If injection fails, return null instead of throwing
      return null
    }
  }
 
  const injectors: Injectors = {
    asyncInject,
    inject,
    optional,
    wrapSyncInit,
    provideFactoryContext,
  } as Injectors
 
  return injectors
}