Commit 5d6232f7 authored by nanahira's avatar nanahira

first

parent b369b74d
Pipeline #20145 passed with stages
in 1 minute and 13 seconds
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
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/
unit-test:
extends:
- .build_base
script:
- npm run test
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . --access public && curl -X PUT "https://registry-direct.npmmirror.com/$(cat package.json | jq '.name' | sed 's/\"//g')/sync?sync_upstream=true" || true
only:
- master
/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
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-deck-encode
YGOPro Deck encode and decode, with well-browser support.
\ No newline at end of file
YGOPro Deck encode and decode, with well-browser support.
## Usage
```ts
const deck = new YGOProDeck();
// main: number[]
// extra: number[]
// side: number[]
const code = deck.toEncodedString(); // base64url-encoded deck code
const anotherDeck = YGOProDeck.fromEncodedString(code); // decode it back
const ydk = deck.toYdkString(); // YDK format
const yetAnotherDeck = YGOProDeck.fromYdkString(ydk); // decode it back
```
## Encode format
The deck code is a base64url-encoded string, which is an unsigned 32-bit integer array, each number representing a card
- 28 bits: card ID
- 2 bits: card type
- 0: main deck
- 1: extra deck
- 2: side deck
- 2 bits: card count - 1. a.k.a. 0 means 1, 1 means 2, 2 means 3, 3 means 4
import { countItems } from './src/utils';
import { Base64 } from 'js-base64';
export default class YGOProDeck {
main: number[] = [];
extra: number[] = [];
side: number[] = [];
private sort() {
this.main.sort();
this.extra.sort();
this.side.sort();
}
bufferLength() {
const counted = [this.main, this.extra, this.side].map(countItems);
return counted.reduce((a, b) => a + b.size * 4, 0);
}
toEncodedString() {
const counted = [this.main, this.extra, this.side].map(countItems);
const buf = new Uint8Array(counted.reduce((a, b) => a + b.size * 4, 0));
let pointer = 0;
const writeUint32LE = (value: number) => {
buf[pointer++] = value & 0xff;
buf[pointer++] = (value >> 8) & 0xff;
buf[pointer++] = (value >> 16) & 0xff;
buf[pointer++] = (value >> 24) & 0xff;
};
const writeCards = (countMap: Map<number, number>, type: number) => {
// each card: 28 bits for id, 2 bits(0, 1, 2, 3) for type(0: main, 1: extra, 2: side, 3: unknown), 2 bits for count (0: 1, 1: 2, 2: 3, 3: 4)
for (const [id, count] of countMap.entries()) {
if (count > 4) {
throw new Error(`Too many cards: ${id}`);
}
const value = (id & 0xfffffff) | (type << 28) | ((count - 1) << 30);
writeUint32LE(value);
}
};
counted.forEach(writeCards);
return Base64.fromUint8Array(buf, true);
}
toString() {
return this.toEncodedString();
}
fromEncodedString(str: string) {
const buf = Base64.toUint8Array(str);
for (let i = 0; i < buf.length - 3; i += 4) {
const value =
buf[i] | (buf[i + 1] << 8) | (buf[i + 2] << 16) | (buf[i + 3] << 24);
const id = value & 0xfffffff;
const type = (value >> 28) & 0x3;
const count = ((value >> 30) & 0x3) + 1;
const cards = [this.main, this.extra, this.side][type];
for (let j = 0; j < count; j++) {
cards.push(id);
}
}
this.sort();
return this;
}
static fromEncodedString(str: string) {
return new YGOProDeck().fromEncodedString(str);
}
toYdkString() {
return [
'#created by ygopro-deck-encode',
'#main',
...this.main.map((id) => id.toString()),
'#extra',
...this.extra.map((id) => id.toString()),
'!side',
...this.side.map((id) => id.toString()),
].join('\n');
}
fromYdkString(str: string) {
const lines = str.split('\n');
let current = this.main;
for (const _line of lines) {
const line = _line.trim();
if (line === '#main') {
current = this.main;
}
if (line === '#extra') {
current = this.extra;
}
if (line === '!side') {
current = this.side;
}
if (line.match(/^\d+$/)) {
current.push(parseInt(line, 10));
}
}
this.sort();
return this;
}
static fromYdkString(str: string) {
return new YGOProDeck().fromYdkString(str);
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "myproject",
"description": "myproject-desc",
"version": "1.0.0",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"compile:cjs": "esbuild index.ts --outfile=dist/index.cjs --bundle --sourcemap --platform=node --target=es2019 --external:js-base64",
"compile:esm": "esbuild index.ts --outfile=dist/index.mjs --bundle --sourcemap --platform=neutral --target=esnext --external:js-base64",
"compile:types": "tsc --emitDeclarationOnly --declaration",
"build": "rimraf dist && npm run compile:cjs && npm run compile:esm && npm run compile:types",
"test": "jest --passWithNoTests",
"start": "node dist/index.js"
},
"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": "^29.4.0",
"@types/node": "^18.13.0",
"@typescript-eslint/eslint-plugin": "^5.51.0",
"@typescript-eslint/parser": "^5.51.0",
"esbuild": "^0.17.7",
"esbuild-register": "^3.4.2",
"eslint": "8.22.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.4.2",
"prettier": "^2.8.4",
"rimraf": "^4.1.2",
"ts-jest": "^29.0.5",
"typescript": "^4.9.5"
},
"dependencies": {
"js-base64": "^3.7.5"
}
}
export function countItems<T>(arr: T[]) {
const map = new Map<T, number>();
for (const item of arr) {
map.set(item, (map.get(item) || 0) + 1);
}
return map;
}
import YGOProDeck from '..';
const deck = new YGOProDeck();
deck.main.push(123);
deck.main.push(123);
deck.main.push(123);
deck.main.push(456);
deck.main.push(456);
deck.main.push(789);
deck.extra.push(1234);
deck.extra.push(5678);
deck.side.push(12345);
describe('Sample test.', () => {
it('should encode and decode deck string', () => {
const encoded = deck.toEncodedString();
const buf = Buffer.from(
encoded.replace(/[-_]/g, (m0) => (m0 == '-' ? '+' : '/')),
'base64',
);
expect(buf.length).toBe(24);
const decoded = new YGOProDeck().fromEncodedString(encoded);
expect(decoded.main).toStrictEqual(deck.main);
expect(decoded.extra).toStrictEqual(deck.extra);
expect(decoded.side).toStrictEqual(deck.side);
});
it('should encode and decode ydk text', () => {
const ydk = deck.toYdkString();
console.log(ydk);
expect(ydk.split('\n')).toHaveLength(13);
const decoded = new YGOProDeck().fromYdkString(ydk);
expect(decoded.main).toStrictEqual(deck.main);
expect(decoded.extra).toStrictEqual(deck.extra);
expect(decoded.side).toStrictEqual(deck.side);
})
});
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"test/**/*.ts",
"tests/**/*.ts"
]
}
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