vendorin
Version:
Vendor ES modules locally from esm.sh CDN - no more node_modules!
94 lines (79 loc) • 2.65 kB
JavaScript
import { createRequire } from 'node:module';
import * as fs from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import {
default as init,
initializeTreeSitter,
setupParser,
findNodes,
} from 'ast-grep-wasm';
const { readFile } = fs;
// Create require function for loading CommonJS modules in ESM
const require = createRequire(import.meta.url);
// Mock global require to debug what's being required
if (true) {
// console.log('🔍 Setting up global require mock for debugging...');
global.require = function (id) {
// console.log(`📦 REQUIRE CALL: "${id}"`);
try {
if (id === 'fs/promises') {
// console.log(`✅ REQUIRE REPLACE: "${id}"`);
return fs;
}
const result = require(id);
// console.log(`✅ REQUIRE SUCCESS: "${id}"`);
return result;
} catch (error) {
// console.log(`❌ REQUIRE FAILED: "${id}" - ${error.message}`);
throw error;
}
};
// Copy require properties
Object.setPrototypeOf(global.require, require);
Object.assign(global.require, require);
}
let isInitialized = false;
/**
* Resolve WASM file path using Node.js module resolution
*/
function resolveWasmPath(packageName, wasmFile) {
try {
// Use require.resolve to find the package
const packagePath = require.resolve(packageName + '/package.json');
const packageDir = dirname(packagePath);
return join(packageDir, wasmFile);
} catch (error) {
throw new Error(`Could not resolve WASM file for ${packageName}: ${error.message}`);
}
}
/**
* Initialize ast-grep WASM module
*/
export async function initializeAstGrep() {
if (isInitialized) return;
try {
// Resolve WASM files using Node.js module resolution
const wasmPath = resolveWasmPath('ast-grep-wasm', 'ast_grep_wasm_bg.wasm');
const jsParserPath = resolveWasmPath('tree-sitter-javascript', 'tree-sitter-javascript.wasm');
// Read WASM file as buffer and initialize the module
const wasmBuffer = await readFile(wasmPath);
await init({ module_or_path: wasmBuffer });
// Initialize TreeSitter
await initializeTreeSitter();
// Setup JavaScript parser
await setupParser('javascript', jsParserPath);
isInitialized = true;
// console.log('✅ ast-grep WASM initialized successfully');
} catch (error) {
console.error('❌ Failed to initialize ast-grep WASM:', error);
throw error;
}
}
/**
* Parse JavaScript source code and return root node
*/
export async function transform(source, config) {
await initializeAstGrep();
return findNodes(source, [config]);
}