pref: move `lib.init.init` out.

This commit is contained in:
Rintim 2023-12-22 21:02:48 +08:00
parent 800c74eb10
commit b6d3c94a54
No known key found for this signature in database
GPG Key ID: BE9E1EA615BACFCF
15 changed files with 4186 additions and 4002 deletions

View File

@ -53,7 +53,7 @@ new Promise(resolve => {
// @ts-ignore
const module = import('../noname.js');
module.then(({ ai, game, get, lib, _status, ui }) => {
module.then(({ ai, game, get, lib, _status, ui, boot }) => {
const coreAndVersion = get.coreInfo();
const core = coreAndVersion[0], version = coreAndVersion[1];
if (core == 'chrome' && !isNaN(version) && version < 77) {
@ -65,6 +65,6 @@ new Promise(resolve => {
window.open('https://github.com/libccy/noname/releases/tag/chromium77-client');
}
}
lib.init.init();
boot();
});
});

View File

@ -1,530 +0,0 @@
// 'path' module extracted from Node.js v8.11.1 (only the posix part)
// transplited with Babel
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
{
"use strict"
function assertPath(path) {
if (typeof path !== 'string') {
throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));
}
}
// Resolves . and .. elements in a path with directory names
function normalizeStringPosix(path, allowAboveRoot) {
var res = '';
var lastSegmentLength = 0;
var lastSlash = -1;
var dots = 0;
var code;
for (var i = 0; i <= path.length; ++i) {
if (i < path.length)
code = path.charCodeAt(i);
else if (code === 47 /*/*/)
break;
else
code = 47 /*/*/;
if (code === 47 /*/*/) {
if (lastSlash === i - 1 || dots === 1) {
// NOOP
} else if (lastSlash !== i - 1 && dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
if (res.length > 2) {
var lastSlashIndex = res.lastIndexOf('/');
if (lastSlashIndex !== res.length - 1) {
if (lastSlashIndex === -1) {
res = '';
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
}
lastSlash = i;
dots = 0;
continue;
}
} else if (res.length === 2 || res.length === 1) {
res = '';
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
if (res.length > 0)
res += '/..';
else
res = '..';
lastSegmentLength = 2;
}
} else {
if (res.length > 0)
res += '/' + path.slice(lastSlash + 1, i);
else
res = path.slice(lastSlash + 1, i);
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (code === 46 /*.*/ && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
function _format(sep, pathObject) {
var dir = pathObject.dir || pathObject.root;
var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');
if (!dir) {
return base;
}
if (dir === pathObject.root) {
return dir + base;
}
return dir + sep + base;
}
var posix = {
// path.resolve([from ...], to)
resolve: function resolve() {
var resolvedPath = '';
var resolvedAbsolute = false;
var cwd;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path;
if (i >= 0)
path = arguments[i];
else {
if (cwd === undefined)
cwd = process.cwd();
path = cwd;
}
assertPath(path);
// Skip empty entries
if (path.length === 0) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute) {
if (resolvedPath.length > 0)
return '/' + resolvedPath;
else
return '/';
} else if (resolvedPath.length > 0) {
return resolvedPath;
} else {
return '.';
}
},
normalize: function normalize(path) {
assertPath(path);
if (path.length === 0) return '.';
var isAbsolute = path.charCodeAt(0) === 47 /*/*/;
var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;
// Normalize the path
path = normalizeStringPosix(path, !isAbsolute);
if (path.length === 0 && !isAbsolute) path = '.';
if (path.length > 0 && trailingSeparator) path += '/';
if (isAbsolute) return '/' + path;
return path;
},
isAbsolute: function isAbsolute(path) {
assertPath(path);
return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
},
join: function join() {
if (arguments.length === 0)
return '.';
var joined;
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments[i];
assertPath(arg);
if (arg.length > 0) {
if (joined === undefined)
joined = arg;
else
joined += '/' + arg;
}
}
if (joined === undefined)
return '.';
return posix.normalize(joined);
},
relative: function relative(from, to) {
assertPath(from);
assertPath(to);
if (from === to) return '';
from = posix.resolve(from);
to = posix.resolve(to);
if (from === to) return '';
// Trim any leading backslashes
var fromStart = 1;
for (; fromStart < from.length; ++fromStart) {
if (from.charCodeAt(fromStart) !== 47 /*/*/)
break;
}
var fromEnd = from.length;
var fromLen = fromEnd - fromStart;
// Trim any leading backslashes
var toStart = 1;
for (; toStart < to.length; ++toStart) {
if (to.charCodeAt(toStart) !== 47 /*/*/)
break;
}
var toEnd = to.length;
var toLen = toEnd - toStart;
// Compare paths to find the longest common path from root
var length = fromLen < toLen ? fromLen : toLen;
var lastCommonSep = -1;
var i = 0;
for (; i <= length; ++i) {
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === 47 /*/*/) {
// We get here if `from` is the exact base path for `to`.
// For example: from='/foo/bar'; to='/foo/bar/baz'
return to.slice(toStart + i + 1);
} else if (i === 0) {
// We get here if `from` is the root
// For example: from='/'; to='/foo'
return to.slice(toStart + i);
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
// We get here if `to` is the exact base path for `from`.
// For example: from='/foo/bar/baz'; to='/foo/bar'
lastCommonSep = i;
} else if (i === 0) {
// We get here if `to` is the root.
// For example: from='/foo'; to='/'
lastCommonSep = 0;
}
}
break;
}
var fromCode = from.charCodeAt(fromStart + i);
var toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode)
break;
else if (fromCode === 47 /*/*/)
lastCommonSep = i;
}
var out = '';
// Generate the relative path based on the path difference between `to`
// and `from`
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
if (out.length === 0)
out += '..';
else
out += '/..';
}
}
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts
if (out.length > 0)
return out + to.slice(toStart + lastCommonSep);
else {
toStart += lastCommonSep;
if (to.charCodeAt(toStart) === 47 /*/*/)
++toStart;
return to.slice(toStart);
}
},
_makeLong: function _makeLong(path) {
return path;
},
dirname: function dirname(path) {
assertPath(path);
if (path.length === 0) return '.';
var code = path.charCodeAt(0);
var hasRoot = code === 47 /*/*/;
var end = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? '/' : '.';
if (hasRoot && end === 1) return '//';
return path.slice(0, end);
},
basename: function basename(path, ext) {
if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string');
assertPath(path);
var start = 0;
var end = -1;
var matchedSlash = true;
var i;
if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
if (ext.length === path.length && ext === path) return '';
var extIdx = ext.length - 1;
var firstNonSlashEnd = -1;
for (i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
// We saw the first non-path separator, remember this index in case
// we need it if the extension ends up not matching
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
// Try to match the explicit extension
if (code === ext.charCodeAt(extIdx)) {
if (--extIdx === -1) {
// We matched the extension, so mark this as the end of our path
// component
end = i;
}
} else {
// Extension does not match, so our result is the entire path
// component
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd; else if (end === -1) end = path.length;
return path.slice(start, end);
} else {
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return '';
return path.slice(start, end);
}
},
extname: function extname(path) {
assertPath(path);
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
for (var i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1)
startDot = i;
else if (preDotState !== 1)
preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return '';
}
return path.slice(startDot, end);
},
format: function format(pathObject) {
if (pathObject === null || typeof pathObject !== 'object') {
throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
}
return _format('/', pathObject);
},
parse: function parse(path) {
assertPath(path);
var ret = { root: '', dir: '', base: '', ext: '', name: '' };
if (path.length === 0) return ret;
var code = path.charCodeAt(0);
var isAbsolute = code === 47 /*/*/;
var start;
if (isAbsolute) {
ret.root = '/';
start = 1;
} else {
start = 0;
}
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
var i = path.length - 1;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
// Get non-dir info
for (; i >= start; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) startDot = i; else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
if (end !== -1) {
if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end); else ret.base = ret.name = path.slice(startPart, end);
}
} else {
if (startPart === 0 && isAbsolute) {
ret.name = path.slice(1, startDot);
ret.base = path.slice(1, end);
} else {
ret.name = path.slice(startPart, startDot);
ret.base = path.slice(startPart, end);
}
ret.ext = path.slice(startDot, end);
}
if (startPart > 0) ret.dir = path.slice(0, startPart - 1); else if (isAbsolute) ret.dir = '/';
return ret;
},
sep: '/',
delimiter: ':',
win32: null,
posix: null
};
posix.posix = posix;
window._noname_path = posix;
}

View File

@ -6,6 +6,8 @@ import { Library as lib } from './noname/library/index.js';
import { status as _status } from './noname/status/index.js';
import { UI as ui } from './noname/ui/index.js';
export { boot } from './noname/init/index.js';
export {
gnc,
ai,
@ -13,5 +15,5 @@ export {
get,
lib,
_status,
ui
ui,
}

218
noname/init/cordova.js vendored Normal file
View File

@ -0,0 +1,218 @@
// @ts-nocheck
import { Get as get } from '../get/index.js';
import { Library as lib } from '../library/index.js';
import { Game as game } from '../game/index.js';
import { status as _status } from '../status/index.js';
import { UI as ui } from '../ui/index.js';
export function cordovaReady() {
lib.path = (await import('../library/path.js')).default;
if (lib.device == 'android') {
document.addEventListener("pause", function () {
if (!_status.paused2 && (typeof _status.event.isMine == 'function' && !_status.event.isMine())) {
ui.click.pause();
}
if (ui.backgroundMusic) {
ui.backgroundMusic.pause();
}
});
document.addEventListener("resume", () => {
if (ui.backgroundMusic) ui.backgroundMusic.play();
});
document.addEventListener("backbutton", function () {
if (ui.arena && ui.arena.classList.contains('menupaused')) {
if (window.saveNonameInput) {
window.saveNonameInput();
}
else {
ui.click.configMenu();
}
}
else if (lib.config.confirm_exit) {
navigator.notification.confirm(
'是否退出游戏?',
function (index) {
switch (index) {
case 2: game.reload(); break;
case 3: navigator.app.exitApp(); break;
}
},
'确认退出',
['取消', '重新开始', '退出']
);
}
else {
navigator.app.exitApp();
}
});
if ("cordova" in window && "plugins" in window.cordova && "permissions" in window.cordova.plugins) {
const permissions = cordova.plugins.permissions;
const requests = ["WRITE_EXTERNAL_STORAGE", "READ_EXTERNAL_STORAGE"]
requests.forEach(request => {
permissions.checkPermission(permissions[request], status => {
if (!status.hasPermission) {
permissions.requestPermission(permissions[request], lib.other.ignore, lib.other.ignore);
}
}, lib.other.ignore);
});
}
}
game.download = function (url, folder, onsuccess, onerror, dev, onprogress) {
if (!url.startsWith('http')) {
url = get.url(dev) + url;
}
var fileTransfer = new FileTransfer();
folder = lib.assetURL + folder;
if (onprogress) {
fileTransfer.onprogress = function (progressEvent) {
onprogress(progressEvent.loaded, progressEvent.total);
};
}
lib.config.brokenFile.add(folder);
game.saveConfigValue('brokenFile');
fileTransfer.download(encodeURI(url), encodeURI(folder), function () {
lib.config.brokenFile.remove(folder);
game.saveConfigValue('brokenFile');
if (onsuccess) {
onsuccess();
}
}, onerror);
};
game.readFile = function (filename, callback, onerror) {
window.resolveLocalFileSystemURL(lib.assetURL, function (entry) {
entry.getFile(filename, {}, function (fileEntry) {
fileEntry.file(function (fileToLoad) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
callback(e.target.result);
};
fileReader.readAsArrayBuffer(fileToLoad, "UTF-8");
}, onerror);
}, onerror);
}, onerror);
};
game.readFileAsText = function (filename, callback, onerror) {
window.resolveLocalFileSystemURL(lib.assetURL, function (entry) {
entry.getFile(filename, {}, function (fileEntry) {
fileEntry.file(function (fileToLoad) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
callback(e.target.result);
};
fileReader.readAsText(fileToLoad, "UTF-8");
}, onerror);
}, onerror);
}, onerror);
};
game.writeFile = function (data, path, name, callback) {
game.ensureDirectory(path, function () {
if (Object.prototype.toString.call(data) == '[object File]') {
var fileReader = new FileReader();
fileReader.onload = function (e) {
game.writeFile(e.target.result, path, name, callback);
};
fileReader.readAsArrayBuffer(data, "UTF-8");
}
else {
window.resolveLocalFileSystemURL(lib.assetURL + path, function (entry) {
entry.getFile(name, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = callback;
fileWriter.write(data);
}, callback);
}, callback);
}, callback);
}
});
};
game.removeFile = function (dir, callback) {
window.resolveLocalFileSystemURL(lib.assetURL, function (entry) {
entry.getFile(dir, {}, function (fileEntry) {
fileEntry.remove();
if (callback) callback();
}, callback || function () { });
}, callback || function () { });
};
game.getFileList = (dir, success, failure) => {
var files = [], folders = [];
window.resolveLocalFileSystemURL(lib.assetURL + dir, entry => {
var dirReader = entry.createReader();
var entries = [];
var readEntries = () => {
dirReader.readEntries(results => {
if (!results.length) {
entries.sort();
for (var i = 0; i < entries.length; i++) {
if (entries[i].isDirectory) {
folders.push(entries[i].name);
}
else {
files.push(entries[i].name);
}
}
success(folders, files);
}
else {
entries = entries.concat(Array.from(results));
readEntries();
}
}, failure);
};
readEntries();
}, failure);
};
game.ensureDirectory = (list, callback, file) => {
const directoryList = typeof list == 'string' ? [list] : list.slice().reverse(), num = file ? 1 : 0, access = (entry, directory, createDirectory) => {
if (directory.length <= num) {
createDirectory();
return;
}
const str = directory.pop();
return new Promise((resolve, reject) => entry.getDirectory(str, {
create: false
}, resolve, reject)).catch(() => new Promise(resolve => entry.getDirectory(str, {
create: true
}, resolve))).then(directoryEntry => access(directoryEntry, directory, createDirectory));
};
return new Promise((resolve, reject) => window.resolveLocalFileSystemURL(lib.assetURL, rootEntry => {
const createDirectory = () => {
if (directoryList.length) access(rootEntry, directoryList.pop().split('/').reverse(), createDirectory);
if (typeof callback == 'function') callback();
resolve();
};
createDirectory();
}, reject));
};
if (ui.updateUpdate) {
ui.updateUpdate();
}
var showbar = function () {
if (window.StatusBar) {
if (lib.device == 'android') {
if (lib.config.show_statusbar_android) {
window.StatusBar.overlaysWebView(false);
window.StatusBar.backgroundColorByName('black');
window.StatusBar.show();
}
}
else if (lib.device == 'ios') {
if (lib.config.show_statusbar_ios != 'off' && lib.config.show_statusbar_ios != 'auto') {
if (lib.config.show_statusbar_ios == 'default') {
window.StatusBar.overlaysWebView(false);
}
else {
window.StatusBar.overlaysWebView(true);
}
window.StatusBar.backgroundColorByName('black');
window.StatusBar.show();
}
}
}
}
if (lib.arenaReady) {
lib.arenaReady.push(showbar);
}
else {
showbar();
}
}

1002
noname/init/index.js Normal file

File diff suppressed because it is too large Load Diff

161
noname/init/node.js Normal file
View File

@ -0,0 +1,161 @@
// @ts-nocheck
import { Get as get } from '../get/index.js';
import { Library as lib } from '../library/index.js';
import { Game as game } from '../game/index.js';
import { status as _status } from '../status/index.js';
import { UI as ui } from '../ui/index.js';
export function nodeReady() {
lib.node = {
fs: require('fs'),
path: require("path"),
debug: function () {
require('electron').remote.getCurrentWindow().toggleDevTools();
}
};
lib.path = lib.node.path;
game.download = function (url, folder, onsuccess, onerror, dev, onprogress) {
if (!url.startsWith('http')) {
url = get.url(dev) + url;
}
game.ensureDirectory(folder, function () {
try {
var file = lib.node.fs.createWriteStream(__dirname + '/' + folder);
}
catch (e) {
onerror();
}
lib.config.brokenFile.add(folder);
game.saveConfigValue('brokenFile');
if (!lib.node.http) lib.node.http = require('http');
if (!lib.node.https) lib.node.https = require('https');
var opts = require('url').parse(encodeURI(url));
opts.headers = { 'User-Agent': 'AppleWebkit' };
(url.startsWith('https') ? lib.node.https : lib.node.http).get(opts, function (response) {
var stream = response.pipe(file);
stream.on('finish', function () {
lib.config.brokenFile.remove(folder);
game.saveConfigValue('brokenFile');
if (onsuccess) {
onsuccess();
}
});
stream.on('error', onerror);
if (onprogress) {
var streamInterval = setInterval(function () {
if (stream.closed) {
clearInterval(streamInterval);
}
else {
onprogress(stream.bytesWritten);
}
}, 200);
}
});
}, true);
};
game.readFile = function (filename, callback, onerror) {
lib.node.fs.readFile(__dirname + '/' + filename, function (err, data) {
if (err) {
onerror(err);
}
else {
callback(data);
}
});
};
game.readFileAsText = function (filename, callback, onerror) {
lib.node.fs.readFile(__dirname + '/' + filename, 'utf-8', function (err, data) {
if (err) {
onerror(err);
}
else {
callback(data);
}
});
};
game.writeFile = function (data, path, name, callback) {
game.ensureDirectory(path, function () {
if (Object.prototype.toString.call(data) == '[object File]') {
var fileReader = new FileReader();
fileReader.onload = function (e) {
game.writeFile(e.target.result, path, name, callback);
};
fileReader.readAsArrayBuffer(data, "UTF-8");
}
else {
get.zip(function (zip) {
zip.file('i', data);
lib.node.fs.writeFile(__dirname + '/' + path + '/' + name, zip.files.i.asNodeBuffer(), null, callback);
});
}
});
};
game.removeFile = function (filename, callback) {
lib.node.fs.unlink(__dirname + '/' + filename, callback || function () { });
};
game.getFileList = (dir, success, failure) => {
var files = [], folders = [];
dir = __dirname + '/' + dir;
if (typeof failure == "undefined") {
failure = err => {
throw err;
};
}
else if (failure == null) {
failure = () => { };
}
try {
lib.node.fs.readdir(dir, (err, filelist) => {
if (err) {
failure(err);
return;
}
for (var i = 0; i < filelist.length; i++) {
if (filelist[i][0] != '.' && filelist[i][0] != '_') {
if (lib.node.fs.statSync(dir + '/' + filelist[i]).isDirectory()) {
folders.push(filelist[i]);
}
else {
files.push(filelist[i]);
}
}
}
success(folders, files);
});
}
catch (e) {
failure(e);
}
};
game.ensureDirectory = (list, callback, file) => {
const directoryList = typeof list == 'string' ? [list] : list.slice().reverse(), number = file ? 1 : 0, access = (path, directory, createDirectory) => {
if (directory.length <= number) {
createDirectory();
return;
}
path += `/${directory.pop()}`;
const fullPath = `${__dirname}${path}`;
return new Promise((resolve, reject) => lib.node.fs.access(fullPath, errnoException => {
if (errnoException) reject();
else resolve();
})).catch(() => new Promise((resolve, reject) => lib.node.fs.mkdir(fullPath, errnoException => {
if (errnoException) reject(errnoException);
else resolve();
}))).then(() => access(path, directory, createDirectory), console.log);
};
return new Promise(resolve => {
const createDirectory = () => {
if (directoryList.length) access('', directoryList.pop().split('/').reverse(), createDirectory);
else {
if (typeof callback == 'function') callback();
resolve();
}
};
createDirectory();
});
};
if (ui.updateUpdate) {
ui.updateUpdate();
}
}

517
noname/init/polyfill.js Normal file
View File

@ -0,0 +1,517 @@
// @ts-nocheck
import { Get as get } from '../get/index.js';
import { Library as lib } from '../library/index.js';
import { Game as game } from '../game/index.js';
import { status as _status } from '../status/index.js';
import { UI as ui } from '../ui/index.js';
HTMLDivElement.prototype.animate = function (name, time) {
var that;
if (get.is.mobileMe(this) && name == 'target') {
that = ui.mebg;
}
else {
that = this;
}
that.classList.add(name);
setTimeout(function () {
that.classList.remove(name);
}, time || 1000);
return this;
};
HTMLDivElement.prototype.hide = function () {
this.classList.add('hidden');
return this;
};
HTMLDivElement.prototype.unfocus = function () {
if (lib.config.transparent_dialog) this.classList.add('transparent');
return this;
};
HTMLDivElement.prototype.refocus = function () {
this.classList.remove('transparent');
return this;
};
HTMLDivElement.prototype.show = function () {
this.classList.remove('hidden');
return this;
};
HTMLDivElement.prototype.delete = function (time, callback) {
if (this.timeout) {
clearTimeout(this.timeout);
delete this.timeout;
}
if (!this._listeningEnd || this._transitionEnded) {
if (typeof time != 'number') time = 500;
this.classList.add('removing');
var that = this;
this.timeout = setTimeout(function () {
that.remove();
that.classList.remove('removing');
if (typeof callback == 'function') {
callback();
}
}, time);
}
else {
this._onEndDelete = true;
}
return this;
};
HTMLDivElement.prototype.goto = function (position, time) {
if (this.timeout) {
clearTimeout(this.timeout);
delete this.timeout;
}
if (typeof time != 'number') time = 500;
this.classList.add('removing');
var that = this;
this.timeout = setTimeout(function () {
if (!that._selfDestroyed) {
position.appendChild(that);
}
that.classList.remove('removing');
delete that.destiny;
}, time);
this.destiny = position;
return this;
};
HTMLDivElement.prototype.fix = function () {
clearTimeout(this.timeout);
delete this.timeout;
delete this.destiny;
this.classList.remove('removing');
return this;
};
Reflect.defineProperty(HTMLDivElement.prototype, 'setBackground', {
configurable: true,
enumerable: false,
writable: true,
value: function (name, type, ext, subfolder) {
if (!name) return;
let src;
if (ext == 'noskin') ext = '.jpg';
ext = ext || '.jpg';
subfolder = subfolder || 'default';
if (type) {
let dbimage = null, extimage = null, modeimage = null, nameinfo, gzbool = false;
const mode = get.mode();
if (type == 'character') {
if (lib.characterPack[`mode_${mode}`] && lib.characterPack[`mode_${mode}`][name]) {
if (mode == 'guozhan') {
nameinfo = lib.character[name];
if (name.startsWith('gz_shibing')) name = name.slice(3, 11);
else {
if (lib.config.mode_config.guozhan.guozhanSkin && lib.character[name] && lib.character[name][4].contains('gzskin')) gzbool = true;
name = name.slice(3);
}
}
else modeimage = mode;
}
else if (name.includes('::')) {
name = name.split('::');
modeimage = name[0];
name = name[1];
}
else {
nameinfo = get.character(name);
}
}
if (!modeimage && nameinfo && nameinfo[4]) for (const value of nameinfo[4]) {
if (value.startsWith('ext:')) {
extimage = value;
break;
}
else if (value.startsWith('db:')) {
dbimage = value;
break;
}
else if (value.startsWith('mode:')) {
modeimage = value.slice(5);
break;
}
else if (value.startsWith('character:')) {
name = value.slice(10);
break;
}
}
if (extimage) src = extimage.replace(/^ext:/, 'extension/');
else if (dbimage) {
this.setBackgroundDB(dbimage.slice(3));
return this;
}
else if (modeimage) src = `image/mode/${modeimage}/character/${name}${ext}`;
else if (type == 'character' && lib.config.skin[name] && arguments[2] != 'noskin') src = `image/skin/${name}/${lib.config.skin[name]}${ext}`;
else if (type == 'character') {
src = `image/character/${gzbool ? 'gz_' : ''}${name}${ext}`;
}
else src = `image/${type}/${subfolder}/${name}${ext}`;
}
else src = `image/${name}${ext}`;
this.setBackgroundImage(src);
this.style.backgroundPositionX = 'center';
this.style.backgroundSize = 'cover';
if (type === 'character') {
const nameinfo = get.character(name);
const sex = nameinfo ? nameinfo[0] : 'male';
this.style.backgroundImage = [
this.style.backgroundImage,
`url("${lib.assetURL}image/character/default_silhouette_${sex}${ext}")`,
`url("${lib.assetURL}image/character/default_silhouette_male${ext}")`,
].join(",");
}
return this;
}
});
HTMLDivElement.prototype.setBackgroundDB = function (img) {
return game.getDB('image', img).then(src => {
this.style.backgroundImage = `url('${src}')`;
this.style.backgroundSize = "cover";
return this;
});
};
HTMLDivElement.prototype.setBackgroundImage = function (img) {
this.style.backgroundImage = `url("${lib.assetURL}${img}")`;
return this;
},
HTMLDivElement.prototype.listen = function (func) {
if (lib.config.touchscreen) {
this.addEventListener('touchend', function (e) {
if (!_status.dragged) {
func.call(this, e);
}
});
var fallback = function (e) {
if (!_status.touchconfirmed) {
func.call(this, e);
}
else {
this.removeEventListener('click', fallback);
}
}
this.addEventListener('click', fallback);
}
else {
this.addEventListener('click', func);
}
return this;
};
HTMLDivElement.prototype.listenTransition = function (func, time) {
let done = false;
const callback = () => {
if (!done) {
done = true;
func.call(this);
}
clearTimeout(timer);
this.removeEventListener('webkitTransitionEnd', callback);
};
const timer = setTimeout(callback, time || 1000);
this.addEventListener('webkitTransitionEnd', callback);
return timer;
};
HTMLDivElement.prototype.setPosition = function () {
var position;
if (arguments.length == 4) {
position = [];
for (var i = 0; i < arguments.length; i++) position.push(arguments[i]);
}
else if (arguments.length == 1 && Array.isArray(arguments[0]) && arguments[0].length == 4) {
position = arguments[0];
}
else {
return this;
}
var top = 'calc(' + position[0] + '% ';
if (position[1] > 0) top += '+ ' + position[1] + 'px)';
else top += '- ' + Math.abs(position[1]) + 'px)';
var left = 'calc(' + position[2] + '% ';
if (position[3] > 0) left += '+ ' + position[3] + 'px)';
else left += '- ' + Math.abs(position[3]) + 'px)';
this.style.top = top;
this.style.left = left;
return this;
};
HTMLDivElement.prototype.css = function (style) {
for (var i in style) {
if (i == 'innerHTML') {
this.innerHTML = style[i];
}
else {
this.style[i] = style[i];
}
}
return this;
};
HTMLTableElement.prototype.get = function (row, col) {
if (row < this.childNodes.length) {
return this.childNodes[row].childNodes[col];
}
};
/*处理lib.nature的兼容性问题*/
const mapHasFunc = function (item) {
return this.has(item)
};
Object.defineProperty(Map.prototype, "contains", {
configurable: true,
enumerable: false,
writable: true,
value: mapHasFunc
});
Object.defineProperty(Map.prototype, "includes", {
configurable: true,
enumerable: false,
writable: true,
value: mapHasFunc
});
const mapAddFunc = function (item) {
this.set(item, 0);
return this;
}
Object.defineProperty(Map.prototype, "add", {
configurable: true,
enumerable: false,
writable: true,
value: mapAddFunc
});
Object.defineProperty(Map.prototype, "push", {
configurable: true,
enumerable: false,
writable: true,
value: mapAddFunc
});
Object.defineProperty(Map.prototype, "addArray", {
configurable: true,
enumerable: false,
writable: true,
value: function (arr) {
for (var i = 0; i < arr.length; i++) {
this.add(arr[i]);
}
return this;
}
});
Object.defineProperty(Map.prototype, "remove", {
configurable: true,
enumerable: false,
writable: true,
value: function (item) {
this.delete(item);
return this;
}
});
/*Map prototype end*/
Object.defineProperty(Array.prototype, "filterInD", {
configurable: true,
enumerable: false,
writable: true,
value: function (pos) {
if (typeof pos != 'string') pos = 'o';
return this.filter(card => pos.includes(get.position(card, true)));
}
});
Object.defineProperty(Array.prototype, "someInD", {
configurable: true,
enumerable: false,
writable: true,
value: function (pos) {
if (typeof pos != 'string') pos = 'o';
return this.some(card => pos.includes(get.position(card, true)));
}
});
Object.defineProperty(Array.prototype, "everyInD", {
configurable: true,
enumerable: false,
writable: true,
value: function (pos) {
if (typeof pos != 'string') pos = 'o';
return this.every(card => pos.includes(get.position(card, true)));
}
});
/**
*@legacy Use {@link Array#includes} instead.
*/
Object.defineProperty(Array.prototype, "contains", {
configurable: true,
enumerable: false,
writable: true,
value: Array.prototype.includes
});
Object.defineProperty(Array.prototype, "containsSome", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
return Array.from(arguments).some(i => this.includes(i));
}
});
Object.defineProperty(Array.prototype, "containsAll", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
return Array.from(arguments).every(i => this.includes(i));
}
});
Object.defineProperty(Array.prototype, "add", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
for (const arg of arguments) {
if (this.contains(arg)) continue;
this.push(arg);
}
return this;
}
});
Object.defineProperty(Array.prototype, "addArray", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
for (const arr of arguments) {
for (const item of arr) this.add(item);
}
return this;
}
});
Object.defineProperty(Array.prototype, "remove", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
for (const item of arguments) {
let pos = -1;
if (typeof item == 'number' && isNaN(item)) {
pos = this.findIndex(v => isNaN(v))
} else {
pos = this.indexOf(item);
}
if (pos == -1) continue;
this.splice(pos, 1);
}
return this;
}
});
Object.defineProperty(Array.prototype, "removeArray", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
for (const i of Array.from(arguments)) this.remove(...i);
return this;
}
});
Object.defineProperty(Array.prototype, "unique", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
let uniqueArray = [...new Set(this)];
this.length = uniqueArray.length;
for (let i = 0; i < uniqueArray.length; i++) this[i] = uniqueArray[i];
return this;
}
});
Object.defineProperty(Array.prototype, "toUniqued", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
return [...new Set(this)];
}
});
Object.defineProperty(Array.prototype, "randomGet", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
let arr = this.slice(0);
arr.removeArray(Array.from(arguments));
return arr[Math.floor(Math.random() * arr.length)];
}
});
Object.defineProperty(Array.prototype, "randomGets", {
configurable: true,
enumerable: false,
writable: true,
value: function (num) {
if (num > this.length) num = this.length;
let arr = this.slice(0);
let list = [];
for (let i = 0; i < num; i++) {
list.push(arr.splice(Math.floor(Math.random() * arr.length), 1)[0]);
}
return list;
}
});
Object.defineProperty(Array.prototype, "randomRemove", {
configurable: true,
enumerable: false,
writable: true,
value: function (num) {
if (typeof num == 'number') {
let list = [];
for (let i = 0; i < num; i++) {
if (!this.length) break;
list.push(this.randomRemove());
}
return list;
}
return this.splice(Math.floor(Math.random() * this.length), 1)[0];
}
});
Object.defineProperty(Array.prototype, "randomSort", {
configurable: true,
enumerable: false,
writable: true,
value: function () {
let list = [];
while (this.length) {
list.push(this.randomRemove());
}
for (let i = 0; i < list.length; i++) {
this.push(list[i]);
}
return this;
}
});
Object.defineProperty(Array.prototype, "sortBySeat", {
configurable: true,
enumerable: false,
writable: true,
value: function (target) {
lib.tempSortSeat = target;
this.sort(lib.sort.seat);
delete lib.tempSortSeat;
return this;
}
});
/**
*@description 从数组中寻找某个特征最大的且通过筛选的第一个元素
*/
Object.defineProperty(Array.prototype, "maxBy", {
configurable: true,
enumerable: false,
writable: true,
value: function (sortBy, filter) {
let list = this.filter(filter || (() => true));
if (sortBy && typeof sortBy == 'function') list.sort((a, b) => sortBy(a) - sortBy(b));
else list.sort();
return list[list.length - 1];
}
});
Object.defineProperty(Array.prototype, "minBy", {
configurable: true,
enumerable: false,
writable: true,
value: function (sortBy, filter) {
let list = this.filter(filter || (() => true));
if (sortBy && typeof sortBy == 'function') list.sort((a, b) => sortBy(a) - sortBy(b));
else list.sort();
return list[0];
}
});

51
noname/library/announce/index.d.ts vendored Normal file
View File

@ -0,0 +1,51 @@
export interface IAnnounceSubscriber {
subscribe(name: string): void;
unsubscribe(name: string): void;
get isEmpty(): boolean
}
export type AnnounceSubscriberType<T> = new (
content: (value: T, name: string) => void,
target: EventTarget
) => IAnnounceSubscriber;
export class Announce {
constructor(eventTarget: EventTarget, records: WeakMap<((arg0: any) => void), IAnnounceSubscriber>, SubscriberType: AnnounceSubscriberType<any> = AnnounceSubscriber)
/**
*
*
*
*
* @param name -
* @param values -
*/
publish<T>(name: string, values: T): T
/**
*
*
*
*
*
*
* @param name -
* @param method -
*/
subscribe<T>(name: string, method: (values: T) => void): (values: T) => void
/**
*
*
*
*
* @param name -
* @param method -
*/
unsubscribe<T>(name: string, method: (values: T) => void): (values: T) => void
}
export class AnnounceSubscriber<T> implements IAnnounceSubscriber {
constructor(content: (value: T, name: string) => void, target: EventTarget)
}

View File

@ -5,6 +5,14 @@
*/
const vm = new WeakMap();
/**
* @template T
* @typedef {import("./index").AnnounceSubscriberType<T>} AnnounceSubscriberType
*/
/**
* @typedef {import("./index").IAnnounceSubscriber} IAnnounceSubscriber
*/
/**
*
*/
@ -15,20 +23,20 @@ export class Announce {
#eventTarget;
/**
* @type {WeakMap<function(any): void, AnnounceSubscriber>}
* @type {WeakMap<function(any): void, IAnnounceSubscriber>}
*/
#records;
/**
* @type {FunctionConstructor}
* @type {AnnounceSubscriberType<any>}
*/
#SubscriberType;
/**
*
* @param {EventTarget} eventTarget
* @param {WeakMap<function(any): void, AnnounceSubscriber>} records
* @param {FunctionConstructor} [SubscriberType]
* @param {WeakMap<function(any): void, IAnnounceSubscriber>} records
* @param {AnnounceSubscriberType<any>} [SubscriberType]
*/
constructor(eventTarget, records, SubscriberType = AnnounceSubscriber) {
this.#eventTarget = eventTarget;
@ -73,6 +81,7 @@ export class Announce {
subscriber = new this.#SubscriberType(method, this.#eventTarget);
this.#records.set(method, subscriber);
}
if (!subscriber) throw new Error()
subscriber.subscribe(name);
return method;
}
@ -90,6 +99,7 @@ export class Announce {
unsubscribe(name, method) {
if (this.#records.has(method)) {
const subscriber = this.#records.get(method);
if (!subscriber) throw new Error()
subscriber.unsubscribe(name);
if (subscriber.isEmpty)
this.#records.delete(method);
@ -101,7 +111,7 @@ export class Announce {
/**
* @template T
*/
class AnnounceSubscriber {
export class AnnounceSubscriber {
/**
* @type {function(CustomEvent): void}
*/
@ -134,12 +144,19 @@ class AnnounceSubscriber {
* @param {string} name
*/
subscribe(name) {
// @ts-expect-error MustHave
vm.get(this).addEventListener(name, this.#content);
// @ts-expect-error NonameDefine
this.#listening.add(name);
}
unsubscribe() {
/**
* @param {string} name
*/
unsubscribe(name) {
// @ts-expect-error MustHave
vm.get(this).removeEventListener(name, this.#content);
// @ts-expect-error NonameDefine
this.#listening.remove(name);
}
}

File diff suppressed because it is too large Load Diff

1575
noname/library/init/index.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,67 @@
import { Uninstantable } from "../../util/index.js";
import { Library as lib } from "../index.js";
export class LibInitPromises extends Uninstantable {
/**
* Promise版的`lib.init.js`
*
* @param {string} path - 文件路径
* @param {string | string[]} [file] - 文件名或文件名组忽略则直接读取`path`的内容
* @returns {Promise<Event>}
*/
static js(path, file) {
return new Promise((resolve, reject) => lib.init.js(path, file, resolve, reject))
}
/**
* Promise版的`lib.init.css`
*
* @param {string} path - 文件路径
* @param {string | string[]} [file] - 文件名或文件名组忽略则直接读取`path`的内容
* @param {Element} [before] - 新样式dom的位置
* @param {boolean} [noerror = false] - 是否忽略报错
* @returns {Promise<HTMLLinkElement>}
*/
static css(path, file, before, noerror = false) {
return new Promise((resolve, reject) => {
const style = lib.init.css(path, file, before);
const success = () => resolve(style);
style.addEventListener("load", success);
style.addEventListener("error", noerror ? success : reject);
})
}
/**
* Promise版的`lib.init.req`
*
* @param {string} str - 要读取的地址
* @param {string} [master]
* @returns {Promise<ProgressEvent>}
*/
static req(str, master) {
return new Promise((resolve, reject) => lib.init.req(str, resolve, reject, master))
}
/**
* Promise版的`lib.init.json`
*
* @param {string} url - 要读取的地址
* @returns {Promise<object>}
*/
static json(url) {
return new Promise((resolve, reject) => lib.init.json(url, resolve, reject))
}
/**
* Promise版的`lib.init.sheet`
*
* @returns {Promise<HTMLStyleElement>}
*/
static sheet() {
return new Promise((resolve, reject) => {
const style = lib.init.sheet.apply(lib.init, arguments);
style.addEventListener("load", () => resolve(style));
style.addEventListener("error", reject);
})
}
}

528
noname/library/path.js Normal file
View File

@ -0,0 +1,528 @@
// 'path' module extracted from Node.js v8.11.1 (only the posix part)
// transplited with Babel
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
function assertPath(path) {
if (typeof path !== 'string') {
throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));
}
}
// Resolves . and .. elements in a path with directory names
function normalizeStringPosix(path, allowAboveRoot) {
var res = '';
var lastSegmentLength = 0;
var lastSlash = -1;
var dots = 0;
var code;
for (var i = 0; i <= path.length; ++i) {
if (i < path.length)
code = path.charCodeAt(i);
else if (code === 47 /*/*/)
break;
else
code = 47 /*/*/;
if (code === 47 /*/*/) {
if (lastSlash === i - 1 || dots === 1) {
// NOOP
} else if (lastSlash !== i - 1 && dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
if (res.length > 2) {
var lastSlashIndex = res.lastIndexOf('/');
if (lastSlashIndex !== res.length - 1) {
if (lastSlashIndex === -1) {
res = '';
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
}
lastSlash = i;
dots = 0;
continue;
}
} else if (res.length === 2 || res.length === 1) {
res = '';
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
if (res.length > 0)
res += '/..';
else
res = '..';
lastSegmentLength = 2;
}
} else {
if (res.length > 0)
res += '/' + path.slice(lastSlash + 1, i);
else
res = path.slice(lastSlash + 1, i);
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (code === 46 /*.*/ && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
function _format(sep, pathObject) {
var dir = pathObject.dir || pathObject.root;
var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');
if (!dir) {
return base;
}
if (dir === pathObject.root) {
return dir + base;
}
return dir + sep + base;
}
var posix = {
// path.resolve([from ...], to)
resolve: function resolve() {
var resolvedPath = '';
var resolvedAbsolute = false;
var cwd;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path;
if (i >= 0)
path = arguments[i];
else {
if (cwd === undefined)
cwd = process.cwd();
path = cwd;
}
assertPath(path);
// Skip empty entries
if (path.length === 0) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute) {
if (resolvedPath.length > 0)
return '/' + resolvedPath;
else
return '/';
} else if (resolvedPath.length > 0) {
return resolvedPath;
} else {
return '.';
}
},
normalize: function normalize(path) {
assertPath(path);
if (path.length === 0) return '.';
var isAbsolute = path.charCodeAt(0) === 47 /*/*/;
var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;
// Normalize the path
path = normalizeStringPosix(path, !isAbsolute);
if (path.length === 0 && !isAbsolute) path = '.';
if (path.length > 0 && trailingSeparator) path += '/';
if (isAbsolute) return '/' + path;
return path;
},
isAbsolute: function isAbsolute(path) {
assertPath(path);
return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
},
join: function join() {
if (arguments.length === 0)
return '.';
var joined;
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments[i];
assertPath(arg);
if (arg.length > 0) {
if (joined === undefined)
joined = arg;
else
joined += '/' + arg;
}
}
if (joined === undefined)
return '.';
return posix.normalize(joined);
},
relative: function relative(from, to) {
assertPath(from);
assertPath(to);
if (from === to) return '';
from = posix.resolve(from);
to = posix.resolve(to);
if (from === to) return '';
// Trim any leading backslashes
var fromStart = 1;
for (; fromStart < from.length; ++fromStart) {
if (from.charCodeAt(fromStart) !== 47 /*/*/)
break;
}
var fromEnd = from.length;
var fromLen = fromEnd - fromStart;
// Trim any leading backslashes
var toStart = 1;
for (; toStart < to.length; ++toStart) {
if (to.charCodeAt(toStart) !== 47 /*/*/)
break;
}
var toEnd = to.length;
var toLen = toEnd - toStart;
// Compare paths to find the longest common path from root
var length = fromLen < toLen ? fromLen : toLen;
var lastCommonSep = -1;
var i = 0;
for (; i <= length; ++i) {
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === 47 /*/*/) {
// We get here if `from` is the exact base path for `to`.
// For example: from='/foo/bar'; to='/foo/bar/baz'
return to.slice(toStart + i + 1);
} else if (i === 0) {
// We get here if `from` is the root
// For example: from='/'; to='/foo'
return to.slice(toStart + i);
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
// We get here if `to` is the exact base path for `from`.
// For example: from='/foo/bar/baz'; to='/foo/bar'
lastCommonSep = i;
} else if (i === 0) {
// We get here if `to` is the root.
// For example: from='/foo'; to='/'
lastCommonSep = 0;
}
}
break;
}
var fromCode = from.charCodeAt(fromStart + i);
var toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode)
break;
else if (fromCode === 47 /*/*/)
lastCommonSep = i;
}
var out = '';
// Generate the relative path based on the path difference between `to`
// and `from`
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
if (out.length === 0)
out += '..';
else
out += '/..';
}
}
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts
if (out.length > 0)
return out + to.slice(toStart + lastCommonSep);
else {
toStart += lastCommonSep;
if (to.charCodeAt(toStart) === 47 /*/*/)
++toStart;
return to.slice(toStart);
}
},
_makeLong: function _makeLong(path) {
return path;
},
dirname: function dirname(path) {
assertPath(path);
if (path.length === 0) return '.';
var code = path.charCodeAt(0);
var hasRoot = code === 47 /*/*/;
var end = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? '/' : '.';
if (hasRoot && end === 1) return '//';
return path.slice(0, end);
},
basename: function basename(path, ext) {
if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string');
assertPath(path);
var start = 0;
var end = -1;
var matchedSlash = true;
var i;
if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
if (ext.length === path.length && ext === path) return '';
var extIdx = ext.length - 1;
var firstNonSlashEnd = -1;
for (i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
// We saw the first non-path separator, remember this index in case
// we need it if the extension ends up not matching
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
// Try to match the explicit extension
if (code === ext.charCodeAt(extIdx)) {
if (--extIdx === -1) {
// We matched the extension, so mark this as the end of our path
// component
end = i;
}
} else {
// Extension does not match, so our result is the entire path
// component
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd; else if (end === -1) end = path.length;
return path.slice(start, end);
} else {
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return '';
return path.slice(start, end);
}
},
extname: function extname(path) {
assertPath(path);
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
for (var i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1)
startDot = i;
else if (preDotState !== 1)
preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return '';
}
return path.slice(startDot, end);
},
format: function format(pathObject) {
if (pathObject === null || typeof pathObject !== 'object') {
throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
}
return _format('/', pathObject);
},
parse: function parse(path) {
assertPath(path);
var ret = { root: '', dir: '', base: '', ext: '', name: '' };
if (path.length === 0) return ret;
var code = path.charCodeAt(0);
var isAbsolute = code === 47 /*/*/;
var start;
if (isAbsolute) {
ret.root = '/';
start = 1;
} else {
start = 0;
}
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
var i = path.length - 1;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
// Get non-dir info
for (; i >= start; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) startDot = i; else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
if (end !== -1) {
if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end); else ret.base = ret.name = path.slice(startPart, end);
}
} else {
if (startPart === 0 && isAbsolute) {
ret.name = path.slice(1, startDot);
ret.base = path.slice(1, end);
} else {
ret.name = path.slice(startPart, startDot);
ret.base = path.slice(startPart, end);
}
ret.ext = path.slice(startDot, end);
}
if (startPart > 0) ret.dir = path.slice(0, startPart - 1); else if (isAbsolute) ret.dir = '/';
return ret;
},
sep: '/',
delimiter: ':',
win32: null,
posix: null
};
// @ts-ignore
posix.posix = posix;
export default posix;

32
noname/util/config.js Normal file
View File

@ -0,0 +1,32 @@
import { Library as lib } from "../library/index.js";
/**
* @param {string} name
* @returns {any}
*/
export function get(name) {
const config = Reflect.get(lib, 'config');
if (!config) return null;
return Reflect.get(config, name);
}
/**
* @param {string} name
* @param {any} value
* @returns {void}
*/
export function set(name, value) {
const config = Reflect.get(lib, 'config');
if (!config) return;
Reflect.set(config, name, value)
}
/**
* @param {string} name
* @returns {boolean}
*/
export function has(name) {
const config = Reflect.get(lib, 'config');
if (!config) return false;
return Reflect.has(config, name);
}