Commit fa1b934f authored by nanahira's avatar nanahira

first

parents
Pipeline #40619 passed with stages
in 2 minutes and 15 seconds
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
.git*
Dockerfile
.dockerignore
/tests
/script*
\ No newline at end of file
webpack.config.js
dist/*
build/*
*.js
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir : __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
/script*
\ No newline at end of file
stages:
- install
- build
- deploy
variables:
GIT_DEPTH: "1"
npm_ci:
stage: install
tags:
- linux
script:
- npm ci
artifacts:
paths:
- node_modules
.build_base:
stage: build
tags:
- linux
dependencies:
- npm_ci
build:
extends: .build_base
script: npm run build
artifacts:
paths:
- dist/
upload_to_minio:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- aws s3 --endpoint=https://minio.momobako.com:9000 sync --delete dist/ s3://nanahira/path
only:
- master
stages:
- build
- deploy
variables:
GIT_DEPTH: "1"
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
.build-image:
stage: build
script:
- docker build --pull -t $TARGET_IMAGE .
- docker push $TARGET_IMAGE
build-x86:
extends: .build-image
tags:
- docker
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-x86
build-arm:
extends: .build-image
tags:
- docker-arm
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-arm
.deploy:
stage: deploy
tags:
- docker
script:
- docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-x86
- docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-arm
- docker manifest create $TARGET_IMAGE --amend $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-x86 --amend
$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-arm
- docker manifest push $TARGET_IMAGE
deploy_latest:
extends: .deploy
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:latest
only:
- master
deploy_branch:
extends: .deploy
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
/coverage
/tests
/dist/tests
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
FROM node:lts-bookworm-slim as base
LABEL Author="Nanahira <nanahira@momobako.com>"
RUN apt update && apt -y install python3 build-essential && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /var/log/*
WORKDIR /usr/src/app
COPY ./package*.json ./
FROM base as builder
RUN npm ci && npm cache clean --force
COPY . ./
RUN npm run build
FROM base
ENV NODE_ENV production
RUN npm ci && npm cache clean --force
COPY --from=builder /usr/src/app/dist ./dist
CMD [ "npm", "start" ]
The MIT License (MIT)
Copyright (c) 2021 Nanahira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# ygopro-lua-minify
## Usage
### Install
```bash
npm ci
npm run build
```
### Run
```bash
npm start <path-to-lua-dir>
```
import path from 'node:path';
import { YGOProLuaMinify } from './src/ygopro-lua-minify';
const root = path.resolve(process.cwd(), process.argv[2] || 'script');
async function main() {
await new YGOProLuaMinify({
root,
}).run();
}
main();
#!/bin/bash
npm i --save-exact --save-dev eslint@8.22.0
npm install --save-dev \
@types/node \
typescript \
'@typescript-eslint/eslint-plugin@^6.0.0' \
'@typescript-eslint/parser@^6.0.0 '\
'eslint-config-prettier@^9.0.0' \
'eslint-plugin-prettier@^5.0.0' \
prettier \
jest \
@types/jest \
ts-jest \
rimraf
This diff is collapsed.
{
"name": "myproject",
"description": "myproject-desc",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "rimraf dist && tsc && cp -rf src/minifier dist/src/",
"test": "jest --passWithNoTests",
"start": "node dist/index.js",
"reset": "rm -rf script2/* && cp -rf script/* script2/"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/myproject.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/myproject/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/myproject",
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "tests",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"devDependencies": {
"@types/jest": "^30.0.0",
"@types/node": "^24.5.0",
"@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0",
"eslint": "8.22.0",
"eslint-config-prettier": "^9.1.2",
"eslint-plugin-prettier": "^5.5.4",
"jest": "^30.1.3",
"prettier": "^3.6.2",
"rimraf": "^6.0.1",
"ts-jest": "^29.4.2",
"typescript": "^5.9.2"
},
"dependencies": {
"axios": "^1.12.2",
"p-queue": "6.6.2"
}
}
export interface LuaFormatSettings {
RenameVariables?: boolean;
RenameGlobals?: boolean;
SolveMath?: boolean;
Indentation?: string;
}
/** 美化 Lua 源码 */
export declare function Beautify(
code: string,
settings?: LuaFormatSettings,
): string;
/** 压缩 Lua 源码 */
export declare function Minify(
code: string,
settings?: LuaFormatSettings,
): string;
/** 另一种压缩/混淆方式 */
export declare function Uglify(
code: string,
settings?: LuaFormatSettings,
): string;
This source diff could not be displayed because it is too large. You can view the blob instead.
import path from 'node:path';
import PQueue from 'p-queue';
import * as fs from 'node:fs';
import axios from 'axios';
import { Minify } from './minifier/luamin';
export interface YGOProLuaMinifyOptions {
root: string;
constantContent?: string;
constantPath?: string;
constantUrl?: string;
}
export class YGOProLuaMinify {
constructor(private options: YGOProLuaMinifyOptions) {}
constantContent = this.options.constantContent || '';
constantQueue = new PQueue({ concurrency: 1 });
async getConstantContent(): Promise<string> {
if (this.constantContent) return this.constantContent;
const resolveContent = (content: string) => {
this.constantContent = content;
return content;
};
return this.constantQueue.add(async () => {
if (this.constantContent) return this.constantContent;
const constantPath = path.resolve(
this.options.root,
this.options.constantPath || 'constant.lua',
);
// if file exists, read it
try {
const content = await fs.promises.readFile(constantPath, 'utf-8');
console.log(`Loaded constant.lua from ${constantPath}`);
return resolveContent(content);
} catch (e) {
// ignore
}
const url =
this.options.constantUrl ||
'https://cdntx.moecube.com/koishipro/content/script/constant.lua';
const res = await axios.get<string>(url, {
responseType: 'text',
});
console.log(`Loaded constant.lua from ${url}`);
return resolveContent(res.data);
});
}
constants: { key: string; value: string; valueNum: number }[] = [];
parseConstants(content: string) {
const constantsMap = new Map<
string,
{ key: string; value: string; valueNum: number }
>();
for (const line of content.split('\n')) {
const withoutComment = line.split('--')[0];
const [keyPart, valuePart] = withoutComment.split('=');
const key = keyPart?.trim();
const value = valuePart?.trim();
if (!key || !value) continue;
const valueParts = value.split(/[+|]/).map((v) => {
if (/[A-Z_]/.test(v)) {
// reference to another constant
const ref = constantsMap.get(v.trim());
if (ref) return ref.valueNum;
return 0;
}
return parseInt(v.trim()) || 0;
});
const valueNum = valueParts.reduce((a, b) => a | b, 0);
const valueDec = valueNum.toString(10);
// const valueHex = '0x' + valueNum.toString(16).toLowerCase();
const pickValue = valueDec; // valueHex.length < valueDec.length ? valueHex : valueDec;
constantsMap.set(key, { key, value: pickValue, valueNum });
if (key.endsWith('_DEFENSE')) {
// add _DEFENCE version too
const altKey = key.replace(/_DEFENSE$/, '_DEFENCE');
constantsMap.set(altKey, { key: altKey, value: pickValue, valueNum });
}
}
// sort with key length desc
this.constants = Array.from(constantsMap.values()).filter(
(c) => c.key.length > c.value.length,
);
this.constants.sort((a, b) => b.key.length - a.key.length);
console.log(`Parsed ${this.constants.length} constants`);
}
async loadConstants() {
const content = await this.getConstantContent();
this.parseConstants(content);
}
async minifyFile(filePath: string) {
const absPath = path.resolve(this.options.root, filePath);
let content = await fs.promises.readFile(absPath, 'utf-8');
if (!filePath.endsWith('constant.lua')) {
const isUtility = filePath.endsWith('utility.lua');
const contentLinesPre = content
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0);
for (let i = 0; i < contentLinesPre.length; i++) {
if (isUtility && contentLinesPre[i].includes('_DEFENCE')) {
continue;
}
for (const { key, value } of this.constants) {
contentLinesPre[i] = contentLinesPre[i].replaceAll(key, value);
}
}
content = contentLinesPre.join('\n');
}
try {
content = Minify(content, {
RenameVariables: true,
RenameGlobals: false,
SolveMath: true,
Indentation: ' ',
});
// there are lines generated by the minifier, so remove them
let contentLines = content
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0);
const commentStartLine = contentLines.findIndex(
(line) => line === '--[[',
);
if (commentStartLine >= 0) {
const commentEndLine = contentLines.findIndex(
(line, index) => index > commentStartLine && line === '--]]',
);
if (commentEndLine > commentStartLine) {
contentLines = contentLines.filter(
(_, index) => index < commentStartLine || index > commentEndLine,
);
} else {
contentLines = contentLines.filter(
(_, index) => index < commentStartLine,
);
}
}
content = contentLines
.filter((line) => !line.startsWith('--'))
.join('\n')
.replace(/[(,](\d+[+\-*/&|^~%])+\d+[),]/g, (expr) => {
const firstChar = expr[0];
const lastChar = expr[expr.length - 1];
const innerExpr = expr.slice(1, -1);
const num = eval(innerExpr) as number;
const dec = num.toString(10);
const hex = '0x' + num.toString(16).toLowerCase();
return `${firstChar}${hex.length < dec.length ? hex : dec}${lastChar}`;
});
await fs.promises.writeFile(absPath, content, 'utf-8');
} catch (e) {
console.error(`Failed to minify ${filePath}:`, e);
return false;
}
return true;
}
async run() {
await this.loadConstants();
// find all lua files recursively
const luaFiles: string[] = [];
const walk = async (dir: string) => {
const files = await fs.promises.readdir(dir);
for (const file of files) {
const fullPath = path.join(dir, file);
const stat = await fs.promises.stat(fullPath);
if (stat.isDirectory()) {
await walk(fullPath);
} else if (stat.isFile() && file.endsWith('.lua')) {
luaFiles.push(path.relative(this.options.root, fullPath));
}
}
};
await walk(this.options.root);
console.log(`Found ${luaFiles.length} lua files`);
const fails: string[] = [];
for (const file of luaFiles) {
console.log(`Minifying ${file}...`);
if (!(await this.minifyFile(file))) {
fails.push(file);
}
}
console.log(
'Done. Success:',
luaFiles.length - fails.length,
'Fail:',
fails.length,
);
if (fails.length > 0) {
console.log('Failed files:');
for (const file of fails) {
console.log(' ', file);
}
}
}
}
describe('Sample test.', () => {
it('should pass', () => {
expect(true).toBe(true);
});
});
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true,
"allowJs": true,
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"test/**/*.ts",
"tests/**/*.ts"
]
}
// types/lua-format.d.ts
declare module "lua-format" {
/** 配置项,与 index.js/luamin.js 的用法一致 */
export interface LuaFormatSettings {
RenameVariables?: boolean;
RenameGlobals?: boolean;
SolveMath?: boolean;
Indentation?: string;
}
/** 美化 Lua 源码 */
export function Beautify(code: string, settings?: LuaFormatSettings): string;
/** 压缩 Lua 源码 */
export function Minify(code: string, settings?: LuaFormatSettings): string;
/** 另一种压缩/混淆方式 */
export function Uglify(code: string, settings?: LuaFormatSettings): string;
// CommonJS 默认导出是对象形式
const _default: {
Beautify: typeof Beautify;
Minify: typeof Minify;
Uglify: typeof Uglify;
};
export default _default;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment