vitest.shared.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import ts from 'typescript'
  2. const decoratorSyntax = /^\s*@[A-Za-z_$][\w$]*/m
  3. /**
  4. * Worker arguments that keep process-wide Web Storage from shadowing jsdom storage.
  5. * Node lists the positive spelling in `allowedNodeEnvironmentFlags` for this negatable flag.
  6. */
  7. export const vitestExecArgv = process.allowedNodeEnvironmentFlags.has('--webstorage') ? ['--no-webstorage'] : []
  8. /**
  9. * Transform standard TypeScript decorators before Vite's default parser sees source files.
  10. * @returns a pre-transform Vite plugin shared by source-mode test configurations.
  11. */
  12. export function standardDecoratorPlugin() {
  13. return {
  14. name: 'dsh-standard-decorators',
  15. enforce: 'pre' as const,
  16. transform(code: string, id: string) {
  17. const file = id.split('?', 1)[0]!
  18. if (!/\.[cm]?tsx?$/.test(file) || !decoratorSyntax.test(code)) return
  19. const result = ts.transpileModule(code, {
  20. fileName: file,
  21. compilerOptions: {
  22. target: ts.ScriptTarget.ES2024,
  23. module: ts.ModuleKind.ESNext,
  24. jsx: file.endsWith('x') ? ts.JsxEmit.ReactJSX : undefined,
  25. sourceMap: true,
  26. },
  27. })
  28. return {
  29. code: result.outputText
  30. .replace(
  31. /^(\s*)(__esDecorate\()/gmu,
  32. '$1/* v8 ignore next -- compiler-synthetic decorator accessors have no source behavior */ $2',
  33. )
  34. .replace(/\n?\/\/# sourceMappingURL=.*$/u, '\n'),
  35. map: result.sourceMapText,
  36. }
  37. },
  38. }
  39. }