package-metadata.ts 684 B

1234567891011121314151617181920212223
  1. import { readFileSync } from 'node:fs';
  2. interface PackageMetadata {
  3. version?: unknown;
  4. }
  5. /** Read the installed plugin version from the package shipped with this code. */
  6. export function readPluginPackageVersion(): string | undefined {
  7. for (const packageUrl of [
  8. new URL('../../package.json', import.meta.url),
  9. new URL('../package.json', import.meta.url),
  10. ]) {
  11. try {
  12. const metadata = JSON.parse(
  13. readFileSync(packageUrl, 'utf8'),
  14. ) as PackageMetadata;
  15. if (typeof metadata.version === 'string') return metadata.version;
  16. } catch {
  17. // Try the next package location for source and bundled execution.
  18. }
  19. }
  20. return undefined;
  21. }