Skip to content

Commit

Permalink
fix: edge case
Browse files Browse the repository at this point in the history
  • Loading branch information
Wxh16144 committed Apr 11, 2024
1 parent 6072519 commit e883a73
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 16 deletions.
2 changes: 1 addition & 1 deletion src/features/compile/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default (api: IApi) => {
extraRehypePlugins: api.config.extraRehypePlugins,
routes: api.appData.routes,
locales: api.config.locales,
pkg: api.pkg,
pkgPath: api.pkgPath,
};

memo.module
Expand Down
19 changes: 12 additions & 7 deletions src/features/theme/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import {
VERSION_2_LEVEL_NAV,
} from '@/constants';
import type { IApi } from '@/types';
import { getPackageVersionFromDependency, isVersionInRange } from '@/utils';
import { parseModule } from '@umijs/bundler-utils';
import { execSync } from 'child_process';
import fs from 'fs';
import hostedGit from 'hosted-git-info';
import path from 'path';
import { deepmerge, lodash, resolve, semver, winPath } from 'umi/plugin-utils';
import { deepmerge, lodash, resolve, winPath } from 'umi/plugin-utils';
import { safeExcludeInMFSU } from '../derivative';
import loadTheme, { IThemeLoadResult } from './loader';

Expand Down Expand Up @@ -79,14 +80,18 @@ async function getModuleExports(modulePath: string) {
/**
* check if package dumi version is minor 2
*/
function checkMinor2ByPkg(pkg: IApi['pkg']) {
function checkMinor2ByPkg(pkgPath: string) {
const pkg = require(pkgPath);

// for dumi local example project
if (pkg.name?.startsWith('@examples/')) return true;

const ver =
pkg.peerDependencies?.dumi || pkg.devDependencies?.dumi || '^2.0.0';
const dumiVer = getPackageVersionFromDependency(pkgPath, 'dumi', [
'peer',
'dev',
]);

return semver.subset(ver, VERSION_2_LEVEL_NAV);
return isVersionInRange(dumiVer, VERSION_2_LEVEL_NAV);
}

export default (api: IApi) => {
Expand Down Expand Up @@ -176,12 +181,12 @@ export default (api: IApi) => {
api.modifyAppData((memo) => {
// auto enable 2-level nav by declared dumi version, for existing projects compatibility
// ref: https://github.com/umijs/dumi/discussions/1618
memo._2LevelNavAvailable = checkMinor2ByPkg(api.pkg);
memo._2LevelNavAvailable = checkMinor2ByPkg(api.pkgPath);

// always respect theme package declaration, for theme compatibility
if (pkgThemePath && !memo._2LevelNavAvailable) {
memo._2LevelNavAvailable = checkMinor2ByPkg(
require(path.join(pkgThemePath, 'package.json')),
path.join(pkgThemePath, 'package.json'),
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/loaders/markdown/transformer/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ for (let casePath of cases) {
},
locales: [],
routes: {},
pkg: {},
pkgPath: '',
alias: {
'@': __dirname,
},
Expand Down
17 changes: 11 additions & 6 deletions src/loaders/markdown/transformer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import type { IParsedBlockAsset } from '@/assetParsers/block';
import type { ILocalesConfig, IRouteMeta } from '@/client/theme-api/types';
import { VERSION_2_DEPRECATE_SOFT_BREAKS } from '@/constants';
import type { IApi, IDumiConfig, IDumiTechStack } from '@/types';
import { getPackageVersionFromDependency, isVersionInRange } from '@/utils';
import enhancedResolve from 'enhanced-resolve';
import type { IRoute } from 'umi';
import { semver } from 'umi/plugin-utils';
import type { Plugin, Processor } from 'unified';
import type { Data } from 'vfile';
import rehypeDemo from './rehypeDemo';
Expand Down Expand Up @@ -67,7 +67,7 @@ export interface IMdTransformerOptions {
extraRehypePlugins?: IDumiConfig['extraRehypePlugins'];
routes: Record<string, IRoute>;
locales: ILocalesConfig;
pkg: IApi['pkg'];
pkgPath: IApi['pkgPath'];
}

export interface IMdTransformerResult {
Expand All @@ -78,12 +78,17 @@ export interface IMdTransformerResult {
/**
* keep markdown soft break before 2.2.0
*/
function keepSoftBreak(pkg: IApi['pkg']) {
function keepSoftBreak(pkgPath: string) {
const pkg = require(pkgPath);
// for dumi local example project
if (pkg?.name?.startsWith('@examples/') || pkg?.name === 'dumi') return false;

const ver = pkg?.devDependencies?.dumi ?? pkg?.dependencies?.dumi ?? '^2.0.0';
return !semver.subset(ver, VERSION_2_DEPRECATE_SOFT_BREAKS);
const dumiVer = getPackageVersionFromDependency(pkgPath, 'dumi', [
'dev',
'prod',
]);

return !isVersionInRange(dumiVer, VERSION_2_DEPRECATE_SOFT_BREAKS);
}

async function applyUnifiedPlugin(opts: {
Expand Down Expand Up @@ -143,7 +148,7 @@ export default async (raw: string, opts: IMdTransformerOptions) => {
.use(remarkContainer)
.use(remarkGfm);

if (keepSoftBreak(opts.pkg)) {
if (keepSoftBreak(opts.pkgPath)) {
processor.use(remarkBreaks, { fileAbsPath: opts.fileAbsPath });
}

Expand Down
57 changes: 56 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import type { Range, RangeOptions } from '@umijs/utils/compiled/semver';
import { createHash } from 'crypto';
import Cache from 'file-system-cache';
import fs from 'fs';
import yaml from 'js-yaml';
import path from 'path';
import { lodash, logger, winPath } from 'umi/plugin-utils';
import { lodash, logger, resolve, semver, winPath } from 'umi/plugin-utils';
import { FS_CACHE_DIR } from './constants';

/**
Expand Down Expand Up @@ -168,3 +169,57 @@ export function getProjectRoot(cwd: string) {
export function getContentHash(content: string, length = 8) {
return createHash('md5').update(content).digest('hex').slice(0, length);
}

/**
* get package version from dependency
* @param pkgPath package.json file path
*/
export function getPackageVersionFromDependency(
pkgPath: string,
pkgName: string,
category: Array<'peer' | 'dev' | 'prod'> = ['prod'],
) {
const pkg = fs.existsSync(pkgPath) ? require(pkgPath) : null;

if (!pkg || pkgName.length < 1) return null;

let depVer = null;
for (const cat of category) {
const depsCategory = cat === 'prod' ? 'dependencies' : `${cat}Dependencies`;
depVer = lodash.get(pkg, [depsCategory, pkgName]);
if (depVer) break;
}

if (!depVer) return null;

if (semver.valid(depVer) || semver.validRange(depVer)) {
return depVer;
}

const depJson = resolve.sync(`${pkgName}/package.json`, {
basedir: path.dirname(pkgPath),
});
if (fs.existsSync(depJson)) {
const depPkg = require(depJson);
return depPkg?.version;
}
}

/**
* check if version is in range
* @param version version to check
* @param range range to check
*/
export function isVersionInRange(
version: string,
range: string | Range,
options: RangeOptions = { includePrerelease: true },
) {
if (semver.valid(version)) {
return semver.satisfies(version, range, options);
}
if (semver.validRange(version)) {
return semver.subset(version, range, options);
}
return false;
}

0 comments on commit e883a73

Please sign in to comment.