enonic / xp

Enonic XP
https://enonic.com
GNU General Public License v3.0
198 stars 34 forks source link

Make the global types importable #10555

Open ComLock opened 1 month ago

ComLock commented 1 month ago

LongTitle: Make the types in @enonic-types/global importable from @enonic-types/core

--

The types in @enonic-types/global are working as intended for Enonic XP server-side code files in src/main/resources/*.ts

However when writing tests the global functions and object must be replaced by mocks. Since the globals are defined as "const" in @enonic-types/global, it's a type error if one tries to replace them.

Changing the type to var (let) is not a good idea since that's actually wrong when it comes to the actual "runtime" types.

My suggestion is to

  1. export the global types in @enonic-types/core
  2. make @enonic-types/global dependant on @enonic-types/core
  3. import the global types from @enonic-types/core into @enonic-types/global and use them to define the const's

Then if I need any of those global types anywhere, I can manually import only the specific ones I need from @enonic-types/core.

One example is when implementing the classes in Mock-XP, I would like to use the type for the global log object as an interface:

import type {Log as LogInterface} from '@enonic-types/core';

export class Log implements LogInterface {
  public debug(...args: unknown[]): void {
    //...
  }
}

The same goes then modifying the type of globalThis when mocking in test files:

import type {Log} from '@enonic-types/core';

declare module globalThis {
   let log: Log
}

log.debug = () => {
  // no-op silence :)
}

I can probably make it even prettier with a local Global Type Library, or a local Global Modifying Module.

But I need the actual types. I don't want to duplicate those types locally. Define once, use everywhere.