Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@
},
"dependencies": {
"chalk": "4",
"chalk-template": "^1.1.0",
"clipcc-extension": "^0.2.0"
}
}
}
117 changes: 73 additions & 44 deletions src/native/plugins.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,78 @@
import { Linter } from 'eslint';
import fs from 'fs';
import { ExtendWebpackConfig, NativePlugin } from './structs/plugin';
import path from 'path';
import { Configuration } from 'webpack';
import chalkTemplate from 'chalk-template';
import { Linter } from "eslint";
import fs from "fs";
import { ExtendWebpackConfig, NativePlugin } from "./structs/plugin";
import path from "path";
import { Configuration } from "webpack";
import chalk from "chalk";

export function load() {
console.log(`Mode: ${process.env.NODE_ENV === 'production' ? 'production' : 'development'}`);
const disablePlugins = JSON.parse(fs.readFileSync(path.join(__dirname, '../../plugins/disable.json'), 'utf-8')) as Record<'platform' | 'folder', string[]>;
const webpack: Record<string, (config: ExtendWebpackConfig) => Configuration> = {};
const eslint: Linter.Config[] = [];
const pluginsDir = path.join(__dirname, '../../plugins');
const pluginFolders = fs.readdirSync(pluginsDir)
.filter(file => fs.statSync(path.join(pluginsDir, file)).isDirectory());
const pluginIds: string[] = [];
function pad(id: string) {
return id.padEnd(Math.max(...pluginIds.map(id => id.length)), ' ');
console.log(
`Mode: ${
process.env.NODE_ENV === "production" ? "production" : "development"
}`
);
const disablePlugins = JSON.parse(
fs.readFileSync(path.join(__dirname, "../../plugins/disable.json"), "utf-8")
) as Record<"platform" | "folder", string[]>;
const webpack: Record<
string,
(config: ExtendWebpackConfig) => Configuration
> = {};
const eslint: Linter.Config[] = [];
const pluginsDir = path.join(__dirname, "../../plugins");
const pluginFolders = fs
.readdirSync(pluginsDir)
.filter((file) => fs.statSync(path.join(pluginsDir, file)).isDirectory());
const pluginIds: string[] = [];
function pad(id: string) {
return id.padEnd(Math.max(...pluginIds.map((id) => id.length)), " ");
}
for (const folder of pluginFolders) {
pluginIds.push(folder);
}
for (const folder of pluginFolders) {
const currentNativeId = folder;
if (disablePlugins.folder.includes(currentNativeId)) {
console.log(
`${chalk.gray(pad(currentNativeId))} | ${chalk.red("DISABLED")}`
);
continue;
}
for (const folder of pluginFolders) {
pluginIds.push(folder);
}
for (const folder of pluginFolders) {
const currentNativeId = folder;
if (disablePlugins.folder.includes(currentNativeId)) {
console.log(chalkTemplate`{gray ${pad(currentNativeId)}} | {red DISABLED}`);
continue;
}
try {
const nativePath = path.resolve('dist/native/plugins', folder, 'native.js');
if (fs.existsSync(nativePath)) {
const { default: plugin }: { default: NativePlugin } = require(nativePath);
if (disablePlugins.platform.includes(plugin.platform)) {
console.log(chalkTemplate`{gray ${pad(plugin.platform)}} | {red DISABLED}`);
continue;
}
webpack[currentNativeId] = plugin.configureWebpack?.call(plugin) ?? (() => ({}));
eslint.push(...(plugin.configureESLint?.call(plugin) ?? []));
console.log(chalkTemplate`{gray ${pad(currentNativeId)}} | {green loaded successfully}: {cyan ${plugin.platform}}.`);
} else {
webpack[currentNativeId] = () => ({});
console.warn(chalkTemplate`{gray ${pad(currentNativeId)}} | {yellow not found native module}.`);
}
} catch (err) {
console.error(chalkTemplate`{gray ${pad(currentNativeId)}} | {red ${err}}`);
try {
const nativePath = path.resolve(
"dist/native/plugins",
folder,
"native.js"
);
if (fs.existsSync(nativePath)) {
const {
default: plugin,
}: { default: NativePlugin } = require(nativePath);
if (disablePlugins.platform.includes(plugin.platform)) {
console.log(
`${chalk.gray(pad(plugin.platform))} | ${chalk.red("DISABLED")}`
);
continue;
}
webpack[currentNativeId] =
plugin.configureWebpack?.call(plugin) ?? (() => ({}));
eslint.push(...(plugin.configureESLint?.call(plugin) ?? []));
console.log(
`${chalk.gray(pad(currentNativeId))} | ${chalk.green(
"loaded successfully"
)}: ${chalk.cyan(plugin.platform)}.`
);
} else {
webpack[currentNativeId] = () => ({});
console.warn(
`${chalk.gray(pad(currentNativeId))} | ${chalk.yellow(
"not found native module"
)}.`
);
}
} catch (err) {
console.error(`${chalk.gray(pad(currentNativeId))} | ${chalk.red(err)}`);
}
return { webpack, eslint };
}
}
return { webpack, eslint };
}
79 changes: 28 additions & 51 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,52 +1,29 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"allowJs": true,
"checkJs": true,
"isolatedModules": true,
"resolveJsonModule": true,
"typeRoots": [
"node_modules/@types",
"node_modules/@turbowarp/types"
],
"types": [
"webpack-env",
"node",
"index.d.ts"
],
"baseUrl": ".",
"outDir": "dist/native",
"paths": {
"fs-context": [
"src/fs-context/index"
],
"package.json": [
"package.json"
],
"fs-context/*": [
"src/fs-context/*"
],
"@/*": [
"src/extension/*"
],
"@sample/*": [
"src/fs-context/samples/*"
],
"@plugin/*": [
"plugins/*"
]
}
},
"include": [
"src/**/*.ts",
"plugins/**/*.ts",
"plugins/disable.json"
]
}
"compilerOptions": {
"target": "ESNext",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"allowJs": true,
"checkJs": true,
"isolatedModules": true,
"resolveJsonModule": true,
"typeRoots": ["node_modules/@types", "node_modules/@turbowarp/types"],
"types": ["webpack-env", "node", "index.d.ts"],
"baseUrl": ".",
"outDir": "dist/native",
"paths": {
"fs-context": ["src/fs-context/index"],
"package.json": ["package.json"],
"fs-context/*": ["src/fs-context/*"],
"@/*": ["src/extension/*"],
"@sample/*": ["src/fs-context/samples/*"],
"@plugin/*": ["plugins/*"]
}
},
"include": ["src/**/*.ts", "plugins/**/*.ts", "plugins/disable.json"]
}
158 changes: 85 additions & 73 deletions webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,90 @@
const path = require('path');
const webpack = require('webpack');
const path = require("path");
const webpack = require("webpack");

const Webpackbar = require('webpackbar');
const Webpackbar = require("webpackbar");

const tsconfigJson = require('./tsconfig.json');
const packageJson = require('./package.json');
const { merge } = require('webpack-merge');
const tsconfigJson = require("./tsconfig.json");
const packageJson = require("./package.json");
const { merge } = require("webpack-merge");

module.exports = () => {
const { webpack: webpackConfig } = require('./dist/native/src/native/plugins').load();
return packageJson.extension.platform.map((platform) => {
const filename = `[${platform}]${packageJson.extension.id}@${packageJson.extension.version}.js`;
const base = {
name: platform,
entry: 'fs-context/entry.ts',
resolve: {
extensions: ['.js', '.ts'],
alias: Object.fromEntries(
Object.entries(tsconfigJson.compilerOptions.paths)
.map(([key, value]) => [key.replace('/*', ''), path.resolve(__dirname, value[0].replace('/*', ''))])
)
},
output: {
path: path.resolve(__dirname, 'dist'),
filename
},
module: {
rules: [
{
test: /\.ts$/i,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
plugins: [
new Webpackbar({
name: packageJson.extension.name.toUpperCase(),
color: 'green'
}),
new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
new webpack.DefinePlugin({
fsContext: JSON.stringify({
platform,
developing: process.env.NODE_ENV === 'development',
extension: packageJson.extension
})
})
],
/**
* @type {import('webpack-dev-server').Configuration}
*/
devServer: {
port: 7777,
setupExitSignals: false,
webSocketServer: false,
client: {
logging: 'none'
},
setupMiddlewares(mw, server) {
server.app.get('/', (_, res) => {
res.redirect(`/${filename}`);
});
return mw;
},
allowedHosts: 'all'
},
mode: process.env.NODE_ENV,
stats: 'errors-warnings'
};
return merge(base, webpackConfig[platform]({ filename, base }) ?? {}, {
plugins: [
//pass
const { webpack: webpackConfig } =
require("./dist/native/src/native/plugins").load();
return packageJson.extension.platform.map((platform) => {
const filename = `[${platform}]${packageJson.extension.id}@${packageJson.extension.version}.js`;
const base = {
name: platform,
entry: "fs-context/entry.ts",
resolve: {
extensions: [".js", ".ts"],
alias: Object.fromEntries(
Object.entries(tsconfigJson.compilerOptions.paths).map(
([key, value]) => [
key.replace("/*", ""),
path.resolve(__dirname, value[0].replace("/*", "")),
]
});
})
};
)
),
},
output: {
path: path.resolve(__dirname, "dist"),
filename,
},
module: {
rules: [
{
test: /\.ts$/i,
use: "ts-loader",
exclude: /node_modules/,
},
],
},
plugins: [
new Webpackbar({
name: packageJson.extension.name.toUpperCase(),
color: "green",
}),
new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
new webpack.DefinePlugin({
fsContext: JSON.stringify({
platform,
developing: process.env.NODE_ENV === "development",
extension: packageJson.extension,
}),
}),
],
/**
* @type {import('webpack-dev-server').Configuration}
*/
devServer: {
port: 7777,
setupExitSignals: false,
webSocketServer: false,
client: {
logging: "none",
},
setupMiddlewares(mw, server) {
server.app.get("/", (_, res) => {
res.redirect(`/${filename}`);
});
return mw;
},
allowedHosts: "all",
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods":
"GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers":
"X-Requested-With, content-type, Authorization",
},
},
mode: process.env.NODE_ENV,
stats: "errors-warnings",
};
return merge(base, webpackConfig[platform]({ filename, base }) ?? {}, {
plugins: [
//pass
],
});
});
};
Loading