lockfile.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Lazy accessor for proper-lockfile.
  3. *
  4. * proper-lockfile depends on graceful-fs, which monkey-patches every fs
  5. * method on first require (~8ms). Static imports of proper-lockfile pull this
  6. * cost into the startup path even when no locking happens (e.g. `--help`).
  7. *
  8. * Import this module instead of `proper-lockfile` directly. The underlying
  9. * package is only loaded the first time a lock function is actually called.
  10. */
  11. import type { CheckOptions, LockOptions, UnlockOptions } from 'proper-lockfile'
  12. type Lockfile = typeof import('proper-lockfile')
  13. let _lockfile: Lockfile | undefined
  14. function getLockfile(): Lockfile {
  15. if (!_lockfile) {
  16. // eslint-disable-next-line @typescript-eslint/no-require-imports
  17. _lockfile = require('proper-lockfile') as Lockfile
  18. }
  19. return _lockfile
  20. }
  21. export function lock(
  22. file: string,
  23. options?: LockOptions,
  24. ): Promise<() => Promise<void>> {
  25. return getLockfile().lock(file, options)
  26. }
  27. export function lockSync(file: string, options?: LockOptions): () => void {
  28. return getLockfile().lockSync(file, options)
  29. }
  30. export function unlock(file: string, options?: UnlockOptions): Promise<void> {
  31. return getLockfile().unlock(file, options)
  32. }
  33. export function check(file: string, options?: CheckOptions): Promise<boolean> {
  34. return getLockfile().check(file, options)
  35. }