importVscode.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Utility for lazy-loading the VS Code module in environments where it's available.
  3. * This allows the SDK to be used in both VS Code extension and Node.js environments.
  4. * Compatible with both VSCode and Cursor extension hosts.
  5. */
  6. let vscodeModule: typeof import("vscode") | undefined
  7. /**
  8. * Attempts to dynamically import the `vscode` module.
  9. * Returns undefined if not running in a VSCode extension context.
  10. */
  11. export async function importVscode(): Promise<typeof import("vscode") | undefined> {
  12. if (vscodeModule) {
  13. return vscodeModule
  14. }
  15. try {
  16. if (typeof require !== "undefined") {
  17. try {
  18. // eslint-disable-next-line @typescript-eslint/no-require-imports
  19. vscodeModule = require("vscode")
  20. if (vscodeModule) {
  21. console.log("VS Code module loaded from require")
  22. return vscodeModule
  23. }
  24. } catch (error) {
  25. console.error(`Error loading VS Code module: ${error instanceof Error ? error.message : String(error)}`)
  26. // Fall through to dynamic import.
  27. }
  28. }
  29. vscodeModule = await import("vscode")
  30. console.log("VS Code module loaded from dynamic import")
  31. return vscodeModule
  32. } catch (error) {
  33. console.warn(
  34. `VS Code module not available in this environment: ${error instanceof Error ? error.message : String(error)}`,
  35. )
  36. return undefined
  37. }
  38. }