vite: SSR transformed named imported functions don't work with debuggers "step-into"

Describe the bug

Originally reported at https://github.com/vitest-dev/vitest/issues/5569. I think I’ve seen 2-3 similar reports in the past too.

When a file is SSR transformed in Vite, debuggers like Chrome Dev tools and VSCode are unable to “step into” functions that are imported via named imports. In practice this means stopping debugger in line 3 and pressing “step into” button of debuggers in the example below.

1 | import { add } from "./math.ts";
2 |
3 | add(1, 2);

Debugger should stop at line 1 or 2, but instead it stops at 7.

1 | export function add(a: number, b: number): number {
2 |   if (a === 1) {
3 |     return 1;
4 |   }
5 | 
6 |   return a + b;
7 | }
8 |

Source map of the math.ts in reproduction: https://evanw.github.io/source-map-visualization/#NDI2AGZ1bmN0….

Video demonstrating step-into issue with Vite SSR

vite-step-into.webm

I think this has something to do with the way Vite SSR transforms import into import() and saves the results into single variable. In the reproduction setup I’ve created “Vite simulation”, where SSR transformed file is loaded directly into Node.

In this example “step into” works correctly on lines 11 and 15. If Vite was able to destructure the named imports of __vite_ssr_exports__ into separate variables, I think debuggers would work just fine. But this would break ESM live bindings.

 1 | globalThis.__vite_ssr_exports__ = {};
 2 | debugger;
 3 | 
 4 | await import("./transpiled.js");
 5 | const { add, multiply } = globalThis.__vite_ssr_exports__;
 6 | 
 7 | // Incorrect position when "step into"
 8 | globalThis.__vite_ssr_exports__.add(1, 2);
 9 | 
10 | // Correct position when "stepinto"
11 | add(1, 2);
12 | 
13 | // Same here
14 | globalThis.__vite_ssr_exports__.multiply(1, 2);
15 | multiply(1, 2);
16 |
Video showing how lines 11 and 15 work correctly

node-step-into.webm

Reproduction

https://github.com/AriPerkkio/vite-ssr-transform-sourcemaps-issue

Steps to reproduce

See README https://github.com/AriPerkkio/vite-ssr-transform-sourcemaps-issue/blob/main/README.md.

System Info

System:
    OS: macOS 15.0.1
    CPU: (8) arm64 Apple M2
    Memory: 471.58 MB / 16.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 20.17.0 - ~/.nvm/versions/node/v20.17.0/bin/node
    Yarn: 1.22.22 - ~/.nvm/versions/node/v20.17.0/bin/yarn
    npm: 10.8.2 - ~/.nvm/versions/node/v20.17.0/bin/npm
    pnpm: 8.15.9 - ~/.nvm/versions/node/v20.17.0/bin/pnpm
  Browsers:
    Chrome: 129.0.6668.91
    Safari: 18.0.1

Used Package Manager

pnpm

Logs

No response

Validations

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 1
  • Comments: 31 (20 by maintainers)

Most upvoted comments

There’s also one big inconvenience with debugging related to the SSR transformations – inability to evaluate code that includes imported modules.

For example,

import { hello, bye } from 'module';

const debuggingThis = () => {
  const res = hello() + bye();
  // breakpoint
}

If res has unexpected value, I normally would want evaluate hello() and bye() to see what they return to make sense of the res value. However, they are not defined, as they live in the __vite_ssr_import_0__.hello and __vite_ssr_import_0__.bye.

Maybe we can use C++ API directly 🤔

I guess no. That feature is not exposed in Node API (I’m not sure which feature you are referring to, but probably) and other APIs exposed from Node does not have a stable ABI. That means we’ll have to compile the lib for each Node version, otherwise the users has to compile it. Even if we compile it for each version, AFAIK there’s no way to do optional dependencies based on Node version, so all versions will have to be downloaded (unless we do it on our own with postinstall script).

I think I found solution that works identical to ESM in Node.js (not in stackblitz for some reason - looks like they are using a vite-node like wrapper to import 😄 )

https://stackblitz.com/edit/node-7j9afi?file=test.js

Running this code in Node.js shows the same values for the native ESM module and the proxy+wrapper. One caveat - to make this work, we need to know all exports before we execute the code (we can just return them alongside dependencies)

// exports are statically known, fill the object before executing the code
const __vite_ssr_exports__ = {
  a: undefined,
  __proto__: null,
};
Object.defineProperty(__vite_ssr_exports__, Symbol.toStringTag, {
  enumerable: false,
  writable: false,
  configurable: false,
  value: 'Module',
});

const __vite_ssr_namespace__ = new Proxy(__vite_ssr_exports__, {
  set(target, p) {
    const key = String(p);
    if (!Reflect.has(target, p)) {
      throw new TypeError(
        `Cannot add property ${key}, object is not extensible`
      );
    }
    throw new TypeError(
      `Cannot assign to read only property '${key}' of object 'Module'`
    );
  },
});

// this also seals the __vite_ssr_exports__, but sealed objects CAN override values
Object.seal(__vite_ssr_namespace__);
// this is LEGAL and the only LEGAL way to reassign values
// we can call this INSIDE the module
__vite_ssr_exports__.a = 123;
// this is NOT LEGAL (because of the proxy),
// this is the module exposed to the user
__vite_ssr_namespace__.a = 123;

// this returns descriptors ACCORDING to the MDN (writable: true)
console.log(Object.getOwnPropertyDescriptors(__vite_ssr_namespace__))

The new algorithm would be something like this:

  • Parse and transform the file as usual, but
    • Keep a record of all exports
    • Use = assignment to assign values instead of Object.defineProperty because the module will be sealed before the values are assigned at runtime
    • Add reassignments of __vite_ssr_exports__.${method} when the export is reassigned
    • Instead of using __vite_ssr_identity__ use (0, method)()
  • Create the __vite_ssr_exports__ objects with all exported properties assigned to undefined (we kept the record of all exports) and sort them
  • Create a public proxy __vite_ssr_namespace__ that throws an error if someone attempts to assign a value
  • __vite_ssr_import__ now returns __vite_ssr_namespace__ instead of __vite_ssr_exports__ for public usage

Benchmark-wise it seems to be the slowest one 😄 (Even slower than getters, even though we don’t define a get method on a proxy). Property access seems to be on par with reassignment (I recommend running benchmarks locally and not on stackblitz because it messes with imports):

Screenshot 2024-11-21 at 18 43 19

In real-world scenarios using the module runner, it makes it around ~4 mil operations slower:

Screenshot 2024-11-21 at 20 45 56

const server = await createServer({
  root: process.cwd(),
})

const AsyncFunction = async function () {}.constructor as typeof Function

class MyEvaluator {
  startOffset: number
  runExternalModule: (url: string) => Promise<any>

  constructor() {
    const evaluator = new ESModulesEvaluator()
    this.runExternalModule = evaluator.runExternalModule.bind(evaluator)
    this.startOffset = evaluator.startOffset
  }

  async runInlinedModule(context: ModuleRunnerContext, code: string, module: EvaluatedModuleNode): Promise<any> {
    context[ssrModuleExportsKey].squared = undefined
    const __vite_ssr_namespace__ = new Proxy(context[ssrModuleExportsKey], {
      set(target, p) {
        const key = String(p);
        if (!Reflect.has(target, p)) {
          throw new TypeError(
            `Cannot add property ${key}, object is not extensible`
          );
        }
        throw new TypeError(
          `Cannot assign to read only property '${key}' of object 'Module'`
        );
      },
    });
    module.exports = __vite_ssr_namespace__
    Object.seal(__vite_ssr_namespace__)
    const transform = code.replace('Object.defineProperty(__vite_ssr_exports__, "squared", { enumerable: true, configurable: true, get(){ return squared }});', '__vite_ssr_exports__.squared = squared;')
    console.log(transform)
    // use AsyncFunction instead of vm module to support broader array of environments out of the box
    const initModule = new AsyncFunction(
      ssrModuleExportsKey,
      ssrImportMetaKey,
      ssrImportKey,
      ssrDynamicImportKey,
      ssrExportAllKey,
      // source map should already be inlined by Vite
      '"use strict";' + transform,
    )

    await initModule(
      context[ssrModuleExportsKey],
      context[ssrImportMetaKey],
      context[ssrImportKey],
      context[ssrDynamicImportKey],
      context[ssrExportAllKey],
    )
  }
}

class OverrideModuleRunner extends ModuleRunner {
  override async directRequest(
    url: string,
    mod: EvaluatedModuleNode,
    _callstack: string[],
  ) {
    await super.directRequest(url, mod, _callstack)
    return mod.exports
  }
}

const createServerModuleRunnerTransport = (options: {
  channel: any
}): ModuleRunnerTransport => {
  const hmrClient: HotChannelClient = {
    send: (payload: HotPayload) => {
      if (payload.type !== 'custom') {
        throw new Error(
          'Cannot send non-custom events from the client to the server.',
        )
      }
      options.channel.send!(payload)
    },
  }

  let handler: ((data: HotPayload) => void) | undefined

  return {
    connect({ onMessage }) {
      options.channel.api!.outsideEmitter.on('send', onMessage)
      onMessage({ type: 'connected' })
      handler = onMessage
    },
    disconnect() {
      if (handler) {
        options.channel.api!.outsideEmitter.off('send', handler)
      }
    },
    send(payload) {
      if (payload.type !== 'custom') {
        throw new Error(
          'Cannot send non-custom events from the server to the client.',
        )
      }
      options.channel.api!.innerEmitter.emit(
        payload.event,
        payload.data,
        hmrClient,
      )
    },
  }
}

const runner = new OverrideModuleRunner(
  {
    root: server.config.root,
    transport: createServerModuleRunnerTransport({
      channel: server.environments.ssr.hot
    })
  },
  new MyEvaluator()
)

const defaultRunner = createServerModuleRunner(server.environments.ssr)

const module = await runner.import('/basic.mjs')

bench(
  'proxy-access',
  () => {
    module.squared(2)
  },
  config
);

const module2 = await defaultRunner.import('/basic.mjs')

bench(
  'direct-access',
  () => {
    module2.squared(2);
  },
  config
);

Just a note: internally, module namespace exports are defined as getters/setters: https://github.com/nodejs/node/blob/main/deps/v8/src/builtins/accessors.cc#L265