Spaces:
Paused

File size: 1,852 Bytes
3246b69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * 自定义 ESM Loader
 * 1. 自动为无扩展名的相对导入添加 .js 后缀
 * 2. 将 Cloudflare 特定的包重定向到本地 mock
 */

import { fileURLToPath, pathToFileURL } from 'url';
import { existsSync } from 'fs';
import { dirname, resolve as pathResolve } from 'path';

// Mock 文件路径
const __dirname = dirname(fileURLToPath(import.meta.url));
const MOCKS = {
    '@cloudflare/pages-plugin-sentry': pathResolve(__dirname, 'mocks/sentry-plugin.js'),
    '@sentry/tracing': pathResolve(__dirname, 'mocks/sentry-tracing.js'),
};

export async function resolve(specifier, context, nextResolve) {
    // 拦截 Cloudflare 特定的包
    if (MOCKS[specifier]) {
        return {
            url: pathToFileURL(MOCKS[specifier]).href,
            shortCircuit: true,
        };
    }

    // 处理无扩展名的相对导入
    if (specifier.startsWith('.') && !hasExtension(specifier)) {
        const parentDir = context.parentURL
            ? dirname(fileURLToPath(context.parentURL))
            : process.cwd();

        // 尝试添加 .js 扩展名
        const withJs = pathResolve(parentDir, specifier + '.js');
        if (existsSync(withJs)) {
            return {
                url: pathToFileURL(withJs).href,
                shortCircuit: true,
            };
        }

        // 尝试作为目录的 index.js
        const indexJs = pathResolve(parentDir, specifier, 'index.js');
        if (existsSync(indexJs)) {
            return {
                url: pathToFileURL(indexJs).href,
                shortCircuit: true,
            };
        }
    }

    return nextResolve(specifier, context);
}

function hasExtension(specifier) {
    const lastSlash = specifier.lastIndexOf('/');
    const filename = lastSlash >= 0 ? specifier.slice(lastSlash + 1) : specifier;
    return filename.includes('.');
}