“初始化俯视角工程,带puerts,未编过”
This commit is contained in:
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,756 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const UE = require("ue");
|
||||
function some(array, predicate) {
|
||||
if (array) {
|
||||
if (predicate) {
|
||||
for (const v of array) {
|
||||
if (predicate(v)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return array.length > 0;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const directorySeparator = "/";
|
||||
const altDirectorySeparator = "\\";
|
||||
const urlSchemeSeparator = "://";
|
||||
const backslashRegExp = /\\/g;
|
||||
const reservedCharacterPattern = /[^\w\s\/]/g;
|
||||
const commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
|
||||
const implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`;
|
||||
function normalizeSlashes(path) {
|
||||
return path.replace(backslashRegExp, directorySeparator);
|
||||
}
|
||||
function isVolumeCharacter(charCode) {
|
||||
return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
|
||||
(charCode >= 65 /* A */ && charCode <= 90 /* Z */);
|
||||
}
|
||||
function getFileUrlVolumeSeparatorEnd(url, start) {
|
||||
const ch0 = url.charCodeAt(start);
|
||||
if (ch0 === 58 /* colon */)
|
||||
return start + 1;
|
||||
if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
|
||||
const ch2 = url.charCodeAt(start + 2);
|
||||
if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
|
||||
return start + 3;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
function getEncodedRootLength(path) {
|
||||
if (!path)
|
||||
return 0;
|
||||
const ch0 = path.charCodeAt(0);
|
||||
// POSIX or UNC
|
||||
if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
|
||||
if (path.charCodeAt(1) !== ch0)
|
||||
return 1; // POSIX: "/" (or non-normalized "\")
|
||||
const p1 = path.indexOf(ch0 === 47 /* slash */ ? directorySeparator : altDirectorySeparator, 2);
|
||||
if (p1 < 0)
|
||||
return path.length; // UNC: "//server" or "\\server"
|
||||
return p1 + 1; // UNC: "//server/" or "\\server\"
|
||||
}
|
||||
// DOS
|
||||
if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
|
||||
const ch2 = path.charCodeAt(2);
|
||||
if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
|
||||
return 3; // DOS: "c:/" or "c:\"
|
||||
if (path.length === 2)
|
||||
return 2; // DOS: "c:" (but not "c:d")
|
||||
}
|
||||
// URL
|
||||
const schemeEnd = path.indexOf(urlSchemeSeparator);
|
||||
if (schemeEnd !== -1) {
|
||||
const authorityStart = schemeEnd + urlSchemeSeparator.length;
|
||||
const authorityEnd = path.indexOf(directorySeparator, authorityStart);
|
||||
if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
|
||||
// For local "file" URLs, include the leading DOS volume (if present).
|
||||
// Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
|
||||
// special case interpreted as "the machine from which the URL is being interpreted".
|
||||
const scheme = path.slice(0, schemeEnd);
|
||||
const authority = path.slice(authorityStart, authorityEnd);
|
||||
if (scheme === "file" && (authority === "" || authority === "localhost") &&
|
||||
isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
|
||||
const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
|
||||
if (volumeSeparatorEnd !== -1) {
|
||||
if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
|
||||
// URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
|
||||
return ~(volumeSeparatorEnd + 1);
|
||||
}
|
||||
if (volumeSeparatorEnd === path.length) {
|
||||
// URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
|
||||
// but not "file:///c:d" or "file:///c%3ad"
|
||||
return ~volumeSeparatorEnd;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
|
||||
}
|
||||
return ~path.length; // URL: "file://server", "http://server"
|
||||
}
|
||||
// relative
|
||||
return 0;
|
||||
}
|
||||
function getRootLength(path) {
|
||||
const rootLength = getEncodedRootLength(path);
|
||||
return rootLength < 0 ? ~rootLength : rootLength;
|
||||
}
|
||||
function hasTrailingDirectorySeparator(path) {
|
||||
if (path.length === 0)
|
||||
return false;
|
||||
const ch = path.charCodeAt(path.length - 1);
|
||||
return ch === 47 /* slash */ || ch === 92 /* backslash */;
|
||||
}
|
||||
function ensureTrailingDirectorySeparator(path) {
|
||||
if (!hasTrailingDirectorySeparator(path)) {
|
||||
return path + directorySeparator;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
function combinePaths(path, ...paths) {
|
||||
if (path)
|
||||
path = normalizeSlashes(path);
|
||||
for (let relativePath of paths) {
|
||||
if (!relativePath)
|
||||
continue;
|
||||
relativePath = normalizeSlashes(relativePath);
|
||||
if (!path || getRootLength(relativePath) !== 0) {
|
||||
path = relativePath;
|
||||
}
|
||||
else {
|
||||
path = ensureTrailingDirectorySeparator(path) + relativePath;
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
exports.combinePaths = combinePaths;
|
||||
function lastOrUndefined(array) {
|
||||
return array.length === 0 ? undefined : array[array.length - 1];
|
||||
}
|
||||
function pathComponents(path, rootLength) {
|
||||
const root = path.substring(0, rootLength);
|
||||
const rest = path.substring(rootLength).split(directorySeparator);
|
||||
if (rest.length && !lastOrUndefined(rest))
|
||||
rest.pop();
|
||||
return [root, ...rest];
|
||||
}
|
||||
function getPathComponents(path, currentDirectory = "") {
|
||||
path = combinePaths(currentDirectory, path);
|
||||
const rootLength = getRootLength(path);
|
||||
return pathComponents(path, rootLength);
|
||||
}
|
||||
function reducePathComponents(components) {
|
||||
if (!some(components))
|
||||
return [];
|
||||
const reduced = [components[0]];
|
||||
for (let i = 1; i < components.length; i++) {
|
||||
const component = components[i];
|
||||
if (!component)
|
||||
continue;
|
||||
if (component === ".")
|
||||
continue;
|
||||
if (component === "..") {
|
||||
if (reduced.length > 1) {
|
||||
if (reduced[reduced.length - 1] !== "..") {
|
||||
reduced.pop();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (reduced[0])
|
||||
continue;
|
||||
}
|
||||
reduced.push(component);
|
||||
}
|
||||
return reduced;
|
||||
}
|
||||
function getPathFromPathComponents(pathComponents) {
|
||||
if (pathComponents.length === 0)
|
||||
return "";
|
||||
const root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
|
||||
return root + pathComponents.slice(1).join(directorySeparator);
|
||||
}
|
||||
function resolvePath(path, ...paths) {
|
||||
const combined = some(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path);
|
||||
const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined)));
|
||||
return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
|
||||
}
|
||||
exports.resolvePath = resolvePath;
|
||||
function directoryExists(path) {
|
||||
let res = UE.FileSystemOperation.DirectoryExists(path);
|
||||
return res;
|
||||
}
|
||||
exports.directoryExists = directoryExists;
|
||||
function createDirectory(path) {
|
||||
UE.FileSystemOperation.CreateDirectory(path);
|
||||
}
|
||||
exports.createDirectory = createDirectory;
|
||||
function realpath(path) {
|
||||
return path;
|
||||
}
|
||||
exports.realpath = realpath;
|
||||
const emptyArray = [];
|
||||
const emptyFileSystemEntries = {
|
||||
files: emptyArray,
|
||||
directories: emptyArray
|
||||
};
|
||||
function getAccessibleFileSystemEntries(path) {
|
||||
try {
|
||||
const files = [];
|
||||
const directories = [];
|
||||
let dirArray = UE.FileSystemOperation.GetDirectories(path);
|
||||
for (var i = 0; i < dirArray.Num(); i++) {
|
||||
directories.push(dirArray.Get(i));
|
||||
}
|
||||
let fileArray = UE.FileSystemOperation.GetFiles(path);
|
||||
for (var i = 0; i < fileArray.Num(); i++) {
|
||||
files.push(fileArray.Get(i));
|
||||
}
|
||||
return { files, directories };
|
||||
}
|
||||
catch (e) {
|
||||
return emptyFileSystemEntries;
|
||||
}
|
||||
}
|
||||
exports.getAccessibleFileSystemEntries = getAccessibleFileSystemEntries;
|
||||
function normalizePath(path) {
|
||||
return resolvePath(path);
|
||||
}
|
||||
exports.normalizePath = normalizePath;
|
||||
function map(array, f) {
|
||||
let result;
|
||||
if (array) {
|
||||
result = [];
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
result.push(f(array[i], i));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function isArray(value) {
|
||||
return Array.isArray ? Array.isArray(value) : value instanceof Array;
|
||||
}
|
||||
function toOffset(array, offset) {
|
||||
return offset < 0 ? array.length + offset : offset;
|
||||
}
|
||||
function addRange(to, from, start, end) {
|
||||
if (from === undefined || from.length === 0)
|
||||
return to;
|
||||
if (to === undefined)
|
||||
return from.slice(start, end);
|
||||
start = start === undefined ? 0 : toOffset(from, start);
|
||||
end = end === undefined ? from.length : toOffset(from, end);
|
||||
for (let i = start; i < end && i < from.length; i++) {
|
||||
if (from[i] !== undefined) {
|
||||
to.push(from[i]);
|
||||
}
|
||||
}
|
||||
return to;
|
||||
}
|
||||
function append(to, value) {
|
||||
if (value === undefined)
|
||||
return to;
|
||||
if (to === undefined)
|
||||
return [value];
|
||||
to.push(value);
|
||||
return to;
|
||||
}
|
||||
function flatMap(array, mapfn) {
|
||||
let result;
|
||||
if (array) {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
const v = mapfn(array[i], i);
|
||||
if (v) {
|
||||
if (isArray(v)) {
|
||||
result = addRange(result, v);
|
||||
}
|
||||
else {
|
||||
result = append(result, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result || emptyArray;
|
||||
}
|
||||
function getNormalizedPathComponents(path, currentDirectory) {
|
||||
return reducePathComponents(getPathComponents(path, currentDirectory));
|
||||
}
|
||||
function last(array) {
|
||||
return array[array.length - 1];
|
||||
}
|
||||
function removeTrailingDirectorySeparator(path) {
|
||||
if (hasTrailingDirectorySeparator(path)) {
|
||||
return path.substr(0, path.length - 1);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
function isImplicitGlob(lastPathComponent) {
|
||||
return !/[.*?]/.test(lastPathComponent);
|
||||
}
|
||||
function getSubPatternFromSpec(spec, basePath, usage, { singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter }) {
|
||||
let subpattern = "";
|
||||
let hasWrittenComponent = false;
|
||||
const components = getNormalizedPathComponents(spec, basePath);
|
||||
const lastComponent = last(components);
|
||||
if (usage !== "exclude" && lastComponent === "**") {
|
||||
return undefined;
|
||||
}
|
||||
// getNormalizedPathComponents includes the separator for the root component.
|
||||
// We need to remove to create our regex correctly.
|
||||
components[0] = removeTrailingDirectorySeparator(components[0]);
|
||||
if (isImplicitGlob(lastComponent)) {
|
||||
components.push("**", "*");
|
||||
}
|
||||
let optionalCount = 0;
|
||||
for (let component of components) {
|
||||
if (component === "**") {
|
||||
subpattern += doubleAsteriskRegexFragment;
|
||||
}
|
||||
else {
|
||||
if (usage === "directories") {
|
||||
subpattern += "(";
|
||||
optionalCount++;
|
||||
}
|
||||
if (hasWrittenComponent) {
|
||||
subpattern += directorySeparator;
|
||||
}
|
||||
if (usage !== "exclude") {
|
||||
let componentPattern = "";
|
||||
// The * and ? wildcards should not match directories or files that start with . if they
|
||||
// appear first in a component. Dotted directories and files can be included explicitly
|
||||
// like so: **/.*/.*
|
||||
if (component.charCodeAt(0) === 42 /* asterisk */) {
|
||||
componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
|
||||
component = component.substr(1);
|
||||
}
|
||||
else if (component.charCodeAt(0) === 63 /* question */) {
|
||||
componentPattern += "[^./]";
|
||||
component = component.substr(1);
|
||||
}
|
||||
componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
|
||||
// Patterns should not include subfolders like node_modules unless they are
|
||||
// explicitly included as part of the path.
|
||||
//
|
||||
// As an optimization, if the component pattern is the same as the component,
|
||||
// then there definitely were no wildcard characters and we do not need to
|
||||
// add the exclusion pattern.
|
||||
if (componentPattern !== component) {
|
||||
subpattern += implicitExcludePathRegexPattern;
|
||||
}
|
||||
subpattern += componentPattern;
|
||||
}
|
||||
else {
|
||||
subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
|
||||
}
|
||||
}
|
||||
//modify by john, 如果使用相对路径,最后面的pattern会添加一个/到开头,导致匹配失败
|
||||
// hasWrittenComponent = !!component;
|
||||
//modify by zombie,上述改动会导致Mac无法watch到TS文件,据车神说现在已经不用相对路径,因此回滚
|
||||
hasWrittenComponent = true;
|
||||
}
|
||||
while (optionalCount > 0) {
|
||||
subpattern += ")?";
|
||||
optionalCount--;
|
||||
}
|
||||
return subpattern;
|
||||
}
|
||||
function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
|
||||
return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
|
||||
}
|
||||
const filesMatcher = {
|
||||
/**
|
||||
* Matches any single directory segment unless it is the last segment and a .min.js file
|
||||
* Breakdown:
|
||||
* [^./] # matches everything up to the first . character (excluding directory separators)
|
||||
* (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension
|
||||
*/
|
||||
singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
|
||||
/**
|
||||
* Regex for the ** wildcard. Matches any number of subdirectories. When used for including
|
||||
* files or directories, does not match subdirectories that start with a . character
|
||||
*/
|
||||
doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`,
|
||||
replaceWildcardCharacter: match => replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment)
|
||||
};
|
||||
const directoriesMatcher = {
|
||||
singleAsteriskRegexFragment: "[^/]*",
|
||||
/**
|
||||
* Regex for the ** wildcard. Matches any number of subdirectories. When used for including
|
||||
* files or directories, does not match subdirectories that start with a . character
|
||||
*/
|
||||
doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`,
|
||||
replaceWildcardCharacter: match => replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment)
|
||||
};
|
||||
const excludeMatcher = {
|
||||
singleAsteriskRegexFragment: "[^/]*",
|
||||
doubleAsteriskRegexFragment: "(/.+?)?",
|
||||
replaceWildcardCharacter: match => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment)
|
||||
};
|
||||
const wildcardMatchers = {
|
||||
files: filesMatcher,
|
||||
directories: directoriesMatcher,
|
||||
exclude: excludeMatcher
|
||||
};
|
||||
function getRegularExpressionsForWildcards(specs, basePath, usage) {
|
||||
if (specs === undefined || specs.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return flatMap(specs, spec => spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]));
|
||||
}
|
||||
function getRegularExpressionForWildcard(specs, basePath, usage) {
|
||||
const patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
|
||||
if (!patterns || !patterns.length) {
|
||||
return undefined;
|
||||
}
|
||||
const pattern = patterns.map(pattern => `(${pattern})`).join("|");
|
||||
// If excluding, match "foo/bar/baz...", but if including, only allow "foo".
|
||||
const terminator = usage === "exclude" ? "($|/)" : "$";
|
||||
return `^(${pattern})${terminator}`;
|
||||
}
|
||||
function isRootedDiskPath(path) {
|
||||
return getEncodedRootLength(path) > 0;
|
||||
}
|
||||
function contains(array, value, equalityComparer = equateValues) {
|
||||
if (array) {
|
||||
for (const v of array) {
|
||||
if (equalityComparer(v, value)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function equateStringsCaseInsensitive(a, b) {
|
||||
return a === b
|
||||
|| a !== undefined
|
||||
&& b !== undefined
|
||||
&& a.toUpperCase() === b.toUpperCase();
|
||||
}
|
||||
function equateValues(a, b) {
|
||||
return a === b;
|
||||
}
|
||||
function equateStringsCaseSensitive(a, b) {
|
||||
return equateValues(a, b);
|
||||
}
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
|
||||
if (typeof extensions === "string")
|
||||
extensions = [extensions];
|
||||
for (let extension of extensions) {
|
||||
if (!startsWith(extension, "."))
|
||||
extension = "." + extension;
|
||||
if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
|
||||
const pathExtension = path.slice(path.length - extension.length);
|
||||
if (stringEqualityComparer(pathExtension, extension)) {
|
||||
return pathExtension;
|
||||
}
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
function getAnyExtensionFromPath(path, extensions, ignoreCase) {
|
||||
// Retrieves any string from the final "." onwards from a base file name.
|
||||
// Unlike extensionFromPath, which throws an exception on unrecognized extensions.
|
||||
if (extensions) {
|
||||
return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
|
||||
}
|
||||
const baseFileName = getBaseFileName(path);
|
||||
const extensionIndex = baseFileName.lastIndexOf(".");
|
||||
if (extensionIndex >= 0) {
|
||||
return baseFileName.substring(extensionIndex);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
function getBaseFileName(path, extensions, ignoreCase) {
|
||||
path = normalizeSlashes(path);
|
||||
// if the path provided is itself the root, then it has not file name.
|
||||
const rootLength = getRootLength(path);
|
||||
if (rootLength === path.length)
|
||||
return "";
|
||||
// return the trailing portion of the path starting after the last (non-terminal) directory
|
||||
// separator but not including any trailing directory separator.
|
||||
path = removeTrailingDirectorySeparator(path);
|
||||
const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1));
|
||||
const extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
|
||||
return extension ? name.slice(0, name.length - extension.length) : name;
|
||||
}
|
||||
exports.getBaseFileName = getBaseFileName;
|
||||
function stringContains(str, substring) {
|
||||
return str.indexOf(substring) !== -1;
|
||||
}
|
||||
function hasExtension(fileName) {
|
||||
return stringContains(getBaseFileName(fileName), ".");
|
||||
}
|
||||
function indexOfAnyCharCode(text, charCodes, start) {
|
||||
for (let i = start || 0; i < text.length; i++) {
|
||||
if (contains(charCodes, text.charCodeAt(i))) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
const wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
|
||||
function getDirectoryPath(path) {
|
||||
path = normalizeSlashes(path);
|
||||
// If the path provided is itself the root, then return it.
|
||||
const rootLength = getRootLength(path);
|
||||
if (rootLength === path.length)
|
||||
return path;
|
||||
// return the leading portion of the path up to the last (non-terminal) directory separator
|
||||
// but not including any trailing directory separator.
|
||||
path = removeTrailingDirectorySeparator(path);
|
||||
return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator)));
|
||||
}
|
||||
exports.getDirectoryPath = getDirectoryPath;
|
||||
function getIncludeBasePath(absolute) {
|
||||
const wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes);
|
||||
if (wildcardOffset < 0) {
|
||||
// No "*" or "?" in the path
|
||||
return !hasExtension(absolute)
|
||||
? absolute
|
||||
: removeTrailingDirectorySeparator(getDirectoryPath(absolute));
|
||||
}
|
||||
return absolute.substring(0, absolute.lastIndexOf(directorySeparator, wildcardOffset));
|
||||
}
|
||||
function compareComparableValues(a, b) {
|
||||
return a === b ? 0 /* EqualTo */ :
|
||||
a === undefined ? -1 /* LessThan */ :
|
||||
b === undefined ? 1 /* GreaterThan */ :
|
||||
a < b ? -1 /* LessThan */ :
|
||||
1 /* GreaterThan */;
|
||||
}
|
||||
function compareStringsCaseInsensitive(a, b) {
|
||||
if (a === b)
|
||||
return 0 /* EqualTo */;
|
||||
if (a === undefined)
|
||||
return -1 /* LessThan */;
|
||||
if (b === undefined)
|
||||
return 1 /* GreaterThan */;
|
||||
a = a.toUpperCase();
|
||||
b = b.toUpperCase();
|
||||
return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
|
||||
}
|
||||
function compareStringsCaseSensitive(a, b) {
|
||||
return compareComparableValues(a, b);
|
||||
}
|
||||
function getStringComparer(ignoreCase) {
|
||||
return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
|
||||
}
|
||||
function containsPath(parent, child, currentDirectory, ignoreCase) {
|
||||
if (typeof currentDirectory === "string") {
|
||||
parent = combinePaths(currentDirectory, parent);
|
||||
child = combinePaths(currentDirectory, child);
|
||||
}
|
||||
else if (typeof currentDirectory === "boolean") {
|
||||
ignoreCase = currentDirectory;
|
||||
}
|
||||
if (parent === undefined || child === undefined)
|
||||
return false;
|
||||
if (parent === child)
|
||||
return true;
|
||||
const parentComponents = reducePathComponents(getPathComponents(parent));
|
||||
const childComponents = reducePathComponents(getPathComponents(child));
|
||||
if (childComponents.length < parentComponents.length) {
|
||||
return false;
|
||||
}
|
||||
const componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
|
||||
for (let i = 0; i < parentComponents.length; i++) {
|
||||
const equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
|
||||
if (!equalityComparer(parentComponents[i], childComponents[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function every(array, callback) {
|
||||
if (array) {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if (!callback(array[i], i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function getBasePaths(path, includes, useCaseSensitiveFileNames) {
|
||||
// Storage for our results in the form of literal paths (e.g. the paths as written by the user).
|
||||
const basePaths = [path];
|
||||
if (includes) {
|
||||
// Storage for literal base paths amongst the include patterns.
|
||||
const includeBasePaths = [];
|
||||
for (const include of includes) {
|
||||
// We also need to check the relative paths by converting them to absolute and normalizing
|
||||
// in case they escape the base path (e.g "..\somedirectory")
|
||||
const absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include));
|
||||
// Append the literal and canonical candidate base paths.
|
||||
includeBasePaths.push(getIncludeBasePath(absolute));
|
||||
}
|
||||
// Sort the offsets array using either the literal or canonical path representations.
|
||||
includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames));
|
||||
// Iterate over each include base path and include unique base paths that are not a
|
||||
// subpath of an existing base path
|
||||
for (const includeBasePath of includeBasePaths) {
|
||||
if (every(basePaths, basePath => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) {
|
||||
basePaths.push(includeBasePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
return basePaths;
|
||||
}
|
||||
function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
|
||||
path = normalizePath(path);
|
||||
currentDirectory = normalizePath(currentDirectory);
|
||||
const absolutePath = combinePaths(currentDirectory, path);
|
||||
return {
|
||||
includeFilePatterns: map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), pattern => `^${pattern}$`),
|
||||
includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
|
||||
includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
|
||||
excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
|
||||
basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
|
||||
};
|
||||
}
|
||||
function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
|
||||
return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
|
||||
}
|
||||
function createMap() {
|
||||
return new Map();
|
||||
}
|
||||
function identity(x) { return x; }
|
||||
function toLowerCase(x) { return x.toLowerCase(); }
|
||||
function createGetCanonicalFileName(useCaseSensitiveFileNames) {
|
||||
return useCaseSensitiveFileNames ? identity : toLowerCase;
|
||||
}
|
||||
function flatten(array) {
|
||||
const result = [];
|
||||
for (const v of array) {
|
||||
if (v) {
|
||||
if (isArray(v)) {
|
||||
addRange(result, v);
|
||||
}
|
||||
else {
|
||||
result.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function endsWith(str, suffix) {
|
||||
const expectedPos = str.length - suffix.length;
|
||||
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
function fileExtensionIs(path, extension) {
|
||||
return path.length > extension.length && endsWith(path, extension);
|
||||
}
|
||||
function fileExtensionIsOneOf(path, extensions) {
|
||||
for (const extension of extensions) {
|
||||
if (fileExtensionIs(path, extension)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function sort(array, comparer) {
|
||||
return (array.length === 0 ? array : array.slice().sort(comparer));
|
||||
}
|
||||
function findIndex(array, predicate, startIndex) {
|
||||
for (let i = startIndex || 0; i < array.length; i++) {
|
||||
if (predicate(array[i], i)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
|
||||
path = normalizePath(path);
|
||||
currentDirectory = normalizePath(currentDirectory);
|
||||
const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
|
||||
const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(pattern => getRegexFromPattern(pattern, useCaseSensitiveFileNames));
|
||||
const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
|
||||
const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
|
||||
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
|
||||
// If there are no "includes", then just put everything in results[0].
|
||||
const results = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]];
|
||||
const visited = createMap();
|
||||
const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames);
|
||||
for (const basePath of patterns.basePaths) {
|
||||
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
|
||||
}
|
||||
return flatten(results);
|
||||
function visitDirectory(path, absolutePath, depth) {
|
||||
const canonicalPath = toCanonical(realpath(absolutePath));
|
||||
if (visited.has(canonicalPath))
|
||||
return;
|
||||
visited.set(canonicalPath, true);
|
||||
const { files, directories } = getFileSystemEntries(path);
|
||||
for (const current of sort(files, compareStringsCaseSensitive)) {
|
||||
const name = combinePaths(path, current);
|
||||
const absoluteName = combinePaths(absolutePath, current);
|
||||
if (extensions && !fileExtensionIsOneOf(name, extensions))
|
||||
continue;
|
||||
if (excludeRegex && excludeRegex.test(absoluteName))
|
||||
continue;
|
||||
if (!includeFileRegexes) {
|
||||
results[0].push(name);
|
||||
}
|
||||
else {
|
||||
const includeIndex = findIndex(includeFileRegexes, re => re.test(absoluteName));
|
||||
if (includeIndex !== -1) {
|
||||
results[includeIndex].push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (depth !== undefined) {
|
||||
depth--;
|
||||
if (depth === 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (const current of sort(directories, compareStringsCaseSensitive)) {
|
||||
const name = combinePaths(path, current);
|
||||
const absoluteName = combinePaths(absolutePath, current);
|
||||
if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
|
||||
(!excludeRegex || !excludeRegex.test(absoluteName))) {
|
||||
visitDirectory(name, absoluteName, depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.matchFiles = matchFiles;
|
||||
const extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
|
||||
function removeFileExtension(path) {
|
||||
for (const ext of extensionsToRemove) {
|
||||
const extensionless = tryRemoveExtension(path, ext);
|
||||
if (extensionless !== undefined) {
|
||||
return extensionless;
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
exports.removeFileExtension = removeFileExtension;
|
||||
function tryRemoveExtension(path, extension) {
|
||||
return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
|
||||
}
|
||||
function removeExtension(path, extension) {
|
||||
return path.substring(0, path.length - extension.length);
|
||||
}
|
||||
exports.removeExtension = removeExtension;
|
||||
function getSourceFilePathInNewDir(fileName, currentDirectory, commonSourceDirectory, newDirPath) {
|
||||
return getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, createGetCanonicalFileName(true));
|
||||
}
|
||||
exports.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
|
||||
function getNormalizedAbsolutePath(fileName, currentDirectory) {
|
||||
return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
|
||||
}
|
||||
function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
|
||||
let sourceFilePath = getNormalizedAbsolutePath(fileName, currentDirectory);
|
||||
const isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
|
||||
sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
|
||||
return combinePaths(newDirPath, sourceFilePath);
|
||||
}
|
||||
//-----------------------end copy form typescript--------------------
|
||||
//# sourceMappingURL=TypeScriptInternal.js.map
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "PuertsEditor",
|
||||
"version": "1.0.0",
|
||||
"description": "PuertsEditor",
|
||||
"scripts": {},
|
||||
"dependencies": {
|
||||
"typescript": "4.7.4"
|
||||
},
|
||||
"devDependencies": {}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
const ffi_bindings = require('ffi_bindings');
|
||||
const typeInfo = require('type').typeInfo;
|
||||
const pointer = typeInfo('pointer');
|
||||
const ffi_call = ffi_bindings.ffi_call;
|
||||
const UTF8Length = ffi_bindings.UTF8Length;
|
||||
const writeUTF8String = ffi_bindings.writeUTF8String;
|
||||
const readUTF8String = ffi_bindings.readUTF8String;
|
||||
|
||||
function stringToCString(str) {
|
||||
let buffLen = UTF8Length(str);
|
||||
let buff = new Uint8Array(buffLen + 1);
|
||||
writeUTF8String(buff, str);
|
||||
return buff;
|
||||
}
|
||||
|
||||
|
||||
function id(x) {
|
||||
return x;
|
||||
}
|
||||
|
||||
function allocCif(returnType, parameterTypes, abi, fixArgNum) {
|
||||
let param_ffi_types = parameterTypes.map(t => t.ffi_type);
|
||||
|
||||
let cifPtr = new Uint8Array(ffi_bindings.FFI_CIF_SIZE);
|
||||
let status
|
||||
if (typeof fixArgNum === 'number') {
|
||||
status = ffi_bindings.ffi_prep_cif_var(cifPtr, abi, fixArgNum, parameterTypes.length, returnType.ffi_type, pointer.alloc(...param_ffi_types));
|
||||
} else {
|
||||
status = ffi_bindings.ffi_prep_cif(cifPtr, abi, parameterTypes.length, returnType.ffi_type, pointer.alloc(...param_ffi_types));
|
||||
}
|
||||
if (status != 0) {
|
||||
throw new Error(`call ffi_prep_cif fail, status=${status}`);
|
||||
}
|
||||
return cifPtr;
|
||||
}
|
||||
|
||||
function binding(func, abi, returnType, parameterTypes, fixArgNum) {
|
||||
if (typeof abi !== 'number') {
|
||||
fixArgNum = parameterTypes;
|
||||
parameterTypes = returnType;
|
||||
returnType = abi;
|
||||
abi = ffi_bindings.FFI_DEFAULT_ABI;
|
||||
}
|
||||
|
||||
const argsProcessers = parameterTypes.map(t => t === 'cstring' ? stringToCString : id);
|
||||
const resultProcesser = returnType === 'cstring' ? readUTF8String : id;
|
||||
returnType = typeInfo(returnType);
|
||||
parameterTypes = parameterTypes.map(t => typeInfo(t));
|
||||
const cifPtr = allocCif(returnType, parameterTypes, abi, fixArgNum);
|
||||
let argPtrs = parameterTypes.map(t => t.alloc());
|
||||
let retPtr = returnType.alloc();
|
||||
const ffi_call_args = pointer.alloc(...argPtrs);
|
||||
const expectArgNum = parameterTypes.length;
|
||||
|
||||
function wrap(...args) {
|
||||
if (args.length != expectArgNum) {
|
||||
throw new Error(`expect ${expectArgNum} argument but got ${args.length}`);
|
||||
}
|
||||
for (var i = 0; i < expectArgNum; i++) {
|
||||
args[i] = argsProcessers[i](args[i]);
|
||||
parameterTypes[i].write(argPtrs[i], args[i]);
|
||||
}
|
||||
ffi_call(cifPtr, func, retPtr, ffi_call_args);
|
||||
return resultProcesser(returnType.read(retPtr));
|
||||
}
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function allocClosure(func, abi, returnType, parameterTypes) {
|
||||
if (typeof abi !== 'number') {
|
||||
parameterTypes = returnType;
|
||||
returnType = abi;
|
||||
abi = ffi_bindings.FFI_DEFAULT_ABI;
|
||||
}
|
||||
returnType = typeInfo(returnType);
|
||||
parameterTypes = parameterTypes.map(t => typeInfo(t));
|
||||
const cifPtr = allocCif(returnType, parameterTypes, abi);
|
||||
|
||||
return ffi_bindings.ffi_alloc_closure(cifPtr, function(retPtr, argPtrs) {
|
||||
try {
|
||||
var args = [];
|
||||
for (var i = 0; i < parameterTypes.length; i++) {
|
||||
var argPtr = pointer.read(argPtrs, i * pointer.size, parameterTypes[i].size);
|
||||
args.push(parameterTypes[i].read(argPtr));
|
||||
}
|
||||
var result = func.apply(null, args);
|
||||
returnType.write(retPtr, result);
|
||||
} catch (e) {
|
||||
console.error('js callback exception, msg=', e);
|
||||
}
|
||||
}, returnType.size);
|
||||
}
|
||||
|
||||
function nativeFunctionPtr(cl) {
|
||||
return pointer.read(cl);
|
||||
}
|
||||
|
||||
function freeClosure(cl) {
|
||||
ffi_bindings.ffi_free_closure(cl);
|
||||
}
|
||||
|
||||
exports.binding = binding;
|
||||
exports.closure = {
|
||||
alloc: allocClosure,
|
||||
func: nativeFunctionPtr,
|
||||
free: freeClosure
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
function validateNumber(value, type) {
|
||||
if (typeof value !== 'number')
|
||||
throw new Error(type + " expect an number but got " + value);
|
||||
}
|
||||
|
||||
function boundsError(value, length, type) {
|
||||
if (Math.floor(value) !== value) {
|
||||
validateNumber(value, type);
|
||||
throw new Error((type || 'offset') + ' expect an integer but got ' + value);
|
||||
}
|
||||
|
||||
if (length < 0)
|
||||
throw new Error("out of bound");
|
||||
|
||||
throw new Error(type || 'offset' +
|
||||
`expect >= ${type ? 1 : 0} and <= ${length} but got` + value);
|
||||
}
|
||||
|
||||
function checkBounds(buf, offset, byteLength) {
|
||||
validateNumber(offset, 'offset');
|
||||
if (buf[offset] === undefined || buf[offset + byteLength] === undefined)
|
||||
boundsError(offset, buf.length - (byteLength + 1));
|
||||
}
|
||||
|
||||
|
||||
function writeU_Int8(buf, value, offset, min, max) {
|
||||
value = +value;
|
||||
// `checkInt()` can not be used here because it checks two entries.
|
||||
validateNumber(offset, 'offset');
|
||||
if (value > max || value < min) {
|
||||
throw new Error(`value expect >= ${min} and <= ${max} but got ` + value);
|
||||
}
|
||||
if (buf[offset] === undefined)
|
||||
boundsError(offset, buf.length - 1);
|
||||
|
||||
buf[offset] = value;
|
||||
return offset + 1;
|
||||
}
|
||||
|
||||
function readInt8(buff, offset = 0) {
|
||||
validateNumber(offset, 'offset');
|
||||
const val = buff[offset];
|
||||
if (val === undefined)
|
||||
boundsError(offset, buff.length - 1);
|
||||
|
||||
return val | (val & 2 ** 7) * 0x1fffffe;
|
||||
}
|
||||
|
||||
function writeInt8(buf, value, offset = 0) {
|
||||
return writeU_Int8(buf, value, offset, -0x80, 0x7f);
|
||||
}
|
||||
|
||||
function readUInt8(offset = 0) {
|
||||
validateNumber(offset, 'offset');
|
||||
const val = this[offset];
|
||||
if (val === undefined)
|
||||
boundsError(offset, this.length - 1);
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
function writeUInt8(value, offset = 0) {
|
||||
return writeU_Int8(this, value, offset, 0, 0xff);
|
||||
}
|
||||
|
||||
const int16Array = new Int16Array(1);
|
||||
const uInt8Int6Array = new Uint8Array(int16Array.buffer);
|
||||
|
||||
function readInt16(buff, offset = 0) {
|
||||
validateNumber(offset, 'offset');
|
||||
const first = buff[offset];
|
||||
const last = buff[offset + 1];
|
||||
if (first === undefined || last === undefined)
|
||||
boundsError(offset, buff.length - 2);
|
||||
|
||||
uInt8Int6Array[0] = first;
|
||||
uInt8Int6Array[1] = last;
|
||||
return int16Array[0];
|
||||
}
|
||||
|
||||
function writeInt16(buff, val, offset = 0) {
|
||||
val = +val;
|
||||
checkBounds(buff, offset, 1);
|
||||
|
||||
int16Array[0] = val;
|
||||
buff[offset++] = uInt8Int6Array[0];
|
||||
buff[offset++] = uInt8Int6Array[1];
|
||||
return offset;
|
||||
}
|
||||
|
||||
const uint16Array = new Uint16Array(1);
|
||||
const uint8Uint16Array = new Uint8Array(uint16Array.buffer);
|
||||
|
||||
function readUInt16(buff, offset = 0) {
|
||||
validateNumber(offset, 'offset');
|
||||
const first = buff[offset];
|
||||
const last = buff[offset + 1];
|
||||
if (first === undefined || last === undefined)
|
||||
boundsError(offset, buff.length - 2);
|
||||
|
||||
uint8Uint16Array[0] = first;
|
||||
uint8Uint16Array[1] = last;
|
||||
return uint16Array[0];
|
||||
}
|
||||
|
||||
function writeUInt16(buff, val, offset = 0) {
|
||||
val = +val;
|
||||
checkBounds(buff, offset, 1);
|
||||
|
||||
uint16Array[0] = val;
|
||||
buff[offset++] = uint8Uint16Array[0];
|
||||
buff[offset++] = uint8Uint16Array[1];
|
||||
return offset;
|
||||
}
|
||||
|
||||
const int32Array = new Int32Array(1);
|
||||
const uint8Int32Array = new Uint8Array(int32Array.buffer);
|
||||
|
||||
function readInt32(buff, offset = 0) {
|
||||
validateNumber(offset, 'offset');
|
||||
const first = buff[offset];
|
||||
const last = buff[offset + 3];
|
||||
if (first === undefined || last === undefined)
|
||||
boundsError(offset, buff.length - 4);
|
||||
|
||||
uint8Int32Array[0] = first;
|
||||
uint8Int32Array[1] = buff[++offset];
|
||||
uint8Int32Array[2] = buff[++offset];
|
||||
uint8Int32Array[3] = last;
|
||||
return int32Array[0];
|
||||
}
|
||||
|
||||
function writeInt32(buff, val, offset = 0) {
|
||||
val = +val;
|
||||
checkBounds(buff, offset, 3);
|
||||
|
||||
int32Array[0] = val;
|
||||
buff[offset++] = uint8Int32Array[0];
|
||||
buff[offset++] = uint8Int32Array[1];
|
||||
buff[offset++] = uint8Int32Array[2];
|
||||
buff[offset++] = uint8Int32Array[3];
|
||||
return offset;
|
||||
}
|
||||
|
||||
const uint32Array = new Uint32Array(1);
|
||||
const uint8Uint32Array = new Uint8Array(uint32Array.buffer);
|
||||
|
||||
function readUInt32(buff, offset = 0) {
|
||||
validateNumber(offset, 'offset');
|
||||
const first = buff[offset];
|
||||
const last = buff[offset + 3];
|
||||
if (first === undefined || last === undefined)
|
||||
boundsError(offset, buff.length - 4);
|
||||
|
||||
uint8Uint32Array[0] = first;
|
||||
uint8Uint32Array[1] = buff[++offset];
|
||||
uint8Uint32Array[2] = buff[++offset];
|
||||
uint8Uint32Array[3] = last;
|
||||
return uint32Array[0];
|
||||
}
|
||||
|
||||
function writeUInt32(buff, val, offset = 0) {
|
||||
val = +val;
|
||||
checkBounds(buff, offset, 3);
|
||||
|
||||
uint32Array[0] = val;
|
||||
buff[offset++] = uint8Uint32Array[0];
|
||||
buff[offset++] = uint8Uint32Array[1];
|
||||
buff[offset++] = uint8Uint32Array[2];
|
||||
buff[offset++] = uint8Uint32Array[3];
|
||||
return offset;
|
||||
}
|
||||
|
||||
const float32Array = new Float32Array(1);
|
||||
const uInt8Float32Array = new Uint8Array(float32Array.buffer);
|
||||
|
||||
function readFloat(buff, offset = 0) {
|
||||
validateNumber(offset, 'offset');
|
||||
const first = buff[offset];
|
||||
const last = buff[offset + 3];
|
||||
if (first === undefined || last === undefined)
|
||||
boundsError(offset, buff.length - 4);
|
||||
|
||||
uInt8Float32Array[0] = first;
|
||||
uInt8Float32Array[1] = buff[++offset];
|
||||
uInt8Float32Array[2] = buff[++offset];
|
||||
uInt8Float32Array[3] = last;
|
||||
return float32Array[0];
|
||||
}
|
||||
|
||||
function writeFloat(buff, val, offset = 0) {
|
||||
val = +val;
|
||||
checkBounds(buff, offset, 3);
|
||||
|
||||
float32Array[0] = val;
|
||||
buff[offset++] = uInt8Float32Array[0];
|
||||
buff[offset++] = uInt8Float32Array[1];
|
||||
buff[offset++] = uInt8Float32Array[2];
|
||||
buff[offset++] = uInt8Float32Array[3];
|
||||
return offset;
|
||||
}
|
||||
|
||||
const float64Array = new Float64Array(1);
|
||||
const uInt8Float64Array = new Uint8Array(float64Array.buffer);
|
||||
|
||||
function readDouble(buff, offset = 0) {
|
||||
const first = buff[offset];
|
||||
const last = buff[offset + 7];
|
||||
if (first === undefined || last === undefined)
|
||||
boundsError(offset, buff.length - 8);
|
||||
|
||||
uInt8Float64Array[0] = first;
|
||||
uInt8Float64Array[1] = buff[++offset];
|
||||
uInt8Float64Array[2] = buff[++offset];
|
||||
uInt8Float64Array[3] = buff[++offset];
|
||||
uInt8Float64Array[4] = buff[++offset];
|
||||
uInt8Float64Array[5] = buff[++offset];
|
||||
uInt8Float64Array[6] = buff[++offset];
|
||||
uInt8Float64Array[7] = last;
|
||||
return float64Array[0];
|
||||
}
|
||||
|
||||
function writeDouble(buff, val, offset = 0) {
|
||||
val = +val;
|
||||
checkBounds(buff, offset, 7);
|
||||
|
||||
float64Array[0] = val;
|
||||
buff[offset++] = uInt8Float64Array[0];
|
||||
buff[offset++] = uInt8Float64Array[1];
|
||||
buff[offset++] = uInt8Float64Array[2];
|
||||
buff[offset++] = uInt8Float64Array[3];
|
||||
buff[offset++] = uInt8Float64Array[4];
|
||||
buff[offset++] = uInt8Float64Array[5];
|
||||
buff[offset++] = uInt8Float64Array[6];
|
||||
buff[offset++] = uInt8Float64Array[7];
|
||||
return offset;
|
||||
}
|
||||
|
||||
const bigInt64Array = new BigInt64Array(1);
|
||||
const uint8BigInt64Array = new Uint8Array(bigInt64Array.buffer);
|
||||
|
||||
function readInt64(buff, offset = 0) {
|
||||
const first = buff[offset];
|
||||
const last = buff[offset + 7];
|
||||
if (first === undefined || last === undefined)
|
||||
boundsError(offset, buff.length - 8);
|
||||
|
||||
uint8BigInt64Array[0] = first;
|
||||
uint8BigInt64Array[1] = buff[++offset];
|
||||
uint8BigInt64Array[2] = buff[++offset];
|
||||
uint8BigInt64Array[3] = buff[++offset];
|
||||
uint8BigInt64Array[4] = buff[++offset];
|
||||
uint8BigInt64Array[5] = buff[++offset];
|
||||
uint8BigInt64Array[6] = buff[++offset];
|
||||
uint8BigInt64Array[7] = last;
|
||||
return bigInt64Array[0];
|
||||
}
|
||||
|
||||
function writeInt64(buff, val, offset = 0) {
|
||||
val = +val;
|
||||
if (typeof val === 'number') val = BigInt(val);
|
||||
checkBounds(buff, offset, 7);
|
||||
|
||||
bigInt64Array[0] = val;
|
||||
buff[offset++] = uint8BigInt64Array[0];
|
||||
buff[offset++] = uint8BigInt64Array[1];
|
||||
buff[offset++] = uint8BigInt64Array[2];
|
||||
buff[offset++] = uint8BigInt64Array[3];
|
||||
buff[offset++] = uint8BigInt64Array[4];
|
||||
buff[offset++] = uint8BigInt64Array[5];
|
||||
buff[offset++] = uint8BigInt64Array[6];
|
||||
buff[offset++] = uint8BigInt64Array[7];
|
||||
return offset;
|
||||
}
|
||||
|
||||
const bigUint64Array = new BigUint64Array(1);
|
||||
const uint8BigUint64Array = new Uint8Array(bigUint64Array.buffer);
|
||||
|
||||
function readUInt64(buff, offset = 0) {
|
||||
const first = buff[offset];
|
||||
const last = buff[offset + 7];
|
||||
if (first === undefined || last === undefined)
|
||||
boundsError(offset, buff.length - 8);
|
||||
|
||||
uint8BigUint64Array[0] = first;
|
||||
uint8BigUint64Array[1] = buff[++offset];
|
||||
uint8BigUint64Array[2] = buff[++offset];
|
||||
uint8BigUint64Array[3] = buff[++offset];
|
||||
uint8BigUint64Array[4] = buff[++offset];
|
||||
uint8BigUint64Array[5] = buff[++offset];
|
||||
uint8BigUint64Array[6] = buff[++offset];
|
||||
uint8BigUint64Array[7] = last;
|
||||
return bigUint64Array[0];
|
||||
}
|
||||
|
||||
function writeUInt64(buff, val, offset = 0) {
|
||||
val = +val;
|
||||
if (typeof val === 'number') val = BigInt(val);
|
||||
checkBounds(buff, offset, 7);
|
||||
|
||||
bigUint64Array[0] = val;
|
||||
buff[offset++] = uint8BigUint64Array[0];
|
||||
buff[offset++] = uint8BigUint64Array[1];
|
||||
buff[offset++] = uint8BigUint64Array[2];
|
||||
buff[offset++] = uint8BigUint64Array[3];
|
||||
buff[offset++] = uint8BigUint64Array[4];
|
||||
buff[offset++] = uint8BigUint64Array[5];
|
||||
buff[offset++] = uint8BigUint64Array[6];
|
||||
buff[offset++] = uint8BigUint64Array[7];
|
||||
return offset;
|
||||
}
|
||||
|
||||
let ffi_bindings = require('ffi_bindings');
|
||||
|
||||
ffi_bindings.readInt8 = readInt8;
|
||||
ffi_bindings.readUInt8 = readUInt8;
|
||||
ffi_bindings.readInt16 = readInt16;
|
||||
ffi_bindings.readUInt16 = readUInt16;
|
||||
ffi_bindings.readInt32 = readInt32;
|
||||
ffi_bindings.readUInt32 = readUInt32;
|
||||
ffi_bindings.readInt64 = readInt64;
|
||||
ffi_bindings.readUInt64 = readUInt64;
|
||||
ffi_bindings.readFloat = readFloat;
|
||||
ffi_bindings.readDouble = readDouble;
|
||||
|
||||
ffi_bindings.writeInt8 = writeInt8;
|
||||
ffi_bindings.writeUInt8 = writeUInt8;
|
||||
ffi_bindings.writeInt16 = writeInt16;
|
||||
ffi_bindings.writeUInt16 = writeUInt16;
|
||||
ffi_bindings.writeInt32 = writeInt32;
|
||||
ffi_bindings.writeUInt32 = writeUInt32;
|
||||
ffi_bindings.writeInt64 = writeInt64;
|
||||
ffi_bindings.writeUInt64 = writeUInt64;
|
||||
ffi_bindings.writeFloat = writeFloat;
|
||||
ffi_bindings.writeDouble = writeDouble;
|
||||
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
module.exports = require('ffi_bindings');
|
||||
module.exports.binding = require('binding').binding;
|
||||
module.exports.closure= require('binding').closure;
|
||||
module.exports.typeInfo = require('type').typeInfo;
|
||||
module.exports.makeStruct = require('type').makeStruct;
|
||||
module.exports.makePointer = require('type').makePointer;
|
||||
@@ -0,0 +1,210 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
let ffi_bindings = require('ffi_bindings');
|
||||
require('buffer-ext.js');
|
||||
|
||||
let primitiveTypes = Object.create(null);
|
||||
|
||||
Object.keys(ffi_bindings.sizeof).forEach(function (name) {
|
||||
let uname;
|
||||
if (name.startsWith("ui")) {
|
||||
uname = name.slice(0, 2).toUpperCase() + name.slice(2);
|
||||
} else {
|
||||
uname = name.charAt(0).toUpperCase() + name.slice(1);
|
||||
}
|
||||
primitiveTypes[name] = {
|
||||
ffi_type: ffi_bindings.FFI_TYPES[name],
|
||||
size: ffi_bindings.sizeof[name],
|
||||
align: ffi_bindings.alignof[name],
|
||||
write: ffi_bindings["write" + uname],
|
||||
read: ffi_bindings["read" + uname],
|
||||
set: set,
|
||||
get: get,
|
||||
alloc: alloc
|
||||
}
|
||||
});
|
||||
|
||||
primitiveTypes.cstring = primitiveTypes.pointer;
|
||||
function doNothing(){}
|
||||
primitiveTypes["void"] = {
|
||||
ffi_type: ffi_bindings.FFI_TYPES['void'],
|
||||
size: 0,
|
||||
align: 0,
|
||||
write: doNothing,
|
||||
read: doNothing,
|
||||
set: doNothing,
|
||||
get: doNothing,
|
||||
alloc: doNothing
|
||||
}
|
||||
|
||||
function typeInfo(t) {
|
||||
return (typeof t === 'string') ? primitiveTypes[t] : t;
|
||||
}
|
||||
|
||||
const pointer = primitiveTypes.pointer;
|
||||
|
||||
const sizeType = pointer.size == 4 ? "uint32" : "uint64";
|
||||
|
||||
primitiveTypes.size_t = {
|
||||
ffi_type: pointer.ffi_type,
|
||||
size: pointer.size,
|
||||
align: pointer.align,
|
||||
write: primitiveTypes[sizeType].write,
|
||||
read: primitiveTypes[sizeType].read,
|
||||
set: set,
|
||||
get: get,
|
||||
alloc: alloc
|
||||
}
|
||||
|
||||
function makePointer(t) {
|
||||
t = typeInfo(t);
|
||||
let ret = Object.assign({}, pointer);
|
||||
const orgRead = ret.read;
|
||||
function readTypedPointer(buffer, offset) {
|
||||
return orgRead(buffer, offset, t.size);
|
||||
}
|
||||
|
||||
function ref(value) {
|
||||
return t.alloc(value);
|
||||
}
|
||||
|
||||
function unref(buff) {
|
||||
return t.read(buff);
|
||||
}
|
||||
|
||||
ret.read = readTypedPointer;
|
||||
ret.ref = ref;
|
||||
ret.unref = unref;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
function makeStruct(info, noFfiType) {
|
||||
function structType (buff, data) {
|
||||
if (!(this instanceof structType)) {
|
||||
return new structType(buff, data);
|
||||
}
|
||||
|
||||
if (!(buff instanceof Uint8Array)) {
|
||||
data = buff;
|
||||
buff = new Uint8Array(structType.size);
|
||||
}
|
||||
|
||||
this._buff = buff;
|
||||
if (data) {
|
||||
for (var key in data) {
|
||||
this[key] = data[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function propertyDesc(name, type, offset) {
|
||||
return {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: function() {
|
||||
return type.read(this._buff, offset);
|
||||
},
|
||||
set: function(value) {
|
||||
type.write(this._buff, value, offset);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
let structSize = 0;
|
||||
let structAlign = 0;
|
||||
let elem_ffi_types = [];
|
||||
|
||||
Object.keys(info).forEach(function (name) {
|
||||
fieldType = typeInfo(info[name]);
|
||||
const align = fieldType.align;
|
||||
const padding = (align - (structSize % align)) % align;
|
||||
const desc = propertyDesc(name, fieldType, structSize + padding);
|
||||
Object.defineProperty(structType.prototype, name, desc);
|
||||
structSize += (padding + fieldType.size);
|
||||
structAlign = Math.max(structAlign, align);
|
||||
elem_ffi_types.push(fieldType.ffi_type);
|
||||
});
|
||||
|
||||
var left = structSize % structAlign;
|
||||
if (left > 0) {
|
||||
structSize += structAlign - left;
|
||||
}
|
||||
structType.size = structSize;
|
||||
structType.align = structAlign;
|
||||
structType.read = structRead;
|
||||
structType.write = structWrite;
|
||||
structType.set = set;
|
||||
structType.get = get;
|
||||
structType.alloc = alloc;
|
||||
|
||||
if (!noFfiType) {
|
||||
let ffi_type = new FFI_TYPE();
|
||||
ffi_type.size = 0;
|
||||
ffi_type.alignment = 0;
|
||||
ffi_type.type = ffi_bindings.FFI_TYPE_STRUCT;
|
||||
|
||||
let elements = pointer.alloc(...elem_ffi_types, null);
|
||||
ffi_type.elements = elements;
|
||||
structType._elems_array = elements;//prevent gc;
|
||||
structType.ffi_type = ffi_type._buff;
|
||||
}
|
||||
|
||||
return structType;
|
||||
}
|
||||
|
||||
var FFI_TYPE = makeStruct({
|
||||
size: 'size_t',
|
||||
alignment: 'uint16',
|
||||
type: 'uint16',
|
||||
elements: 'pointer'
|
||||
}, true);
|
||||
|
||||
function structRead(buffer, offset) {
|
||||
if (typeof offset === 'number' && offset > 0) {
|
||||
buffer = new Uint8Array(buffer.buffer, offset);
|
||||
}
|
||||
return new this(buffer);
|
||||
}
|
||||
|
||||
function structWrite(buffer, value, offset) {
|
||||
if (value instanceof this) {
|
||||
let src = value._buff;
|
||||
if (typeof offset !== 'number') offset = 0;
|
||||
for(var i = 0; i < this.size; i++) {
|
||||
buffer[offset++] = src[i];
|
||||
}
|
||||
} else {
|
||||
if (typeof offset === 'number' && offset > 0) {
|
||||
buffer = new Uint8Array(buffer.buffer, offset);
|
||||
}
|
||||
new this(buffer, value);
|
||||
}
|
||||
}
|
||||
|
||||
function set(buff, val, index) {
|
||||
this.write(buff, val, index * this.size);
|
||||
}
|
||||
|
||||
function get(buff, index) {
|
||||
return this.read(buff, index * this.size);
|
||||
}
|
||||
|
||||
function alloc(...values) {
|
||||
if (values.length == 0) return new Uint8Array(this.size);
|
||||
let buff = new Uint8Array(values.length * this.size);
|
||||
for(var i = 0; i < values.length; i++) {
|
||||
this.set(buff, values[i], i);
|
||||
}
|
||||
return buff;
|
||||
}
|
||||
|
||||
exports.typeInfo = typeInfo;
|
||||
exports.makeStruct = makeStruct;
|
||||
exports.makePointer = makePointer;
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
let argList = [];
|
||||
let argMap = {};
|
||||
|
||||
puerts.argv = {
|
||||
getByIndex : function(index) {
|
||||
return argList[index]
|
||||
},
|
||||
|
||||
getByName : function(name) {
|
||||
return argMap[name];
|
||||
},
|
||||
|
||||
add : function(name, value) {
|
||||
argList.push(value);
|
||||
argMap[name] = value;
|
||||
}
|
||||
}
|
||||
}());
|
||||
@@ -0,0 +1,311 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
let sendRequestSync = puerts.sendRequestSync;
|
||||
|
||||
function getClassInfo(className) {
|
||||
let classInfo = sendRequestSync('getClassInfo', className);
|
||||
return JSON.parse(classInfo);
|
||||
}
|
||||
|
||||
function ref(x) {
|
||||
return {value:x};
|
||||
}
|
||||
|
||||
function unref(r) {
|
||||
return r.value;
|
||||
}
|
||||
|
||||
function ret(o) {
|
||||
return o.ReturnValue;
|
||||
}
|
||||
|
||||
function retWithWrap(o){
|
||||
return wrapUObject(o.ReturnValue);
|
||||
}
|
||||
|
||||
function retWithAsyncWrap(o){
|
||||
return wrapUObject(o.ReturnValue, true);
|
||||
}
|
||||
|
||||
function id(x) {
|
||||
return x;
|
||||
}
|
||||
|
||||
function makeArgumentUnpack(paramInfo) {
|
||||
if (paramInfo.isOut && paramInfo.isUObject) {
|
||||
return x => ref(wrapUObject(x));
|
||||
} else if(paramInfo.isOut) {
|
||||
return ref;
|
||||
} else if (paramInfo.isUObject) {
|
||||
return wrapUObject;
|
||||
} else {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
function wrapCallback(functionInfo, callback) {
|
||||
let paramsInfo = functionInfo.parameters;
|
||||
paramsInfo.forEach( paramInfo => paramInfo.unpack = makeArgumentUnpack(paramInfo));
|
||||
return (argsObj) => {
|
||||
let args = paramsInfo.map(paramInfo => paramInfo.unpack(argsObj[paramInfo.name]));
|
||||
callback.apply(null, args);
|
||||
};
|
||||
}
|
||||
|
||||
let registerCallbacks = Object.create(null);
|
||||
var allocedCallbackId = 0;
|
||||
function registerCallback(callback) {
|
||||
let callbackId = allocedCallbackId++;
|
||||
registerCallbacks[callbackId] = callback;
|
||||
return callbackId;
|
||||
}
|
||||
function unregisterCallback(callbackId) {
|
||||
registerCallbacks[callbackId] = undefined;
|
||||
}
|
||||
|
||||
let wrapGenerators = Object.create(null);
|
||||
|
||||
class Delegate {
|
||||
constructor(objectId, propertyName, propertyType) {
|
||||
this.objectId = objectId;
|
||||
this.propertyName = propertyName;
|
||||
this.propertyType = propertyType;
|
||||
}
|
||||
|
||||
Bind(func) {
|
||||
if (typeof func !== 'function') {
|
||||
throw new Error('function needed!');
|
||||
}
|
||||
this.Unbind();
|
||||
let callbackId = registerCallback(wrapCallback(this.propertyType, func));
|
||||
sendRequestSync('bindDelegate', this.objectId + '#' + this.propertyName + '#' + callbackId);
|
||||
this.bindedCallbackId = callbackId;
|
||||
}
|
||||
|
||||
Unbind() {
|
||||
if (this.bindedCallbackId) {
|
||||
sendRequestSync('unbindDelegate', this.bindedCallbackId);
|
||||
unregisterCallback(this.bindedCallbackId);
|
||||
this.bindedCallbackId = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MulticastDelegate {
|
||||
constructor(objectId, propertyName, propertyType) {
|
||||
this.objectId = objectId;
|
||||
this.propertyName = propertyName;
|
||||
this.propertyType = propertyType;
|
||||
}
|
||||
|
||||
Add(func) {
|
||||
if (typeof func !== 'function') {
|
||||
throw new Error('function needed!');
|
||||
}
|
||||
let callbackId = registerCallback(wrapCallback(this.propertyType, func));
|
||||
sendRequestSync('bindDelegate', this.objectId + '#' + this.propertyName + '#' + callbackId);
|
||||
return callbackId;
|
||||
}
|
||||
|
||||
Remove(callbackId) {
|
||||
sendRequestSync('unbindDelegate', callbackId);
|
||||
unregisterCallback(callbackId);
|
||||
}
|
||||
}
|
||||
|
||||
let pendingAsyncCall = [];
|
||||
|
||||
function getWrapGenerator(className, optClassInfo) {
|
||||
if (!(className in wrapGenerators)) {
|
||||
let classInfo = optClassInfo || getClassInfo(className);
|
||||
wrapGenerators[className] = (objectId, isClass, isAsync) => {
|
||||
let target = {$functions: classInfo.functions, $id:objectId, toJSON:() => objectId, $toAsync:() => getWrapGenerator(className, optClassInfo)(objectId, true, true)};
|
||||
if (!isClass) {
|
||||
for (var propertyName in classInfo.delegates) {
|
||||
target[propertyName] = new Delegate(objectId, propertyName, classInfo.delegates[propertyName]);
|
||||
}
|
||||
for (var propertyName in classInfo.multicasts) {
|
||||
target[propertyName] = new MulticastDelegate(objectId, propertyName, classInfo.multicasts[propertyName]);
|
||||
}
|
||||
} else {
|
||||
target["StaticClass"] = () => classInfo.pathName;
|
||||
}
|
||||
return new Proxy(target, {
|
||||
get: function(cfg, name) {
|
||||
if (!(name in cfg)) {
|
||||
let functionInfo = cfg.$functions[name];
|
||||
let id = cfg.$id
|
||||
//之前抛异常不太适合,传统js是duck typing,有时会通过是否有某函数判断能力。
|
||||
//比如,promise里resolve传入的对象,thenable对象是通过是否有then函数来决定的,
|
||||
//所以异步返回,resolve传入wrap的uobject时,会抛无then函数的异常;
|
||||
if (!functionInfo) return;
|
||||
let paramsInfo = functionInfo.parameters;
|
||||
let r = functionInfo.isUObject ? (isAsync ? retWithAsyncWrap : retWithWrap) : ret;
|
||||
cfg[name] = isAsync ? function() {
|
||||
let argsObj = {};
|
||||
paramsInfo.forEach((paramInfo, idx) => argsObj[paramInfo.name] = paramInfo.isOut ? arguments[idx].value : arguments[idx]);
|
||||
let argsString = JSON.stringify(argsObj);
|
||||
let outterArgs = arguments;
|
||||
return new Promise(function(resolve, reject) {
|
||||
let args = id + '#' + name + '#' + argsString;
|
||||
pendingAsyncCall.push({args: args.length + 'A' + args, resolve: res => {
|
||||
paramsInfo.forEach((paramInfo, idx) => {
|
||||
if(paramInfo.isOut) {
|
||||
outterArgs[idx].value = paramInfo.isUObject ? wrapUObject(res[paramInfo.name]) :res[paramInfo.name];
|
||||
}
|
||||
});
|
||||
resolve(r(res));
|
||||
}, reject: reject});
|
||||
});
|
||||
} : function() {
|
||||
let argsObj = {};
|
||||
paramsInfo.forEach((paramInfo, idx) => argsObj[paramInfo.name] = paramInfo.isOut ? arguments[idx].value : arguments[idx]);
|
||||
let argsString = JSON.stringify(argsObj);
|
||||
//puerts.console.log('id:' + id + ',method:' + name + ',args:' + argsString);
|
||||
let res = JSON.parse(sendRequestSync('callUObjectMethod', id + '#' + name + '#' + argsString));
|
||||
paramsInfo.forEach((paramInfo, idx) => {
|
||||
if(paramInfo.isOut) {
|
||||
arguments[idx].value = paramInfo.isUObject ? wrapUObject(res[paramInfo.name]) :res[paramInfo.name];
|
||||
}
|
||||
});
|
||||
|
||||
return r(res);
|
||||
}
|
||||
}
|
||||
return cfg[name];
|
||||
},
|
||||
set: function(cfg, name, value) {
|
||||
throw new Error('set not allow for ' + name);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
return wrapGenerators[className];
|
||||
}
|
||||
|
||||
function wrapUObject(objectId, isAsync) {
|
||||
if (objectId === "0000000000000000") return null;
|
||||
let className = objectId.substring(objectId.indexOf('-') + 1);
|
||||
return getWrapGenerator(className)(objectId, false, isAsync);
|
||||
}
|
||||
|
||||
let UE = new Proxy(Object.create(null), {
|
||||
get: function(classWrapers, name) {
|
||||
if (!(name in classWrapers)) {
|
||||
let classInfo = getClassInfo(name);
|
||||
classWrapers[name] = getWrapGenerator(name, classInfo)(classInfo.pathName, true);
|
||||
}
|
||||
return classWrapers[name];
|
||||
}
|
||||
});
|
||||
|
||||
puerts.registerRequestHandler('invokeCallback', (msg, onFinished) => {
|
||||
let split = msg.indexOf('#');
|
||||
let callbackId = msg.substring(0, split);
|
||||
let cb = registerCallbacks[callbackId];
|
||||
if (cb) {
|
||||
cb(JSON.parse(msg.substring(split + 1)));
|
||||
onFinished("");
|
||||
} else {
|
||||
onFinished(undefined, "no callback " + callbackId);
|
||||
}
|
||||
});
|
||||
|
||||
puerts.registerRequestHandler('onCallbackRelease', callbackId => {
|
||||
registerCallbacks[callbackId] = undefined;
|
||||
});
|
||||
|
||||
var mainObject = undefined;
|
||||
|
||||
function getMainObject() {
|
||||
if (!mainObject) {
|
||||
mainObject = wrapUObject(sendRequestSync('getMainObjectId', ''));
|
||||
}
|
||||
return mainObject;
|
||||
}
|
||||
|
||||
function getProperties(obj, ...fields) {
|
||||
let args = (typeof obj === 'string') ? obj : obj.toJSON();
|
||||
if (fields.length > 0) {
|
||||
args += ("#" + fields.join('#'));
|
||||
}
|
||||
return JSON.parse(sendRequestSync('getProperties', args));
|
||||
}
|
||||
|
||||
function getPropertiesAsync(obj, ...fields) {
|
||||
let args = (typeof obj === 'string') ? obj : obj.toJSON();
|
||||
if (fields.length > 0) {
|
||||
args += ("#" + fields.join('#'));
|
||||
}
|
||||
return new Promise(function(resolve, reject) {
|
||||
pendingAsyncCall.push({args: args.length + 'C' + args, resolve: resolve, reject: reject});
|
||||
});
|
||||
}
|
||||
|
||||
function setProperties(obj, properties) {
|
||||
let objectId = (typeof obj === 'string') ? obj : obj.toJSON();
|
||||
sendRequestSync('setProperties', objectId + '#' +JSON.stringify(properties));
|
||||
}
|
||||
|
||||
function setPropertiesAsync(obj, properties) {
|
||||
let objectId = (typeof obj === 'string') ? obj : obj.toJSON();
|
||||
let args = objectId + '#' +JSON.stringify(properties);
|
||||
return new Promise(function(resolve, reject) {
|
||||
pendingAsyncCall.push({args: args.length + 'B' + args, resolve: resolve, reject: reject});
|
||||
});
|
||||
}
|
||||
|
||||
function flushAsyncCall(trace) {
|
||||
if (pendingAsyncCall.length == 0) return 0;
|
||||
let sliceCalls = pendingAsyncCall;
|
||||
let batchArgs = sliceCalls.map(x =>x.args).join('');
|
||||
if (trace) {
|
||||
puerts.console.log(sliceCalls.map(x =>x.args).join('\n'))
|
||||
}
|
||||
pendingAsyncCall = [];
|
||||
let batchResult = sendRequestSync('batchCall', batchArgs);
|
||||
let callIndex = 0;
|
||||
let split1 = 0;
|
||||
let split2;
|
||||
while((split2 = batchResult.indexOf('#', split1)) >= 0) {
|
||||
let len = parseInt(batchResult.slice(split1, split2));
|
||||
let result = batchResult.substr(split2 + 1, len);
|
||||
if (result.startsWith('#')) {
|
||||
let r = result.substr(1);
|
||||
if (r == '') {
|
||||
sliceCalls[callIndex].resolve();
|
||||
} else {
|
||||
sliceCalls[callIndex].resolve(JSON.parse(result.substr(1)));
|
||||
}
|
||||
} else {
|
||||
sliceCalls[callIndex].reject(new Error(result));
|
||||
}
|
||||
++callIndex;
|
||||
split1 = split2 + 1 + len;
|
||||
}
|
||||
return sliceCalls.length
|
||||
}
|
||||
|
||||
puerts.getMainObject = getMainObject;
|
||||
puerts.getProperties = getProperties;
|
||||
puerts.getPropertiesAsync = getPropertiesAsync;
|
||||
puerts.setProperties = setProperties;
|
||||
puerts.setPropertiesAsync = setPropertiesAsync;
|
||||
puerts.flushAsyncCall = flushAsyncCall;
|
||||
|
||||
puerts.$ref = ref;
|
||||
puerts.$unref = unref;
|
||||
puerts.$async = x => x.$toAsync();
|
||||
|
||||
puerts.registerBuildinModule('ue', UE);
|
||||
}(global));
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
let events = Object.create(null);
|
||||
let eventsCount = 0;
|
||||
|
||||
function checkListener(listener) {
|
||||
if (typeof listener !== 'function') {
|
||||
throw new Error('listener expect a function');
|
||||
}
|
||||
}
|
||||
|
||||
function on(type, listener, prepend) {
|
||||
checkListener(listener);
|
||||
|
||||
let existing = events[type];
|
||||
if (existing === undefined) {
|
||||
events[type] = listener;
|
||||
++eventsCount;
|
||||
} else {
|
||||
if (typeof existing === 'function') {
|
||||
events[type] = prepend ? [listener, existing] : [existing, listener];
|
||||
} else if (prepend) {
|
||||
existing.unshift(listener);
|
||||
} else {
|
||||
existing.push(listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function off(type, listener) {
|
||||
checkListener(listener);
|
||||
|
||||
const list = events[type];
|
||||
if (list === undefined)
|
||||
return;
|
||||
if (list === listener) {
|
||||
if (--eventsCount === 0)
|
||||
events = Object.create(null);
|
||||
else {
|
||||
events[type] = undefined;
|
||||
}
|
||||
} else if (typeof list !== 'function') {
|
||||
for (var i = list.length - 1; i >= 0; i--) {
|
||||
if (list[i] === listener) { //found
|
||||
if (i === 0)
|
||||
list.shift();
|
||||
else {
|
||||
spliceOne(list, i);
|
||||
}
|
||||
|
||||
if (list.length === 1)
|
||||
events[type] = list[0];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emit(type, ...args) {
|
||||
const listener = events[type];
|
||||
|
||||
if (listener === undefined)
|
||||
return false;
|
||||
|
||||
if (typeof listener === 'function') {
|
||||
Reflect.apply(listener, this, args);
|
||||
} else {
|
||||
const len = listener.length;
|
||||
const listeners = arrayClone(listener, len);
|
||||
for (var i = 0; i < len; ++i)
|
||||
Reflect.apply(listeners[i], this, args);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function arrayClone(arr, n) {
|
||||
const copy = new Array(n);
|
||||
for (var i = 0; i < n; ++i)
|
||||
copy[i] = arr[i];
|
||||
return copy;
|
||||
}
|
||||
|
||||
function spliceOne(list, index) {
|
||||
for (; index + 1 < list.length; index++)
|
||||
list[index] = list[index + 1];
|
||||
list.pop();
|
||||
}
|
||||
|
||||
puerts.on = on;
|
||||
puerts.off = off;
|
||||
puerts.emit = emit;
|
||||
}());
|
||||
@@ -0,0 +1 @@
|
||||
//createInspector(8080)
|
||||
@@ -0,0 +1,99 @@
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
let puerts = global.puerts
|
||||
|
||||
let dispatchProtocolMessage = global.__tgjsDispatchProtocolMessage
|
||||
global.__tgjsDispatchProtocolMessage = undefined;
|
||||
|
||||
let setInspectorCallback = global.__tgjsSetInspectorCallback
|
||||
global.__tgjsSetInspectorCallback = undefined;
|
||||
|
||||
const parsedScript = new Map();
|
||||
|
||||
let contextInfo
|
||||
|
||||
const pendingCommnand = new Map();
|
||||
|
||||
function messageHandler(str) {
|
||||
let msg = JSON.parse(str);
|
||||
if (msg.method === "Debugger.scriptParsed") {
|
||||
parsedScript.set(msg.params.scriptId, msg.params.url);
|
||||
parsedScript.set(msg.params.url, msg.params.scriptId);
|
||||
} else if ( msg.method === "Runtime.executionContextCreated") {
|
||||
contextInfo = msg.params.context;
|
||||
} else if (typeof msg.id === "number") {
|
||||
if (msg.result && pendingCommnand.has(msg.id)) {
|
||||
const resolve = pendingCommnand.get(msg.id);
|
||||
pendingCommnand.delete(msg.id);
|
||||
resolve(msg.result);
|
||||
} else {
|
||||
console.error("unexpect inspector message:" + str);
|
||||
}
|
||||
}
|
||||
//if ( msg.method != "Runtime.consoleAPICalled") {
|
||||
// console.error("<--", str);
|
||||
//}
|
||||
};
|
||||
|
||||
let commandId = 0;
|
||||
|
||||
function sendCommand(method, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
commandId++;
|
||||
pendingCommnand.set(commandId, resolve);
|
||||
//console.error("-->", JSON.stringify({"id":commandId,"method":method,"params":params}));
|
||||
dispatchProtocolMessage(JSON.stringify({"id":commandId,"method":method,"params":params}));
|
||||
});
|
||||
}
|
||||
|
||||
let inited = false;
|
||||
|
||||
async function enableDebugger() {
|
||||
if (inited) return;
|
||||
inited = true;
|
||||
setInspectorCallback(messageHandler);
|
||||
await sendCommand("Runtime.enable", {});
|
||||
await sendCommand("Debugger.enable", {"maxScriptsCacheSize":10000000});
|
||||
//await sendCommand("Debugger.setPauseOnExceptions",{"state":"none"});
|
||||
//await sendCommand("Debugger.setAsyncCallStackDepth",{"maxDepth":32});
|
||||
//await sendCommand("Profiler.enable",{});
|
||||
//await sendCommand("Runtime.getIsolateId",{});
|
||||
//await sendCommand("Debugger.setBlackboxPatterns",{"patterns":[]});
|
||||
//await sendCommand("Runtime.runIfWaitingForDebugger");
|
||||
}
|
||||
|
||||
async function reload(moduleName, url, source) {
|
||||
await enableDebugger();
|
||||
let scriptId
|
||||
if (parsedScript.has(url)) {
|
||||
scriptId = parsedScript.get(url)
|
||||
} else {
|
||||
let win_url = url.replace(/\//g, '\\');
|
||||
if (parsedScript.has(win_url)) {
|
||||
scriptId = parsedScript.get(win_url)
|
||||
}
|
||||
}
|
||||
|
||||
if (scriptId) {
|
||||
if (typeof source === "string") {
|
||||
let orgSourceInfo = await sendCommand("Debugger.getScriptSource", {scriptId:"" + scriptId});
|
||||
source = ("(function (exports, require, module, __filename, __dirname) { " + source + "\n});");
|
||||
if (orgSourceInfo.scriptSource == source) {
|
||||
console.log(`source not changed, skip ${url}`);
|
||||
return;
|
||||
}
|
||||
let m = puerts.getModuleByUrl(url);
|
||||
puerts.emit('HMR.prepare', moduleName, m, url);
|
||||
let res = await sendCommand("Debugger.setScriptSource", {scriptId:"" + scriptId,scriptSource:source});
|
||||
puerts.emit('HMR.finish', moduleName, m, url);
|
||||
//puerts.forceReload(url);
|
||||
}
|
||||
} else {
|
||||
console.warn(`can not find scriptId for ${url}`)
|
||||
}
|
||||
};
|
||||
|
||||
puerts.__reload = reload;
|
||||
}(global));
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
let puerts = require("puerts");
|
||||
|
||||
let loadedModules = Object.create(null);
|
||||
|
||||
puerts.registerRequestHandler('requestModuleMethod', (data, onFinished) => {
|
||||
let split = data.indexOf('#');
|
||||
let split2 = data.indexOf('#', split + 1);
|
||||
let moduleName = data.substring(0, split);
|
||||
let moduleMethodName = data.substring(split + 1, split2);
|
||||
let invokeArgs = data.substring(split2 + 1);
|
||||
let module = loadedModules[moduleName];
|
||||
if (!module) {
|
||||
module = require(moduleName);
|
||||
loadedModules[moduleName] = module;
|
||||
}
|
||||
let method = module[moduleMethodName];
|
||||
let args = JSON.parse(invokeArgs);
|
||||
let result = method.apply(module, args);
|
||||
onFinished(undefined, JSON.stringify(result));
|
||||
});
|
||||
|
||||
console.log("jit_skeleton.js loaded!!");
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
let requestJitModuleMethod = global.__tgjsRequestJitModuleMethod;
|
||||
global.__tgjsRequestJitModuleMethod = undefined;
|
||||
|
||||
puerts.requestJitModuleMethod = function(moduleName, methodName, callback, ... args) {
|
||||
let data = moduleName + "#" + methodName + "#" + JSON.stringify(args);
|
||||
requestJitModuleMethod(data, (err, result) => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
} else {
|
||||
callback(undefined, JSON.parse(result));
|
||||
}
|
||||
});
|
||||
}
|
||||
}(global));
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
let levels = ['log', 'info', 'warn', 'error']
|
||||
|
||||
let sendRequestSync = puerts.sendRequestSync;
|
||||
|
||||
let tgjsLog = global.__tgjsLog || function(nlevel, msg) {
|
||||
sendRequestSync(levels[nlevel], msg);
|
||||
}
|
||||
global.__tgjsLog = undefined;
|
||||
|
||||
const console_org = global.console;
|
||||
var console = {}
|
||||
|
||||
function log(level, args) {
|
||||
tgjsLog(level, Array.prototype.map.call(args, x => {
|
||||
try {
|
||||
return x+'';
|
||||
} catch (err){
|
||||
return err;
|
||||
}
|
||||
}).join(','));
|
||||
}
|
||||
|
||||
console.log = function() {
|
||||
if (console_org) console_org.log.apply(null, Array.prototype.slice.call(arguments));
|
||||
log(0, arguments);
|
||||
}
|
||||
|
||||
console.info = function() {
|
||||
if (console_org) console_org.info.apply(null, Array.prototype.slice.call(arguments));
|
||||
log(1, arguments);
|
||||
}
|
||||
|
||||
console.warn = function() {
|
||||
if (console_org) console_org.warn.apply(null, Array.prototype.slice.call(arguments));
|
||||
log(2, arguments);
|
||||
}
|
||||
|
||||
console.error = function() {
|
||||
if (console_org) console_org.error.apply(null, Array.prototype.slice.call(arguments));
|
||||
log(3, arguments);
|
||||
}
|
||||
|
||||
global.puerts.console = console;
|
||||
global.console = console;
|
||||
}(global));
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
let puerts = global.puerts = global.puerts || {};
|
||||
let sendMessage = global.prompt;
|
||||
puerts.sendRawMessage = function(msg) {
|
||||
return sendMessage(msg);
|
||||
}
|
||||
|
||||
//TODO:支持多参数,多参数自动用#连接
|
||||
puerts.sendRequestSync = function(cmd, ...args) {
|
||||
var req = cmd + "#" + args.join('#');
|
||||
let ret = sendMessage(req); //oneway ret === "", normal reply === "#msg", error === "info"
|
||||
if (ret) {
|
||||
var err;
|
||||
var rpy;
|
||||
if (!ret.startsWith('#')) {
|
||||
err = new Error(ret);
|
||||
} else {
|
||||
rpy = ret.substring(1);
|
||||
}
|
||||
if (err) throw err;
|
||||
return rpy;
|
||||
}
|
||||
}
|
||||
|
||||
let requestHandlers = Object.create(null);
|
||||
|
||||
puerts.registerRequestHandler = function(cmd, callback) {
|
||||
requestHandlers[cmd] = callback;
|
||||
}
|
||||
|
||||
function sendReply(replyId, reply, err) {
|
||||
let errMsg = err ? (typeof err == 'string' ? err : err.message) : ''
|
||||
if (replyId) {
|
||||
puerts.sendRequestSync('onReply', replyId + '#' + (errMsg ? errMsg : ('#' + reply)));
|
||||
}
|
||||
}
|
||||
|
||||
function handleMessage(cmd, data, replyId) {
|
||||
let handler = requestHandlers[cmd];
|
||||
if (!handler) {
|
||||
return sendReply(replyId, null, "can not find handler for " + cmd);
|
||||
}
|
||||
|
||||
if (replyId) {
|
||||
handler(data, (err, reply) => sendReply(replyId, reply, err));
|
||||
} else {
|
||||
handler(data);
|
||||
}
|
||||
}
|
||||
|
||||
var lastPollTime = new Date();
|
||||
|
||||
setInterval(() => {
|
||||
let now = new Date();
|
||||
//puerts.console.log('interval:' + (now - lastPollTime));
|
||||
lastPollTime = now;
|
||||
let msg = puerts.sendRequestSync('pollRequest');
|
||||
let cmd, replyId
|
||||
if (msg) {
|
||||
try {
|
||||
//puerts.console.log('msg:' + msg);
|
||||
let firstSplit = msg.indexOf('#');
|
||||
let secondSplit = msg.indexOf('#', firstSplit + 1);
|
||||
replyId = msg.substring(0, firstSplit);
|
||||
cmd = msg.substring(firstSplit + 1, secondSplit);
|
||||
let data = msg.substring(secondSplit + 1);
|
||||
//puerts.console.warn(replyId);
|
||||
//puerts.console.log(cmd);
|
||||
//puerts.console.log(data);
|
||||
handleMessage(cmd, data, replyId);
|
||||
} catch(e) {
|
||||
if (replyId) {
|
||||
sendReply(replyId, null, e.stack);
|
||||
} else {
|
||||
puerts.console.error("handle " + (cmd || "unknow") + " fail, info = " + e.stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 1);
|
||||
|
||||
}(global));
|
||||
@@ -0,0 +1,250 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
let puerts = global.puerts = global.puerts || {};
|
||||
|
||||
let sendRequestSync = puerts.sendRequestSync;
|
||||
|
||||
function normalize(name) {
|
||||
if ('./' === name.substr(0,2)) {
|
||||
name = name.substr(2);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
let evalScript = global.__tgjsEvalScript || function(script, debugPath) {
|
||||
return eval(script);
|
||||
}
|
||||
global.__tgjsEvalScript = undefined;
|
||||
|
||||
let loadModule = global.__tgjsLoadModule;
|
||||
global.__tgjsLoadModule = undefined;
|
||||
|
||||
let searchModule = global.__tgjsSearchModule;
|
||||
global.__tgjsSearchModule = undefined;
|
||||
|
||||
let org_require = global.require;
|
||||
|
||||
let findModule = global.__tgjsFindModule;
|
||||
global.__tgjsFindModule = undefined;
|
||||
|
||||
let tmpModuleStorage = [];
|
||||
|
||||
function addModule(m) {
|
||||
for (var i = 0; i < tmpModuleStorage.length; i++) {
|
||||
if (!tmpModuleStorage[i]) {
|
||||
tmpModuleStorage[i] = m;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return tmpModuleStorage.push(m) - 1;
|
||||
}
|
||||
|
||||
function getModuleBySID(id) {
|
||||
return tmpModuleStorage[id];
|
||||
}
|
||||
|
||||
let moduleCache = Object.create(null);
|
||||
let buildinModule = Object.create(null);
|
||||
function executeModule(fullPath, script, debugPath, sid, isESM, bytecode) {
|
||||
sid = (typeof sid == 'undefined') ? 0 : sid;
|
||||
let fullPathInJs = fullPath.replace(/\\/g, '\\\\');
|
||||
let fullDirInJs = (fullPath.indexOf('/') != -1) ? fullPath.substring(0, fullPath.lastIndexOf("/")) : fullPath.substring(0, fullPath.lastIndexOf("\\")).replace(/\\/g, '\\\\');
|
||||
let exports = {};
|
||||
let module = puerts.getModuleBySID(sid);
|
||||
module.exports = exports;
|
||||
let wrapped = evalScript(
|
||||
// Wrap the script in the same way NodeJS does it. It is important since IDEs (VSCode) will use this wrapper pattern
|
||||
// to enable stepping through original source in-place.
|
||||
(isESM || bytecode) ? script: "(function (exports, require, module, __filename, __dirname) { " + script + "\n});",
|
||||
debugPath, isESM, fullPath, bytecode
|
||||
)
|
||||
if (isESM) return wrapped;
|
||||
wrapped(exports, puerts.genRequire(fullDirInJs), module, fullPathInJs, fullDirInJs)
|
||||
return module.exports;
|
||||
}
|
||||
|
||||
function getESMMain(script) {
|
||||
let packageConfigure = JSON.parse(script);
|
||||
return (packageConfigure && packageConfigure.type === "module") ? packageConfigure.main : undefined;
|
||||
}
|
||||
|
||||
function getSourceLengthFromBytecode(buf, isESM) {
|
||||
let sourceHash = (new Uint32Array(buf))[2];
|
||||
//console.log(`sourceHash:${sourceHash}`);
|
||||
const kModuleFlagMask = (1 << 31);
|
||||
const mask = isESM ? kModuleFlagMask : 0;
|
||||
|
||||
// Remove the mask to get the original length
|
||||
const length = sourceHash & ~mask;
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
let baseString
|
||||
function generateEmptyCode(length) {
|
||||
if (baseString === undefined) {
|
||||
baseString = " ".repeat(128*1024);
|
||||
}
|
||||
if (length <= baseString.length) {
|
||||
return baseString.slice(0, length);
|
||||
} else {
|
||||
const fullString = baseString.repeat(Math.floor(length / baseString.length));
|
||||
const remainingLength = length % baseString.length;
|
||||
return fullString.concat(baseString.slice(0, remainingLength));
|
||||
}
|
||||
}
|
||||
|
||||
function genRequire(requiringDir, outerIsESM) {
|
||||
let localModuleCache = Object.create(null);
|
||||
function require(moduleName) {
|
||||
if (org_require) {
|
||||
try {
|
||||
return org_require(moduleName);
|
||||
} catch (e) {}
|
||||
}
|
||||
moduleName = normalize(moduleName);
|
||||
let forceReload = false;
|
||||
if ((moduleName in localModuleCache)) {
|
||||
let m = localModuleCache[moduleName];
|
||||
if (!m.__forceReload) {
|
||||
return localModuleCache[moduleName].exports;
|
||||
} else {
|
||||
forceReload = true;
|
||||
}
|
||||
}
|
||||
if (moduleName in buildinModule) return buildinModule[moduleName];
|
||||
let nativeModule = findModule(moduleName);
|
||||
if (nativeModule) {
|
||||
buildinModule[moduleName] = nativeModule;
|
||||
return nativeModule;
|
||||
}
|
||||
let moduleInfo = searchModule(moduleName, requiringDir);
|
||||
if (!moduleInfo) {
|
||||
throw new Error(`can not find ${moduleName} in ${requiringDir}`);
|
||||
}
|
||||
|
||||
let [fullPath, debugPath] = moduleInfo;
|
||||
if(debugPath.startsWith("Pak: ")){
|
||||
debugPath = fullPath
|
||||
}
|
||||
|
||||
let key = fullPath;
|
||||
if ((key in moduleCache) && !forceReload) {
|
||||
localModuleCache[moduleName] = moduleCache[key];
|
||||
return localModuleCache[moduleName].exports;
|
||||
}
|
||||
let m = {"exports":{}};
|
||||
localModuleCache[moduleName] = m;
|
||||
moduleCache[key] = m;
|
||||
let sid = addModule(m);
|
||||
let isESM = outerIsESM === true || fullPath.endsWith(".mjs") || fullPath.endsWith(".mbc");
|
||||
if (fullPath.endsWith(".cjs") || fullPath.endsWith(".cbc")) isESM = false;
|
||||
let script = isESM ? undefined : loadModule(fullPath);
|
||||
let bytecode = undefined;
|
||||
if (fullPath.endsWith(".mbc") || fullPath.endsWith(".cbc")) {
|
||||
bytecode = script;
|
||||
script = generateEmptyCode(getSourceLengthFromBytecode(bytecode));
|
||||
}
|
||||
try {
|
||||
if (fullPath.endsWith(".json")) {
|
||||
let packageConfigure = JSON.parse(script);
|
||||
|
||||
if (fullPath.endsWith("package.json")) {
|
||||
isESM = packageConfigure.type === "module"
|
||||
let url = packageConfigure.main || "index.js";
|
||||
if (isESM) {
|
||||
let packageExports = packageConfigure.exports && packageConfigure.exports["."];
|
||||
if (packageExports)
|
||||
url =
|
||||
(packageExports["default"] && packageExports["default"]["require"]) ||
|
||||
(packageExports["require"] && packageExports["require"]["default"]) ||
|
||||
packageExports["require"];
|
||||
if (!url) {
|
||||
throw new Error("can not require a esm in cjs module!");
|
||||
}
|
||||
}
|
||||
let fullDirInJs = (fullPath.indexOf('/') != -1) ? fullPath.substring(0, fullPath.lastIndexOf("/")) : fullPath.substring(0, fullPath.lastIndexOf("\\")).replace(/\\/g, '\\\\');
|
||||
let tmpRequire = genRequire(fullDirInJs, isESM);
|
||||
let r = tmpRequire(url);
|
||||
|
||||
m.exports = r;
|
||||
} else {
|
||||
m.exports = packageConfigure;
|
||||
}
|
||||
} else {
|
||||
let r = executeModule(fullPath, script, debugPath, sid, isESM, bytecode);
|
||||
if (isESM) {
|
||||
m.exports = r;
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
localModuleCache[moduleName] = undefined;
|
||||
moduleCache[key] = undefined;
|
||||
throw e;
|
||||
} finally {
|
||||
tmpModuleStorage[sid] = undefined;
|
||||
}
|
||||
return m.exports;
|
||||
}
|
||||
|
||||
return require;
|
||||
}
|
||||
|
||||
function registerBuildinModule(name, module) {
|
||||
buildinModule[name] = module;
|
||||
}
|
||||
|
||||
function forceReload(reloadModuleKey) {
|
||||
if (reloadModuleKey) {
|
||||
reloadModuleKey = normalize(reloadModuleKey);
|
||||
}
|
||||
let reloaded = false;
|
||||
for(var moduleKey in moduleCache) {
|
||||
if (!reloadModuleKey || (reloadModuleKey == moduleKey)) {
|
||||
moduleCache[moduleKey].__forceReload = true;
|
||||
reloaded = true;
|
||||
if (reloadModuleKey) break;
|
||||
}
|
||||
}
|
||||
if (!reloaded && reloadModuleKey) {
|
||||
console.warn(`reload not loaded module: ${reloadModuleKey}!`);
|
||||
}
|
||||
}
|
||||
|
||||
function getModuleByUrl(url) {
|
||||
if (url) {
|
||||
url = normalize(url);
|
||||
return moduleCache[url];
|
||||
}
|
||||
}
|
||||
|
||||
registerBuildinModule("puerts", puerts)
|
||||
|
||||
puerts.genRequire = genRequire;
|
||||
|
||||
puerts.getESMMain = getESMMain;
|
||||
|
||||
puerts.__require = genRequire("");
|
||||
|
||||
global.require = puerts.__require;
|
||||
|
||||
puerts.getModuleBySID = getModuleBySID;
|
||||
|
||||
puerts.registerBuildinModule = registerBuildinModule;
|
||||
|
||||
puerts.loadModule = loadModule;
|
||||
|
||||
puerts.forceReload = forceReload;
|
||||
|
||||
puerts.getModuleByUrl = getModuleByUrl;
|
||||
|
||||
puerts.generateEmptyCode = generateEmptyCode;
|
||||
}(global));
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
function pathBasename(path) {
|
||||
const regex = /^(.*[\/\\])?(.+)$/;
|
||||
const match = path.match(regex);
|
||||
return match ? match[2] : '';
|
||||
}
|
||||
|
||||
function pathDirname(path) {
|
||||
const regex = /^(.*[\/\\])?/;
|
||||
const match = path.match(regex);
|
||||
return match ? (match[1] || '.').replace(/[\/\\]$/, '') : '.';
|
||||
}
|
||||
|
||||
const org_load = global.puerts.load;
|
||||
const dll_ext = global.puerts.dll_ext;
|
||||
const moduleCache = {};
|
||||
|
||||
function load(filepath) {
|
||||
const iswin = dll_ext === '.dll';
|
||||
const filename = pathBasename(filepath);
|
||||
if (filepath && typeof filepath === 'string' && filename.indexOf('.') === -1) {
|
||||
const prefix = iswin ? '' : 'lib';
|
||||
filepath = `${pathDirname(filepath)}${iswin? '\\' : '/'}${prefix}${filename}${dll_ext}`;
|
||||
}
|
||||
if (!(filepath in moduleCache)) {
|
||||
const module_name = org_load(filepath);
|
||||
moduleCache[filepath] = new Proxy({__name : module_name}, {
|
||||
get: function(classCache, className) {
|
||||
if (!(className in classCache)) {
|
||||
classCache[className] = puerts.loadCPPType(`${module_name}.${className}`);
|
||||
}
|
||||
return classCache[className];
|
||||
}
|
||||
});
|
||||
}
|
||||
return moduleCache[filepath];
|
||||
}
|
||||
|
||||
global.puerts.load = load;
|
||||
|
||||
}(global));
|
||||
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
global.process = { env: { NODE_ENV: 'development' } };
|
||||
}(global));
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
const kPromiseRejectWithNoHandler = 0;
|
||||
const kPromiseHandlerAddedAfterReject = 1;
|
||||
const kPromiseRejectAfterResolved = 2;
|
||||
const kPromiseResolveAfterResolved = 3;
|
||||
|
||||
global.__tgjsSetPromiseRejectCallback(promiseRejectHandler)
|
||||
global.__tgjsSetPromiseRejectCallback = undefined;
|
||||
|
||||
const maybeUnhandledRejection = new WeakMap();
|
||||
|
||||
function promiseRejectHandler(type, promise, reason) {
|
||||
switch (type) {
|
||||
case kPromiseRejectWithNoHandler:
|
||||
maybeUnhandledRejection.set(promise, {
|
||||
reason,
|
||||
}); //maybe unhandledRejection
|
||||
Promise.resolve()
|
||||
.then(() => Promise.resolve()) // run after all microtasks
|
||||
.then(_ => unhandledRejection(promise, reason));
|
||||
break;
|
||||
case kPromiseHandlerAddedAfterReject:
|
||||
handlerAddedAfterReject(promise);
|
||||
break;
|
||||
case kPromiseResolveAfterResolved:
|
||||
console.error('kPromiseResolveAfterResolved', promise, reason);
|
||||
break;
|
||||
case kPromiseRejectAfterResolved:
|
||||
console.error('kPromiseRejectAfterResolved', promise, reason);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function unhandledRejection(promise, reason) {
|
||||
const promiseInfo = maybeUnhandledRejection.get(promise);
|
||||
if (promiseInfo === undefined) {
|
||||
return;
|
||||
}
|
||||
if (!puerts.emit('unhandledRejection', promiseInfo.reason, promise)) {
|
||||
unhandledRejectionWarning(reason);
|
||||
}
|
||||
}
|
||||
|
||||
function unhandledRejectionWarning(reason) {
|
||||
try {
|
||||
if (reason instanceof Error) {
|
||||
console.warn('unhandledRejection', reason, reason.stack);
|
||||
} else {
|
||||
console.warn('unhandledRejection', reason);
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function handlerAddedAfterReject(promise) {
|
||||
const promiseInfo = maybeUnhandledRejection.get(promise);
|
||||
if (promiseInfo !== undefined) { // cancel
|
||||
maybeUnhandledRejection.delete(promise);
|
||||
}
|
||||
}
|
||||
|
||||
const org_setTimeout = setTimeout;
|
||||
function setTimeout_p(handler, timeout, ...args) {
|
||||
return org_setTimeout(() => handler(...args), timeout);
|
||||
}
|
||||
global.setTimeout = setTimeout_p;
|
||||
|
||||
const org_setInterval = setInterval;
|
||||
function setInterval_p(handler, timeout, ...args) {
|
||||
return org_setInterval(() => handler(...args), timeout);
|
||||
}
|
||||
global.setInterval = setInterval_p;
|
||||
|
||||
}(global));
|
||||
@@ -0,0 +1,985 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
let loadUEType = global.puerts.loadUEType;
|
||||
|
||||
let loadCPPType = global.puerts.loadCPPType;
|
||||
|
||||
let cache = Object.create(null);
|
||||
|
||||
let UE = new Proxy(cache, {
|
||||
get : function(classWrapers, name)
|
||||
{
|
||||
let value = classWrapers[name];
|
||||
if (value === undefined)
|
||||
{
|
||||
value = loadUEType(name);
|
||||
classWrapers[name] = value;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
});
|
||||
|
||||
const TNAMESPACE = 0;
|
||||
const TENUM = 1
|
||||
const TBLUEPRINT = 2;
|
||||
const TSTRUCT = 3
|
||||
|
||||
function createNamespaceOrClass(path, parentDir, nodeType) {
|
||||
return new Proxy({__path: path, __parent:parentDir, __type:nodeType}, {
|
||||
get: function(node, name) {
|
||||
if (!(name in node)) {
|
||||
if (name === '__parent' || name === '__path') return undefined;
|
||||
|
||||
if (node.__type == TENUM) { // auto load
|
||||
node[name] = createNamespaceOrClass(name, node, TNAMESPACE);
|
||||
blueprint_load(node[name]);
|
||||
} else {
|
||||
let newNodeType = node.__type;
|
||||
|
||||
if (newNodeType === TNAMESPACE) {
|
||||
let path = `/${name}.${name}`
|
||||
let c = node;
|
||||
while (c && c.__path) {
|
||||
path = `/${c.__path}${path}`
|
||||
c = c.__parent;
|
||||
}
|
||||
const obj = UE.Object.Load(path, true);
|
||||
if (obj) {
|
||||
const typeName = obj.GetClass().GetName();
|
||||
if (typeName === 'UserDefinedEnum') {
|
||||
newNodeType = TENUM;
|
||||
} else if (typeName === 'UserDefinedStruct') {
|
||||
newNodeType = TSTRUCT;
|
||||
} else {
|
||||
newNodeType = TBLUEPRINT;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
node[name] = createNamespaceOrClass(name, node, newNodeType);
|
||||
}
|
||||
}
|
||||
return node[name];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cache["Game"] = createNamespaceOrClass("Game", undefined, TNAMESPACE);
|
||||
|
||||
puerts.registerBuildinModule('ue', UE);
|
||||
global.UE = UE;
|
||||
|
||||
let CPP = new Proxy(cache, {
|
||||
get: function(classWrapers, name) {
|
||||
let value = classWrapers[name];
|
||||
if (value === undefined)
|
||||
{
|
||||
value = loadCPPType(name);
|
||||
classWrapers[name] = value;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
});
|
||||
|
||||
puerts.registerBuildinModule('cpp', CPP);
|
||||
global.CPP = CPP;
|
||||
|
||||
function ref(x) {
|
||||
return [x];
|
||||
}
|
||||
|
||||
function unref(r) {
|
||||
return r[0];
|
||||
}
|
||||
|
||||
function setref(x, val) {
|
||||
x[0] = val;
|
||||
}
|
||||
|
||||
cache.NewObject = global.__tgjsNewObject;
|
||||
global.__tgjsNewObject = undefined;
|
||||
|
||||
cache.NewStruct = global.__tgjsNewStruct;
|
||||
global.__tgjsNewStruct = undefined;
|
||||
|
||||
puerts.$ref = ref;
|
||||
puerts.$unref = unref;
|
||||
puerts.$set = setref;
|
||||
puerts.merge = global.__tgjsMergeObject;
|
||||
global.__tgjsMergeObject = undefined;
|
||||
|
||||
cache.FNameLiteral = global.__tgjsFNameToArrayBuffer;
|
||||
global.__tgjsFNameToArrayBuffer = undefined;
|
||||
|
||||
let rawmakeclass = global.__tgjsMakeUClass
|
||||
global.__tgjsMakeUClass = undefined;
|
||||
|
||||
puerts.setJsTakeRef = global.__tgjsSetJsTakeRef
|
||||
global.__tgjsSetJsTakeRef = undefined
|
||||
|
||||
function defaultUeConstructor(){};
|
||||
|
||||
function makeUClass(cls) {
|
||||
if (typeof cls === 'function' && !cls.hasOwnProperty('arguments')
|
||||
&& typeof cls.StaticClass === 'function'
|
||||
&& !cls.hasOwnProperty('StaticClass')) {
|
||||
//let parentClass = Object.getPrototypeOf(cls.prototype).constructor;
|
||||
let proto = cls.prototype;
|
||||
let methods = Object.create(null);
|
||||
|
||||
let names = Object.getOwnPropertyNames(proto);
|
||||
let ueConstructor = defaultUeConstructor;
|
||||
for(var i = 0; i < names.length; ++i) {
|
||||
let name = names[i];
|
||||
let descriptor = Object.getOwnPropertyDescriptor(proto, name);
|
||||
if (typeof descriptor.value === 'function' && name != "constructor") {
|
||||
if (name === 'Constructor') {
|
||||
ueConstructor = proto[name];
|
||||
} else {
|
||||
methods[name] = proto[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rawmakeclass(ueConstructor, proto, `${cls.name}_C`, methods, cls.StaticClass());
|
||||
|
||||
} else {
|
||||
throw new Error("invalid class");
|
||||
}
|
||||
}
|
||||
|
||||
puerts.makeUClass = makeUClass;
|
||||
|
||||
let UEClassToJSClass = global.__tgjsUEClassToJSClass;
|
||||
global.__tgjsUEClassToJSClass = undefined;
|
||||
|
||||
function blueprint(path) {
|
||||
console.warn('deprecated! use blueprint.tojs instead');
|
||||
let ufield = UE.Field.Load(path, true);
|
||||
if (ufield) {
|
||||
let jsclass = UEClassToJSClass(ufield);
|
||||
jsclass.__puerts_ufield = ufield;
|
||||
return jsclass;
|
||||
} else {
|
||||
throw new Error("can not load type in " + path);
|
||||
}
|
||||
}
|
||||
|
||||
blueprint.tojs = UEClassToJSClass;
|
||||
|
||||
let __tgjsMixin = global.__tgjsMixin;
|
||||
global.__tgjsMixin = undefined;
|
||||
|
||||
function mixin(to, mixinClass, config) {
|
||||
config = config || {};
|
||||
let mixinMethods = Object.create(null);
|
||||
let names = Object.getOwnPropertyNames(mixinClass.prototype);
|
||||
for(var i = 0; i < names.length; ++i) {
|
||||
let name = names[i];
|
||||
let descriptor = Object.getOwnPropertyDescriptor(mixinClass.prototype, name);
|
||||
if (typeof descriptor.value === 'function' && name != "constructor") {
|
||||
mixinMethods[name] = mixinClass.prototype[name];
|
||||
}
|
||||
}
|
||||
let cls = __tgjsMixin(to.StaticClass(), mixinMethods, config.objectTakeByNative, config.inherit, config.noMixinedWarning);
|
||||
|
||||
let jsCls = UEClassToJSClass(cls);
|
||||
Object.getOwnPropertyNames(mixinMethods).forEach(name => {
|
||||
if (!jsCls.prototype.hasOwnProperty(name)) {
|
||||
Object.defineProperty(
|
||||
jsCls.prototype,
|
||||
name,
|
||||
Object.getOwnPropertyDescriptor(mixinMethods, name) ||
|
||||
Object.create(null)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (config.inherit) {
|
||||
config.generatedClass = cls;
|
||||
}
|
||||
return jsCls;
|
||||
}
|
||||
|
||||
blueprint.mixin = mixin;
|
||||
|
||||
function unmixin(to) {
|
||||
__tgjsMixin(to.StaticClass(), {}, undefined, undefined, undefined, true);
|
||||
}
|
||||
|
||||
blueprint.unmixin = unmixin;
|
||||
|
||||
function blueprint_load(cls) {
|
||||
if (cls.__path) {
|
||||
let c = cls
|
||||
let path = `.${c.__path}`
|
||||
c = c.__parent;
|
||||
while (c && c.__path) {
|
||||
path = `/${c.__path}${path}`
|
||||
c = c.__parent;
|
||||
}
|
||||
let ufield = UE.Field.Load(path, true);
|
||||
if (!ufield) {
|
||||
throw new Error(`load ${path} fail!`);
|
||||
}
|
||||
let jsclass = UEClassToJSClass(ufield);
|
||||
jsclass.__puerts_ufield = ufield;
|
||||
|
||||
if (cls.__parent) {
|
||||
jsclass.__parent = cls.__parent;
|
||||
jsclass.__name = cls.__path;
|
||||
cls.__parent[cls.__path] = jsclass;
|
||||
}
|
||||
|
||||
} else {
|
||||
throw new Error("argument #0 is not a unload type");
|
||||
}
|
||||
}
|
||||
|
||||
blueprint.load = blueprint_load;
|
||||
|
||||
function blueprint_unload(cls) {
|
||||
if (cls.__puerts_ufield) {
|
||||
cls.__puerts_ufield = undefined;
|
||||
if (cls.__parent) {
|
||||
cls.__parent[cls.__name] = createNamespaceOrClass(cls.__name, cls.__parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
blueprint.unload = blueprint_unload;
|
||||
|
||||
puerts.blueprint = blueprint;
|
||||
|
||||
const newContainer = global.__tgjsNewContainer;
|
||||
global.__tgjsNewContainer = undefined;
|
||||
|
||||
function translateType(t) {
|
||||
if (typeof t !== 'number') {
|
||||
if (t.hasOwnProperty('__puerts_ufield')) {
|
||||
return t.__puerts_ufield
|
||||
} else {
|
||||
return t.StaticClass();
|
||||
}
|
||||
} else {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
function NewArray(t1) {
|
||||
t1 = translateType(t1);
|
||||
|
||||
var ret = newContainer(0, t1);
|
||||
if (!("[Symbol.iterator]" in ret)) {
|
||||
ret.constructor.prototype[Symbol.iterator] = function*() {
|
||||
let index = 0;
|
||||
let num = this.Num();
|
||||
while (index < num) {
|
||||
yield this.Get(index);
|
||||
index++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
function NewSet(t1) {
|
||||
t1 = translateType(t1);
|
||||
|
||||
var ret = newContainer(1, t1);
|
||||
if (!("[Symbol.iterator]" in ret)) {
|
||||
ret.constructor.prototype[Symbol.iterator] = function*() {
|
||||
let index = 0;
|
||||
let maxIndex = this.GetMaxIndex();
|
||||
while (index < maxIndex) {
|
||||
if (this.IsValidIndex(index)) {
|
||||
yield this.Get(index);
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
function NewMap(t1, t2) {
|
||||
t1 = translateType(t1);
|
||||
t2 = translateType(t2);
|
||||
|
||||
var ret = newContainer(2, t1, t2);
|
||||
if (!("[Symbol.iterator]" in ret)) {
|
||||
ret.constructor.prototype[Symbol.iterator] = function*() {
|
||||
let index = 0;
|
||||
let maxIndex = this.GetMaxIndex();
|
||||
while (index < maxIndex) {
|
||||
if (this.IsValidIndex(index)) {
|
||||
let key = this.GetKey(index);
|
||||
let value = this.Get(key);
|
||||
yield [key, value];
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
cache.BuiltinBool = 0;
|
||||
cache.BuiltinByte = 1;
|
||||
cache.BuiltinInt = 2;
|
||||
cache.BuiltinFloat = 3;
|
||||
cache.BuiltinDouble = 4;
|
||||
cache.BuiltinInt64 = 5;
|
||||
cache.BuiltinString = 6;
|
||||
cache.BuiltinText = 7;
|
||||
cache.BuiltinName = 8;
|
||||
|
||||
// call once to inject iterators to constructor
|
||||
NewArray(cache.BuiltinInt);
|
||||
NewSet(cache.BuiltinInt);
|
||||
NewMap(cache.BuiltinInt, cache.BuiltinInt);
|
||||
|
||||
cache.NewArray = NewArray;
|
||||
cache.NewSet = NewSet;
|
||||
cache.NewMap = NewMap;
|
||||
|
||||
const FunctionFlags = {
|
||||
FUNC_None : 0x00000000,
|
||||
|
||||
FUNC_Final : 0x00000001, // Function is final (prebindable, non-overridable function).
|
||||
FUNC_RequiredAPI : 0x00000002, // Indicates this function is DLL exported/imported.
|
||||
FUNC_BlueprintAuthorityOnly: 0x00000004, // Function will only run if the object has network authority
|
||||
FUNC_BlueprintCosmetic : 0x00000008, // Function is cosmetic in nature and should not be invoked on dedicated servers
|
||||
// FUNC_ : 0x00000010, // unused.
|
||||
// FUNC_ : 0x00000020, // unused.
|
||||
FUNC_Net : 0x00000040, // Function is network-replicated.
|
||||
FUNC_NetReliable : 0x00000080, // Function should be sent reliably on the network.
|
||||
FUNC_NetRequest : 0x00000100, // Function is sent to a net service
|
||||
FUNC_Exec : 0x00000200, // Executable from command line.
|
||||
FUNC_Native : 0x00000400, // Native function.
|
||||
FUNC_Event : 0x00000800, // Event function.
|
||||
FUNC_NetResponse : 0x00001000, // Function response from a net service
|
||||
FUNC_Static : 0x00002000, // Static function.
|
||||
FUNC_NetMulticast : 0x00004000, // Function is networked multicast Server -> All Clients
|
||||
FUNC_UbergraphFunction : 0x00008000, // Function is used as the merge 'ubergraph' for a blueprint, only assigned when using the persistent 'ubergraph' frame
|
||||
FUNC_MulticastDelegate : 0x00010000, // Function is a multi-cast delegate signature (also requires FUNC_Delegate to be set!)
|
||||
FUNC_Public : 0x00020000, // Function is accessible in all classes (if overridden, parameters must remain unchanged).
|
||||
FUNC_Private : 0x00040000, // Function is accessible only in the class it is defined in (cannot be overridden, but function name may be reused in subclasses. IOW: if overridden, parameters don't need to match, and Super.Func() cannot be accessed since it's private.)
|
||||
FUNC_Protected : 0x00080000, // Function is accessible only in the class it is defined in and subclasses (if overridden, parameters much remain unchanged).
|
||||
FUNC_Delegate : 0x00100000, // Function is delegate signature (either single-cast or multi-cast, depending on whether FUNC_MulticastDelegate is set.)
|
||||
FUNC_NetServer : 0x00200000, // Function is executed on servers (set by replication code if passes check)
|
||||
FUNC_HasOutParms : 0x00400000, // function has out (pass by reference) parameters
|
||||
FUNC_HasDefaults : 0x00800000, // function has structs that contain defaults
|
||||
FUNC_NetClient : 0x01000000, // function is executed on clients
|
||||
FUNC_DLLImport : 0x02000000, // function is imported from a DLL
|
||||
FUNC_BlueprintCallable : 0x04000000, // function can be called from blueprint code
|
||||
FUNC_BlueprintEvent : 0x08000000, // function can be overridden/implemented from a blueprint
|
||||
FUNC_BlueprintPure : 0x10000000, // function can be called from blueprint code, and is also pure (produces no side effects). If you set this, you should set FUNC_BlueprintCallable as well.
|
||||
FUNC_EditorOnly : 0x20000000, // function can only be called from an editor scrippt.
|
||||
FUNC_Const : 0x40000000, // function can be called from blueprint code, and only reads state (never writes state)
|
||||
FUNC_NetValidate : 0x80000000, // function must supply a _Validate implementation
|
||||
|
||||
FUNC_AllFlags : 0xFFFFFFFF,
|
||||
};
|
||||
Object.freeze(FunctionFlags);
|
||||
|
||||
const FunctionExportFlags =
|
||||
{
|
||||
FUNCEXPORT_Final :0x00000001, // function declaration included "final" keyword. Used to differentiate between functions that have FUNC_Final only because they're private
|
||||
// =0x00000002,
|
||||
// =0x00000004,
|
||||
FUNCEXPORT_RequiredAPI :0x00000008, // Function should be exported as a public API function
|
||||
FUNCEXPORT_Inline :0x00000010, // export as an inline static C++ function
|
||||
FUNCEXPORT_CppStatic :0x00000020, // Export as a real C++ static function, causing thunks to call via ClassName::FuncName instead of this->FuncName
|
||||
FUNCEXPORT_CustomThunk :0x00000040, // Export no thunk function; the user will manually define a custom one
|
||||
// =0x00000080,
|
||||
// =0x00000100,
|
||||
};
|
||||
Object.freeze(FunctionExportFlags)
|
||||
|
||||
const ELifetimeCondition = {
|
||||
"COND_InitialOnly" : 1 , // This property will only attempt to send on the initial bunch
|
||||
"COND_OwnerOnly" : 2 , // This property will only send to the actor's owner
|
||||
"COND_SkipOwner" : 3 , // This property send to every connection EXCEPT the owner
|
||||
"COND_SimulatedOnly" : 4 , // This property will only send to simulated actors
|
||||
"COND_AutonomousOnly" : 5 , // This property will only send to autonomous actors
|
||||
"COND_SimulatedOrPhysics" : 6 , // This property will send to simulated OR bRepPhysics actors
|
||||
"COND_InitialOrOwner" : 7 , // This property will send on the initial packet, or to the actors owner
|
||||
"COND_Custom" : 8 , // This property has no particular condition, but wants the ability to toggle on/off via SetCustomIsActiveOverride
|
||||
"COND_ReplayOrOwner" : 9 , // This property will only send to the replay connection, or to the actors owner
|
||||
"COND_ReplayOnly" : 10 , // This property will only send to the replay connection
|
||||
"COND_SimulatedOnlyNoReplay" : 11 , // This property will send to actors only, but not to replay connections
|
||||
"COND_SimulatedOrPhysicsNoReplay" : 12 , // This property will send to simulated Or bRepPhysics actors, but not to replay connections
|
||||
"COND_SkipReplay" : 13 , // This property will not send to the replay connection
|
||||
"COND_Never" : 15 , // This property will never be replicated
|
||||
}
|
||||
Object.freeze(ELifetimeCondition);
|
||||
|
||||
const ClassFlags = {
|
||||
CLASS_None: 0x00000000,
|
||||
/** Class is abstract and can't be instantiated directly. */
|
||||
CLASS_Abstract: 0x00000001,
|
||||
/** Save object configuration only to Default INIs, never to local INIs. Must be combined with CLASS_Config */
|
||||
CLASS_DefaultConfig: 0x00000002,
|
||||
/** Load object configuration at construction time. */
|
||||
CLASS_Config: 0x00000004,
|
||||
/** This object type can't be saved; null it out at save time. */
|
||||
CLASS_Transient: 0x00000008,
|
||||
/** Successfully parsed. */
|
||||
CLASS_Parsed: 0x00000010,
|
||||
/** */
|
||||
CLASS_MatchedSerializers: 0x00000020,
|
||||
/** Indicates that the config settings for this class will be saved to Project/User*.ini (similar to CLASS_GlobalUserConfig) */
|
||||
CLASS_ProjectUserConfig: 0x00000040,
|
||||
/** Class is a native class - native interfaces will have CLASS_Native set, but not RF_MarkAsNative */
|
||||
CLASS_Native: 0x00000080,
|
||||
/** Don't export to C++ header. */
|
||||
CLASS_NoExport: 0x00000100,
|
||||
/** Do not allow users to create in the editor. */
|
||||
CLASS_NotPlaceable: 0x00000200,
|
||||
/** Handle object configuration on a per-object basis, rather than per-class. */
|
||||
CLASS_PerObjectConfig: 0x00000400,
|
||||
|
||||
/** Whether SetUpRuntimeReplicationData still needs to be called for this class */
|
||||
CLASS_ReplicationDataIsSetUp: 0x00000800,
|
||||
|
||||
/** Class can be constructed from editinline New button. */
|
||||
CLASS_EditInlineNew: 0x00001000,
|
||||
/** Display properties in the editor without using categories. */
|
||||
CLASS_CollapseCategories: 0x00002000,
|
||||
/** Class is an interface **/
|
||||
CLASS_Interface: 0x00004000,
|
||||
/** Do not export a constructor for this class, assuming it is in the cpptext **/
|
||||
CLASS_CustomConstructor: 0x00008000,
|
||||
/** all properties and functions in this class are const and should be exported as const */
|
||||
CLASS_Const: 0x00010000,
|
||||
|
||||
/** Class flag indicating the class is having its layout changed, and therefore is not ready for a CDO to be created */
|
||||
CLASS_LayoutChanging: 0x00020000,
|
||||
|
||||
/** Indicates that the class was created from blueprint source material */
|
||||
CLASS_CompiledFromBlueprint: 0x00040000,
|
||||
|
||||
/** Indicates that only the bare minimum bits of this class should be DLL exported/imported */
|
||||
CLASS_MinimalAPI: 0x00080000,
|
||||
|
||||
/** Indicates this class must be DLL exported/imported (along with all of it's members) */
|
||||
CLASS_RequiredAPI: 0x00100000,
|
||||
|
||||
/** Indicates that references to this class default to instanced. Used to be subclasses of UComponent, but now can be any UObject */
|
||||
CLASS_DefaultToInstanced: 0x00200000,
|
||||
|
||||
/** Indicates that the parent token stream has been merged with ours. */
|
||||
CLASS_TokenStreamAssembled: 0x00400000,
|
||||
/** Class has component properties. */
|
||||
CLASS_HasInstancedReference: 0x00800000,
|
||||
/** Don't show this class in the editor class browser or edit inline new menus. */
|
||||
CLASS_Hidden: 0x01000000,
|
||||
/** Don't save objects of this class when serializing */
|
||||
CLASS_Deprecated: 0x02000000,
|
||||
/** Class not shown in editor drop down for class selection */
|
||||
CLASS_HideDropDown: 0x04000000,
|
||||
/** Class settings are saved to <AppData>/..../Blah.ini (as opposed to CLASS_DefaultConfig) */
|
||||
CLASS_GlobalUserConfig: 0x08000000,
|
||||
/** Class was declared directly in C++ and has no boilerplate generated by UnrealHeaderTool */
|
||||
CLASS_Intrinsic : 0x10000000,
|
||||
/** Class has already been constructed (maybe in a previous DLL version before hot-reload). */
|
||||
CLASS_Constructed: 0x20000000,
|
||||
/** Indicates that object configuration will not check against ini base/defaults when serialized */
|
||||
CLASS_ConfigDoNotCheckDefaults: 0x40000000,
|
||||
/** Class has been consigned to oblivion as part of a blueprint recompile, and a newer version currently exists. */
|
||||
CLASS_NewerVersionExists: 0x80000000,
|
||||
}
|
||||
|
||||
const PropertyFlags =
|
||||
{
|
||||
CPF_None : 0,
|
||||
|
||||
CPF_Edit : 0x0000000000000001, ///< Property is user-settable in the editor.
|
||||
CPF_ConstParm : 0x0000000000000002, ///< This is a constant function parameter
|
||||
CPF_BlueprintVisible : 0x0000000000000004, ///< This property can be read by blueprint code
|
||||
CPF_ExportObject : 0x0000000000000008, ///< Object can be exported with actor.
|
||||
CPF_BlueprintReadOnly : 0x0000000000000010, ///< This property cannot be modified by blueprint code
|
||||
CPF_Net : 0x0000000000000020, ///< Property is relevant to network replication.
|
||||
CPF_EditFixedSize : 0x0000000000000040, ///< Indicates that elements of an array can be modified, but its size cannot be changed.
|
||||
CPF_Parm : 0x0000000000000080, ///< Function/When call parameter.
|
||||
CPF_OutParm : 0x0000000000000100, ///< Value is copied out after function call.
|
||||
CPF_ZeroConstructor : 0x0000000000000200, ///< memset is fine for construction
|
||||
CPF_ReturnParm : 0x0000000000000400, ///< Return value.
|
||||
CPF_DisableEditOnTemplate : 0x0000000000000800, ///< Disable editing of this property on an archetype/sub-blueprint
|
||||
//CPF_ : 0x0000000000001000, ///<
|
||||
CPF_Transient : 0x0000000000002000, ///< Property is transient: shouldn't be saved or loaded, except for Blueprint CDOs.
|
||||
CPF_Config : 0x0000000000004000, ///< Property should be loaded/saved as permanent profile.
|
||||
//CPF_ : 0x0000000000008000, ///<
|
||||
CPF_DisableEditOnInstance : 0x0000000000010000, ///< Disable editing on an instance of this class
|
||||
CPF_EditConst : 0x0000000000020000, ///< Property is uneditable in the editor.
|
||||
CPF_GlobalConfig : 0x0000000000040000, ///< Load config from base class, not subclass.
|
||||
CPF_InstancedReference : 0x0000000000080000, ///< Property is a component references.
|
||||
//CPF_ : 0x0000000000100000, ///<
|
||||
CPF_DuplicateTransient : 0x0000000000200000, ///< Property should always be reset to the default value during any type of duplication (copy/paste, binary duplication, etc.)
|
||||
//CPF_ : 0x0000000000400000, ///<
|
||||
//CPF_ : 0x0000000000800000, ///<
|
||||
CPF_SaveGame : 0x0000000001000000, ///< Property should be serialized for save games, this is only checked for game-specific archives with ArIsSaveGame
|
||||
CPF_NoClear : 0x0000000002000000, ///< Hide clear (and browse) button.
|
||||
//CPF_ : 0x0000000004000000, ///<
|
||||
CPF_ReferenceParm : 0x0000000008000000, ///< Value is passed by reference; CPF_OutParam and CPF_Param should also be set.
|
||||
CPF_BlueprintAssignable : 0x0000000010000000, ///< MC Delegates only. Property should be exposed for assigning in blueprint code
|
||||
CPF_Deprecated : 0x0000000020000000, ///< Property is deprecated. Read it from an archive, but don't save it.
|
||||
CPF_IsPlainOldData : 0x0000000040000000, ///< If this is set, then the property can be memcopied instead of CopyCompleteValue / CopySingleValue
|
||||
CPF_RepSkip : 0x0000000080000000, ///< Not replicated. For non replicated properties in replicated structs
|
||||
CPF_RepNotify : 0x0000000100000000, ///< Notify actors when a property is replicated
|
||||
CPF_Interp : 0x0000000200000000, ///< interpolatable property for use with matinee
|
||||
CPF_NonTransactional : 0x0000000400000000, ///< Property isn't transacted
|
||||
CPF_EditorOnly : 0x0000000800000000, ///< Property should only be loaded in the editor
|
||||
CPF_NoDestructor : 0x0000001000000000, ///< No destructor
|
||||
//CPF_ : 0x0000002000000000, ///<
|
||||
CPF_AutoWeak : 0x0000004000000000, ///< Only used for weak pointers, means the export type is autoweak
|
||||
CPF_ContainsInstancedReference : 0x0000008000000000, ///< Property contains component references.
|
||||
CPF_AssetRegistrySearchable : 0x0000010000000000, ///< asset instances will add properties with this flag to the asset registry automatically
|
||||
CPF_SimpleDisplay : 0x0000020000000000, ///< The property is visible by default in the editor details view
|
||||
CPF_AdvancedDisplay : 0x0000040000000000, ///< The property is advanced and not visible by default in the editor details view
|
||||
CPF_Protected : 0x0000080000000000, ///< property is protected from the perspective of script
|
||||
CPF_BlueprintCallable : 0x0000100000000000, ///< MC Delegates only. Property should be exposed for calling in blueprint code
|
||||
CPF_BlueprintAuthorityOnly : 0x0000200000000000, ///< MC Delegates only. This delegate accepts (only in blueprint) only events with BlueprintAuthorityOnly.
|
||||
CPF_TextExportTransient : 0x0000400000000000, ///< Property shouldn't be exported to text format (e.g. copy/paste)
|
||||
CPF_NonPIEDuplicateTransient : 0x0000800000000000, ///< Property should only be copied in PIE
|
||||
CPF_ExposeOnSpawn : 0x0001000000000000, ///< Property is exposed on spawn
|
||||
CPF_PersistentInstance : 0x0002000000000000, ///< A object referenced by the property is duplicated like a component. (Each actor should have an own instance.)
|
||||
CPF_UObjectWrapper : 0x0004000000000000, ///< Property was parsed as a wrapper class like TSubclassOf<T>, FScriptInterface etc., rather than a USomething*
|
||||
CPF_HasGetValueTypeHash : 0x0008000000000000, ///< This property can generate a meaningful hash value.
|
||||
CPF_NativeAccessSpecifierPublic : 0x0010000000000000, ///< Public native access specifier
|
||||
CPF_NativeAccessSpecifierProtected : 0x0020000000000000, ///< Protected native access specifier
|
||||
CPF_NativeAccessSpecifierPrivate : 0x0040000000000000, ///< Private native access specifier
|
||||
CPF_SkipSerialization : 0x0080000000000000, ///< Property shouldn't be serialized, can still be exported to text
|
||||
}
|
||||
|
||||
|
||||
function dummyDecorator() {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
cache.rpc = {
|
||||
"FunctionFlags" : FunctionFlags,
|
||||
"PropertyFlags" : PropertyFlags,
|
||||
"ELifetimeCondition" : ELifetimeCondition,
|
||||
"flags" : dummyDecorator,
|
||||
"condition" : dummyDecorator
|
||||
}
|
||||
|
||||
const MetaDataInst = '';
|
||||
|
||||
cache.uclass = {
|
||||
// the class specifier
|
||||
"ClassGroup": MetaDataInst,
|
||||
"Within": MetaDataInst,
|
||||
"BlueprintType": MetaDataInst,
|
||||
"NotBlueprintType": MetaDataInst,
|
||||
"Blueprintable": MetaDataInst,
|
||||
"NotBlueprintable": MetaDataInst,
|
||||
"MinimalAPI": MetaDataInst,
|
||||
"customConstructor": MetaDataInst,
|
||||
"Intrinsic": MetaDataInst,
|
||||
"noexport": MetaDataInst,
|
||||
"placeable": MetaDataInst,
|
||||
"notplaceable": MetaDataInst,
|
||||
"DefaultToInstanced": MetaDataInst,
|
||||
"Const": MetaDataInst,
|
||||
"Abstract": MetaDataInst,
|
||||
"deprecated": MetaDataInst,
|
||||
"Transient": MetaDataInst,
|
||||
"nonTransient": MetaDataInst,
|
||||
"config": MetaDataInst,
|
||||
"perObjectConfig": MetaDataInst,
|
||||
"configdonotcheckdefaults": MetaDataInst,
|
||||
"defaultconfig": MetaDataInst,
|
||||
"editinlinenew": MetaDataInst,
|
||||
"noteditinlinenew": MetaDataInst,
|
||||
"hidedropdown": MetaDataInst,
|
||||
"showCategories": MetaDataInst,
|
||||
"hideCategories": MetaDataInst,
|
||||
"ComponentWrapperClass": MetaDataInst,
|
||||
"showFunctions": MetaDataInst,
|
||||
"hideFunctions": MetaDataInst,
|
||||
"autoExpandCategories": MetaDataInst,
|
||||
"autoCollapseCategories": MetaDataInst,
|
||||
"dontAutoCollapseCategories": MetaDataInst,
|
||||
"collapseCategories": MetaDataInst,
|
||||
"dontCollapseCategories": MetaDataInst,
|
||||
"AdvancedClassDisplay": MetaDataInst,
|
||||
"ConversionRoot": MetaDataInst,
|
||||
"Experimental": MetaDataInst,
|
||||
"EarlyAccessPreview": MetaDataInst,
|
||||
"SparseClassDataType": MetaDataInst,
|
||||
"CustomThunkTemplates": MetaDataInst,
|
||||
// decorator to add class specifier
|
||||
"uclass": dummyDecorator,
|
||||
// metadata of class
|
||||
"ToolTip": MetaDataInst,
|
||||
"ShortTooltip": MetaDataInst,
|
||||
"DocumentationPolicy": MetaDataInst,
|
||||
"BlueprintSpawnableComponent": MetaDataInst,
|
||||
"ChildCanTick": MetaDataInst,
|
||||
"ChildCannotTick": MetaDataInst,
|
||||
"IgnoreCategoryKeywordsInSubclasses": MetaDataInst,
|
||||
"DeprecatedNode": MetaDataInst,
|
||||
"DeprecationMessage": MetaDataInst,
|
||||
"DisplayName": MetaDataInst,
|
||||
"ScriptName": MetaDataInst,
|
||||
"IsBlueprintBase": MetaDataInst,
|
||||
"KismetHideOverrides": MetaDataInst,
|
||||
"ProhibitedInterfaces": MetaDataInst,
|
||||
"RestrictedToClasses": MetaDataInst,
|
||||
"ShowWorldContextPin": MetaDataInst,
|
||||
"DontUseGenericSpawnObject": MetaDataInst,
|
||||
"ExposedAsyncProxy": MetaDataInst,
|
||||
"BlueprintThreadSafe": MetaDataInst,
|
||||
"UsesHierarchy": MetaDataInst,
|
||||
// decorator to add class metadata
|
||||
"umeta": dummyDecorator
|
||||
}
|
||||
|
||||
cache.ufunction = {
|
||||
// the function specifier
|
||||
"BlueprintImplementableEvent": MetaDataInst,
|
||||
"BlueprintNativeEvent": MetaDataInst,
|
||||
"SealedEvent": MetaDataInst,
|
||||
"Exec": MetaDataInst,
|
||||
"Server": MetaDataInst,
|
||||
"Client": MetaDataInst,
|
||||
"NetMulticast": MetaDataInst,
|
||||
"Reliable": MetaDataInst,
|
||||
"Unreliable": MetaDataInst,
|
||||
"BlueprintPure": MetaDataInst,
|
||||
"BlueprintCallable": MetaDataInst,
|
||||
"BlueprintGetter": MetaDataInst,
|
||||
"BlueprintSetter": MetaDataInst,
|
||||
"BlueprintAuthorityOnly": MetaDataInst,
|
||||
"BlueprintCosmetic": MetaDataInst,
|
||||
"BlueprintInternalUseOnly": MetaDataInst,
|
||||
"CallInEditor": MetaDataInst,
|
||||
"CustomThunk": MetaDataInst,
|
||||
"Category": MetaDataInst,
|
||||
"WithValidation": MetaDataInst,
|
||||
"ServiceRequest": MetaDataInst,
|
||||
"ServiceResponse": MetaDataInst,
|
||||
"Variadic": MetaDataInst,
|
||||
"ReturnDisplayName": MetaDataInst,
|
||||
"InternalUseParam": MetaDataInst,
|
||||
// decorator to add function specifier
|
||||
"ufunction": dummyDecorator,
|
||||
// type of metadata specifier
|
||||
"ToolTip": MetaDataInst,
|
||||
"ShortTooltip": MetaDataInst,
|
||||
"DocumentationPolicy": MetaDataInst,
|
||||
"AdvancedDisplay": MetaDataInst,
|
||||
"ArrayParm": MetaDataInst,
|
||||
"ArrayTypeDependentParams": MetaDataInst,
|
||||
"AutoCreateRefTerm": MetaDataInst,
|
||||
"BlueprintProtected": MetaDataInst,
|
||||
"CallableWithoutWorldContext": MetaDataInst,
|
||||
"CommutativeAssociativeBinaryOperator": MetaDataInst,
|
||||
"CompactNodeTitle": MetaDataInst,
|
||||
"CustomStructureParam": MetaDataInst,
|
||||
"DefaultToSelf": MetaDataInst,
|
||||
"DeprecatedFunction": MetaDataInst,
|
||||
"DeprecationMessage": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the function section)
|
||||
"ExpandEnumAsExecs": MetaDataInst,
|
||||
"ExpandBoolAsExecs": MetaDataInst,
|
||||
"DisplayName": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the function section)
|
||||
"ScriptName": MetaDataInst, // (Commented out so as to avoid duplicate name with version in the Class section, but still show in the function section)
|
||||
"ScriptNoExport": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Property section, but still show in the function section)
|
||||
"ScriptMethod": MetaDataInst,
|
||||
"ScriptMethodSelfReturn": MetaDataInst,
|
||||
"ScriptOperator": MetaDataInst,
|
||||
"ScriptConstant": MetaDataInst,
|
||||
"ScriptConstantHost": MetaDataInst,
|
||||
"HidePin": MetaDataInst,
|
||||
"HideSpawnParms": MetaDataInst,
|
||||
"Keywords": MetaDataInst,
|
||||
"Latent": MetaDataInst,
|
||||
"LatentInfo": MetaDataInst,
|
||||
"MaterialParameterCollectionFunction": MetaDataInst,
|
||||
"NativeBreakFunc": MetaDataInst,
|
||||
"NativeMakeFunc": MetaDataInst,
|
||||
"UnsafeDuringActorConstruction": MetaDataInst,
|
||||
"WorldContext": MetaDataInst,
|
||||
"BlueprintAutocast": MetaDataInst,
|
||||
"NotBlueprintThreadSafe": MetaDataInst,
|
||||
"DeterminesOutputType": MetaDataInst,
|
||||
"DynamicOutputParam": MetaDataInst,
|
||||
"DataTablePin": MetaDataInst,
|
||||
"SetParam": MetaDataInst,
|
||||
"MapParam": MetaDataInst,
|
||||
"MapKeyParam": MetaDataInst,
|
||||
"MapValueParam": MetaDataInst,
|
||||
"AnimBlueprintFunction": MetaDataInst,
|
||||
"ArrayParam": MetaDataInst,
|
||||
// decorator to add function metadata
|
||||
"umeta": dummyDecorator
|
||||
}
|
||||
|
||||
cache.uproperty = {
|
||||
// the specifiers
|
||||
"Const": MetaDataInst,
|
||||
"Config": MetaDataInst,
|
||||
"GlobalConfig": MetaDataInst,
|
||||
"Localized": MetaDataInst,
|
||||
"Transient": MetaDataInst,
|
||||
"DuplicateTransient": MetaDataInst,
|
||||
"NonPIETransient": MetaDataInst,
|
||||
"NonPIEDuplicateTransient": MetaDataInst,
|
||||
"Export": MetaDataInst,
|
||||
"NoClear": MetaDataInst,
|
||||
"EditFixedSize": MetaDataInst,
|
||||
"Replicated": MetaDataInst,
|
||||
"ReplicatedUsing": MetaDataInst,
|
||||
"NotReplicated": MetaDataInst,
|
||||
"Interp": MetaDataInst,
|
||||
"NonTransactional": MetaDataInst,
|
||||
"Instanced": MetaDataInst,
|
||||
"BlueprintAssignable": MetaDataInst,
|
||||
"Category": MetaDataInst,
|
||||
"SimpleDisplay": MetaDataInst,
|
||||
"AdvancedDisplay": MetaDataInst,
|
||||
"EditAnywhere": MetaDataInst,
|
||||
"EditInstanceOnly": MetaDataInst,
|
||||
"EditDefaultsOnly": MetaDataInst,
|
||||
"VisibleAnywhere": MetaDataInst,
|
||||
"VisibleInstanceOnly": MetaDataInst,
|
||||
"VisibleDefaultsOnly": MetaDataInst,
|
||||
"BlueprintReadOnly": MetaDataInst,
|
||||
"BlueprintGetter": MetaDataInst,
|
||||
"BlueprintReadWrite": MetaDataInst,
|
||||
"BlueprintSetter": MetaDataInst,
|
||||
"AssetRegistrySearchable": MetaDataInst,
|
||||
"SaveGame": MetaDataInst,
|
||||
"BlueprintCallable": MetaDataInst,
|
||||
"BlueprintAuthorityOnly": MetaDataInst,
|
||||
"TextExportTransient": MetaDataInst,
|
||||
"SkipSerialization": MetaDataInst,
|
||||
"HideSelfPin": MetaDataInst,
|
||||
// decorator
|
||||
"uproperty": dummyDecorator,
|
||||
// specifier
|
||||
"ToolTip": MetaDataInst,
|
||||
"ShortTooltip": MetaDataInst,
|
||||
"DocumentationPolicy": MetaDataInst,
|
||||
"AllowAbstract": MetaDataInst,
|
||||
"AllowAnyActor": MetaDataInst,
|
||||
"AllowedClasses": MetaDataInst,
|
||||
"AllowPreserveRatio": MetaDataInst,
|
||||
"AllowPrivateAccess": MetaDataInst,
|
||||
"ArrayClamp": MetaDataInst,
|
||||
"AssetBundles": MetaDataInst,
|
||||
"BlueprintBaseOnly": MetaDataInst,
|
||||
"BlueprintCompilerGeneratedDefaults": MetaDataInst,
|
||||
"ClampMin": MetaDataInst,
|
||||
"ClampMax": MetaDataInst,
|
||||
"ConfigHierarchyEditable": MetaDataInst,
|
||||
"ContentDir": MetaDataInst,
|
||||
"DeprecatedProperty": MetaDataInst,
|
||||
"DeprecationMessage": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
|
||||
"DisplayName": MetaDataInst, // (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
|
||||
"ScriptName": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
|
||||
"DisallowedClasses": MetaDataInst,
|
||||
"DisplayAfter": MetaDataInst,
|
||||
"DisplayPriority": MetaDataInst,
|
||||
"DisplayThumbnail": MetaDataInst,
|
||||
"EditCondition": MetaDataInst,
|
||||
"EditFixedOrder": MetaDataInst,
|
||||
"ExactClass": MetaDataInst,
|
||||
"ExposeFunctionCategories": MetaDataInst,
|
||||
"ExposeOnSpawn": MetaDataInst,
|
||||
"FilePathFilter": MetaDataInst,
|
||||
"RelativeToGameDir": MetaDataInst,
|
||||
"ForceShowEngineContent": MetaDataInst,
|
||||
"ForceShowPluginContent": MetaDataInst,
|
||||
"HideAlphaChannel": MetaDataInst,
|
||||
"HideInDetailPanel": MetaDataInst,
|
||||
"HideViewOptions": MetaDataInst,
|
||||
"IgnoreForMemberInitializationTest": MetaDataInst,
|
||||
"InlineEditConditionToggle": MetaDataInst,
|
||||
"LongPackageName": MetaDataInst,
|
||||
"MakeEditWidget": MetaDataInst,
|
||||
"MakeStructureDefaultValue": MetaDataInst,
|
||||
"MetaClass": MetaDataInst,
|
||||
"MustImplement": MetaDataInst,
|
||||
"Multiple": MetaDataInst,
|
||||
"MultiLine": MetaDataInst,
|
||||
"PasswordField": MetaDataInst,
|
||||
"NoElementDuplicate": MetaDataInst,
|
||||
"NoResetToDefault": MetaDataInst,
|
||||
"NoSpinbox": MetaDataInst,
|
||||
"OnlyPlaceable": MetaDataInst,
|
||||
"RelativePath": MetaDataInst,
|
||||
"RelativeToGameContentDir": MetaDataInst,
|
||||
"ScriptNoExport": MetaDataInst,
|
||||
"ShowOnlyInnerProperties": MetaDataInst,
|
||||
"ShowTreeView": MetaDataInst,
|
||||
"SliderExponent": MetaDataInst,
|
||||
"TitleProperty": MetaDataInst,
|
||||
"UIMin": MetaDataInst,
|
||||
"UIMax": MetaDataInst,
|
||||
"Untracked": MetaDataInst,
|
||||
"DevelopmentOnly": MetaDataInst,
|
||||
"NeedsLatentFixup": MetaDataInst,
|
||||
"LatentCallbackTarget": MetaDataInst,
|
||||
"GetOptions": MetaDataInst,
|
||||
"Bitmask": MetaDataInst,
|
||||
"BitmaskEnum": MetaDataInst,
|
||||
// decorator
|
||||
"umeta": dummyDecorator,
|
||||
"attach": dummyDecorator
|
||||
}
|
||||
|
||||
cache.uparam =
|
||||
{
|
||||
// the specifiers
|
||||
"Const": MetaDataInst,
|
||||
"Ref": MetaDataInst,
|
||||
"NotReplicated": MetaDataInst,
|
||||
"DisplayName": MetaDataInst,
|
||||
// decorator
|
||||
"uparam": dummyDecorator,
|
||||
// specifier
|
||||
"ToolTip": MetaDataInst,
|
||||
"ShortTooltip": MetaDataInst,
|
||||
"DocumentationPolicy": MetaDataInst,
|
||||
"AllowAbstract": MetaDataInst,
|
||||
"AllowAnyActor": MetaDataInst,
|
||||
"AllowedClasses": MetaDataInst,
|
||||
"AllowPreserveRatio": MetaDataInst,
|
||||
"AllowPrivateAccess": MetaDataInst,
|
||||
"ArrayClamp": MetaDataInst,
|
||||
"AssetBundles": MetaDataInst,
|
||||
"BlueprintBaseOnly": MetaDataInst,
|
||||
"BlueprintCompilerGeneratedDefaults": MetaDataInst,
|
||||
"ClampMin": MetaDataInst,
|
||||
"ClampMax": MetaDataInst,
|
||||
"ConfigHierarchyEditable": MetaDataInst,
|
||||
"ContentDir": MetaDataInst,
|
||||
"DeprecatedProperty": MetaDataInst,
|
||||
"DeprecationMessage": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
|
||||
"ScriptName": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
|
||||
"DisallowedClasses": MetaDataInst,
|
||||
"DisplayAfter": MetaDataInst,
|
||||
"DisplayPriority": MetaDataInst,
|
||||
"DisplayThumbnail": MetaDataInst,
|
||||
"EditCondition": MetaDataInst,
|
||||
"EditFixedOrder": MetaDataInst,
|
||||
"ExactClass": MetaDataInst,
|
||||
"ExposeFunctionCategories": MetaDataInst,
|
||||
"ExposeOnSpawn": MetaDataInst,
|
||||
"FilePathFilter": MetaDataInst,
|
||||
"RelativeToGameDir": MetaDataInst,
|
||||
"ForceShowEngineContent": MetaDataInst,
|
||||
"ForceShowPluginContent": MetaDataInst,
|
||||
"HideAlphaChannel": MetaDataInst,
|
||||
"HideInDetailPanel": MetaDataInst,
|
||||
"HideViewOptions": MetaDataInst,
|
||||
"IgnoreForMemberInitializationTest": MetaDataInst,
|
||||
"InlineEditConditionToggle": MetaDataInst,
|
||||
"LongPackageName": MetaDataInst,
|
||||
"MakeEditWidget": MetaDataInst,
|
||||
"MakeStructureDefaultValue": MetaDataInst,
|
||||
"MetaClass": MetaDataInst,
|
||||
"MustImplement": MetaDataInst,
|
||||
"Multiple": MetaDataInst,
|
||||
"MultiLine": MetaDataInst,
|
||||
"PasswordField": MetaDataInst,
|
||||
"NoElementDuplicate": MetaDataInst,
|
||||
"NoResetToDefault": MetaDataInst,
|
||||
"NoSpinbox": MetaDataInst,
|
||||
"OnlyPlaceable": MetaDataInst,
|
||||
"RelativePath": MetaDataInst,
|
||||
"RelativeToGameContentDir": MetaDataInst,
|
||||
"ScriptNoExport": MetaDataInst,
|
||||
"ShowOnlyInnerProperties": MetaDataInst,
|
||||
"ShowTreeView": MetaDataInst,
|
||||
"SliderExponent": MetaDataInst,
|
||||
"TitleProperty": MetaDataInst,
|
||||
"UIMin": MetaDataInst,
|
||||
"UIMax": MetaDataInst,
|
||||
"Untracked": MetaDataInst,
|
||||
"DevelopmentOnly": MetaDataInst,
|
||||
"NeedsLatentFixup": MetaDataInst,
|
||||
"LatentCallbackTarget": MetaDataInst,
|
||||
"GetOptions": MetaDataInst,
|
||||
"Bitmask": MetaDataInst,
|
||||
"BitmaskEnum": MetaDataInst,
|
||||
// decorator
|
||||
"umeta": dummyDecorator,
|
||||
}
|
||||
|
||||
cache.edit_on_instance = dummyDecorator;
|
||||
|
||||
cache.no_blueprint = dummyDecorator;
|
||||
|
||||
cache.set_flags = dummyDecorator;
|
||||
|
||||
cache.clear_flags = dummyDecorator;
|
||||
|
||||
cache.FunctionFlags = FunctionFlags;
|
||||
|
||||
cache.ClassFlags = ClassFlags;
|
||||
|
||||
cache.PropertyFlags = PropertyFlags;
|
||||
|
||||
cache.FunctionExportFlags = FunctionExportFlags;
|
||||
|
||||
puerts.toManualReleaseDelegate = (x) => x;
|
||||
puerts.toDelegate = (o,k) => [o, k];
|
||||
|
||||
function mergePrototype(from, to, exclude) {
|
||||
Object.getOwnPropertyNames(from).forEach(name => {
|
||||
if (!(name in exclude)) {
|
||||
Object.defineProperty(
|
||||
to,
|
||||
name,
|
||||
Object.getOwnPropertyDescriptor(from, name) ||
|
||||
Object.create(null)
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
puerts.__mergePrototype = mergePrototype
|
||||
|
||||
function removeListItem(list, item) {
|
||||
var found = false;
|
||||
for (var i = 0; i < list.length; ++i) {
|
||||
if (!found) {
|
||||
found = (list[i] === item);
|
||||
}
|
||||
if (found) {
|
||||
list[i] = list[i + 1]; // array[length + 1] === undefined
|
||||
}
|
||||
}
|
||||
if (found) {
|
||||
list.pop();
|
||||
}
|
||||
}
|
||||
puerts.__removeListItem = removeListItem
|
||||
|
||||
function genListApply(lst) {
|
||||
return function(...args) {
|
||||
const len = lst.length;
|
||||
const list = lst.slice();
|
||||
let ret
|
||||
for (var i = 0; i < len; ++i) {
|
||||
ret = Reflect.apply(list[i], this, args);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
puerts.__genListApply = genListApply
|
||||
|
||||
}(global));
|
||||
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
"use strict";
|
||||
const Wasm3 = {}
|
||||
|
||||
const Wasm_NewMemory = global.__tgjsWasm_NewMemory
|
||||
global.__tgjsWasm_NewMemory = undefined
|
||||
const Wasm_MemoryGrowth = global.__tgjsWasm_MemoryGrowth
|
||||
global.__tgjsWasm_MemoryGrowth = undefined
|
||||
const Wasm_MemoryBuffer = global.__tgjsWasm_MemoryBuffer
|
||||
global.__tgjsWasm_MemoryBuffer = undefined
|
||||
class Wasm3Memory{
|
||||
constructor({initial, maximum, _Seq}){
|
||||
if(_Seq) {
|
||||
this._Seq = _Seq
|
||||
}else{
|
||||
this._Seq = Wasm_NewMemory(initial, maximum)
|
||||
}
|
||||
}
|
||||
grow(n){
|
||||
Wasm_MemoryGrowth(this._Seq, n)
|
||||
}
|
||||
get buffer(){
|
||||
return Wasm_MemoryBuffer(this._Seq)
|
||||
}
|
||||
}
|
||||
Wasm3.Memory = Wasm3Memory;
|
||||
|
||||
const Wasm_TableGrow = global.__tgjsWasm_TableGrow;
|
||||
global.__tgjsWasm_TableGrow = undefined;
|
||||
const Wasm_TableSet = global.__tgjsWasm_TableSet;
|
||||
global.__tgjsWasm_TableSet = undefined;
|
||||
const Wasm_TableLen = global.__tgjsWasm_TableLen;
|
||||
global.__tgjsWasm_TableLen = undefined;
|
||||
|
||||
class Wasm3Table {
|
||||
grow(n) {
|
||||
if (this._runtimeSeq && typeof this._moduleIndex === 'number') {
|
||||
return Wasm_TableGrow(this._runtimeSeq, this._moduleIndex, n);
|
||||
} else {
|
||||
throw new Error("invalid table");
|
||||
}
|
||||
}
|
||||
|
||||
set(index, fn) {
|
||||
if (this._runtimeSeq && typeof this._moduleIndex === 'number') {
|
||||
return Wasm_TableSet(this._runtimeSeq, this._moduleIndex, index, fn);
|
||||
} else {
|
||||
throw new Error("invalid table");
|
||||
}
|
||||
}
|
||||
|
||||
get(index) {
|
||||
throw new Error("not implemented in wasm3 version");
|
||||
}
|
||||
|
||||
get length() {
|
||||
if (this._runtimeSeq && typeof this._moduleIndex === 'number') {
|
||||
return Wasm_TableLen(this._runtimeSeq, this._moduleIndex);
|
||||
} else {
|
||||
throw new Error("invalid table");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Wasm3.Table = Wasm3Table;
|
||||
|
||||
class Wasm3Module{
|
||||
constructor(bufferSource){
|
||||
this._bufferSouce = bufferSource;//bufferSource is arraybuffer or typedarray
|
||||
}
|
||||
}
|
||||
Wasm3.Module = Wasm3Module
|
||||
|
||||
const Wasm_Instance = global.__tgjsWasm_Instance
|
||||
global.__tgjsWasm_Instance = undefined
|
||||
class Wasm3ModuleInstance{
|
||||
constructor(InWasm3Module, importObject){
|
||||
this.exports = {}
|
||||
this._Seq = Wasm_Instance(InWasm3Module._bufferSouce, importObject, this.exports)
|
||||
if (this.exports.__memoryExport) {
|
||||
this.exports[this.exports.__memoryExport] = new Wasm3Memory({_Seq:this._Seq});
|
||||
this.exports.__memoryExport = undefined;
|
||||
}
|
||||
if (this.exports.__tableExport && typeof this.exports.__moduleIndex === 'number') {
|
||||
var tbl = new Wasm3Table();
|
||||
tbl._runtimeSeq = this._Seq;
|
||||
tbl._moduleIndex = this.exports.__moduleIndex;
|
||||
this.exports[this.exports.__tableExport] = tbl;
|
||||
this.exports.__tableExport = undefined;
|
||||
this.exports.__moduleIndex = undefined;
|
||||
} else {
|
||||
for(var k in importObject) {
|
||||
var tbl = importObject[k];
|
||||
if (tbl instanceof Wasm3Table) {
|
||||
tbl._runtimeSeq = this._Seq;
|
||||
tbl._moduleIndex = this.exports.__moduleIndex;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Wasm3.instantiate = function(bufferSource, importObject){
|
||||
return new Promise((resolve, reject)=>{
|
||||
const ins = new Wasm3ModuleInstance(new Wasm3Module(bufferSource), importObject)
|
||||
resolve(ins)
|
||||
})
|
||||
}
|
||||
Wasm3.Instance = Wasm3ModuleInstance;
|
||||
|
||||
const __tgjsWasm_OverrideWebAssembly = global.__tgjsWasm_OverrideWebAssembly
|
||||
global.__tgjsWasm_OverrideWebAssembly = undefined
|
||||
if(__tgjsWasm_OverrideWebAssembly()){
|
||||
global.WebAssembly = Wasm3
|
||||
}
|
||||
|
||||
/*setTimeout(()=>{
|
||||
const ProjDir = require('ue').BlueprintPathsLibrary.ProjectDir();
|
||||
global.WebAssembly.instantiate(require('ue').MHScriptIO.ReadFileAsArrayBuffer(`${ProjDir}/Content/JavaScript/wasm/test.wasm`), {
|
||||
env:
|
||||
{
|
||||
ImportFunction_Int : function(intValue, floatValue, doubleValue){
|
||||
console.log("ffffffffffffffffffffffffffffffffffffffffffff")
|
||||
console.log(typeof intValue, intValue)
|
||||
console.log(typeof floatValue, floatValue)
|
||||
console.log(typeof doubleValue, doubleValue)
|
||||
return 1
|
||||
},
|
||||
atan2 : function(x, y){
|
||||
return Math.atan2(x, y)
|
||||
}
|
||||
}
|
||||
}).then((inst)=>{
|
||||
const e = inst.exports
|
||||
console.log("kkkk", e.TestParam(1, 3, 4))
|
||||
{
|
||||
const a = new Date().getTime()
|
||||
for(let i = 0; i < 1000000; ++i){
|
||||
e.atan2_ue(0.1, 0.1)
|
||||
}
|
||||
const b = new Date().getTime()
|
||||
console.log("ffffffffffffffffffff ue", b - a)
|
||||
}
|
||||
|
||||
{
|
||||
const a = new Date().getTime()
|
||||
for(let i = 0; i < 1000000; ++i){
|
||||
e.atan2_js(0.1, 0.1)
|
||||
}
|
||||
const b = new Date().getTime()
|
||||
console.log("ffffffffffffffffffff ue", b - a)
|
||||
}
|
||||
})
|
||||
}, 1)*/
|
||||
}(global));
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
var global = global || (function () { return this; }());
|
||||
(function (global) {
|
||||
const WebSocketPP = global.WebSocketPP;
|
||||
//global.WebSocketPP = undefined;
|
||||
|
||||
class EventTarget {
|
||||
constructor() {
|
||||
this.listeners = {};
|
||||
}
|
||||
|
||||
addEventListener(type, callback) {
|
||||
if (!(type in this.listeners)) {
|
||||
this.listeners[type] = [];
|
||||
}
|
||||
this.listeners[type].push(callback);
|
||||
}
|
||||
|
||||
removeEventListener(type, callback) {
|
||||
if (!(type in this.listeners)) {
|
||||
return;
|
||||
}
|
||||
const stack = this.listeners[type];
|
||||
for (let i = 0; i < stack.length; i++) {
|
||||
if (stack[i] === callback) {
|
||||
stack.splice(i, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dispatchEvent(ev) {
|
||||
if (!(ev.type in this.listeners)) {
|
||||
return true;
|
||||
}
|
||||
const stack = this.listeners[ev.type].slice();
|
||||
|
||||
for (let i = 0; i < stack.length; i++) {
|
||||
stack[i].call(this, ev);
|
||||
}
|
||||
return !ev.defaultPrevented;
|
||||
}
|
||||
}
|
||||
|
||||
const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
|
||||
|
||||
const poll_ws_objects = [];
|
||||
|
||||
class WebSocket extends EventTarget {
|
||||
constructor(url, protocols) {
|
||||
super();
|
||||
if (protocols) throw new Error('do not support protocols argument');
|
||||
this._raw = new WebSocketPP(url);
|
||||
this._url = url;
|
||||
// !!do not raise exception in handles.
|
||||
this._raw.setHandles(
|
||||
()=> {
|
||||
this._readyState = WebSocket.OPEN;
|
||||
this._addPendingEvent({type:'open'});
|
||||
},
|
||||
(data) => {
|
||||
this._addPendingEvent({type:'message', data:data, origin:this._url});
|
||||
},
|
||||
(code, reason) => {
|
||||
this._cleanup();
|
||||
this._addPendingEvent({type:'close', code:code, reason: reason});
|
||||
},
|
||||
() => {
|
||||
this._addPendingEvent({type:'error'});
|
||||
this._cleanup();
|
||||
this._addPendingEvent({type:'close', code:1006, reason: ""});
|
||||
});
|
||||
|
||||
this._readyState = WebSocket.CONNECTING;
|
||||
this._tid = setInterval(() => this._poll(), 1);
|
||||
this._pendingEvents = [];
|
||||
}
|
||||
|
||||
get url() {
|
||||
return this._url;
|
||||
}
|
||||
|
||||
get readyState() {
|
||||
return this._readyState;
|
||||
}
|
||||
|
||||
send(data) {
|
||||
if (this._readyState !== WebSocket.OPEN) {
|
||||
throw new Error(`WebSocket is not open: readyState ${this._readyState} (${readyStates[this._readyState]})`);
|
||||
}
|
||||
this._raw.send(data);
|
||||
}
|
||||
|
||||
_cleanup() {
|
||||
this._readyState = WebSocket.CLOSING;
|
||||
}
|
||||
|
||||
_addPendingEvent(ev) {
|
||||
this._pendingEvents.push(ev);
|
||||
}
|
||||
|
||||
_poll() {
|
||||
if (this._pendingEvents.length === 0 && this._readyState != WebSocket.CLOSING) {
|
||||
this._raw.poll();
|
||||
}
|
||||
const ev = this._pendingEvents.shift();
|
||||
if (ev) this.dispatchEvent(ev);
|
||||
if (this._pendingEvents.length === 0 && this._readyState == WebSocket.CLOSING) {
|
||||
this._raw = undefined;
|
||||
clearInterval(this._tid);
|
||||
this._readyState = WebSocket.CLOSED;
|
||||
}
|
||||
}
|
||||
|
||||
close(code, data) {
|
||||
try {
|
||||
this._raw.close(code, data);
|
||||
} catch(e) {}
|
||||
this._cleanup();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
for (let i = 0; i < readyStates.length; i++) {
|
||||
Object.defineProperty(WebSocket, readyStates[i], {
|
||||
enumerable: true,
|
||||
value: i
|
||||
});
|
||||
|
||||
Object.defineProperty(WebSocket.prototype, readyStates[i], {
|
||||
enumerable: true,
|
||||
value: i
|
||||
});
|
||||
}
|
||||
|
||||
global.WebSocket = WebSocket;
|
||||
|
||||
}(global));
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = require('./react-umg.js');
|
||||
|
||||
let components = require('components.js');
|
||||
|
||||
for(let k in components) {
|
||||
module.exports[k] = components[k];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
Copyright (c) 2011, Daniel Guerrero
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL DANIEL GUERRERO BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Uses the new array typed in javascript to binary base64 encode/decode
|
||||
* at the moment just decodes a binary base64 encoded
|
||||
* into either an ArrayBuffer (decodeArrayBuffer)
|
||||
* or into an Uint8Array (decode)
|
||||
*
|
||||
* References:
|
||||
* https://developer.mozilla.org/en/JavaScript_typed_arrays/ArrayBuffer
|
||||
* https://developer.mozilla.org/en/JavaScript_typed_arrays/Uint8Array
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
|
||||
|
||||
/* will return a Uint8Array type */
|
||||
decodeArrayBuffer: function(input) {
|
||||
var bytes = (input.length/4) * 3;
|
||||
var ab = new ArrayBuffer(bytes);
|
||||
this.decode(input, ab);
|
||||
|
||||
return ab;
|
||||
},
|
||||
|
||||
removePaddingChars: function(input){
|
||||
var lkey = this._keyStr.indexOf(input.charAt(input.length - 1));
|
||||
if(lkey == 64){
|
||||
return input.substring(0,input.length - 1);
|
||||
}
|
||||
return input;
|
||||
},
|
||||
|
||||
decode: function (input, arrayBuffer) {
|
||||
//get last chars to see if are valid
|
||||
input = this.removePaddingChars(input);
|
||||
input = this.removePaddingChars(input);
|
||||
|
||||
var bytes = parseInt((input.length / 4) * 3, 10);
|
||||
|
||||
var uarray;
|
||||
var chr1, chr2, chr3;
|
||||
var enc1, enc2, enc3, enc4;
|
||||
var i = 0;
|
||||
var j = 0;
|
||||
|
||||
if (arrayBuffer)
|
||||
uarray = new Uint8Array(arrayBuffer);
|
||||
else
|
||||
uarray = new Uint8Array(bytes);
|
||||
|
||||
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
|
||||
|
||||
for (i=0; i<bytes; i+=3) {
|
||||
//get the 3 octects in 4 ascii chars
|
||||
enc1 = this._keyStr.indexOf(input.charAt(j++));
|
||||
enc2 = this._keyStr.indexOf(input.charAt(j++));
|
||||
enc3 = this._keyStr.indexOf(input.charAt(j++));
|
||||
enc4 = this._keyStr.indexOf(input.charAt(j++));
|
||||
|
||||
chr1 = (enc1 << 2) | (enc2 >> 4);
|
||||
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
|
||||
chr3 = ((enc3 & 3) << 6) | enc4;
|
||||
|
||||
uarray[i] = chr1;
|
||||
if (enc3 != 64) uarray[i+1] = chr2;
|
||||
if (enc4 != 64) uarray[i+2] = chr3;
|
||||
}
|
||||
|
||||
return uarray;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Puerts available.
|
||||
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
|
||||
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
|
||||
*/
|
||||
|
||||
let base64binary = require("thirdparty/base64-binary.js");
|
||||
|
||||
exports.loadBinarySync = function(name) {
|
||||
let ret = puerts.sendRequestSync('loadBinary', name);
|
||||
return base64binary.decode(ret);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"Exports":{
|
||||
"DistanceCheckSubsystem_IsActorIn":{
|
||||
"ParamList":[
|
||||
{
|
||||
"IsUObject":true,
|
||||
"Type":"Pointer"
|
||||
},
|
||||
{
|
||||
"ClassName":"FVector",
|
||||
"Type":"Struct"
|
||||
},
|
||||
{
|
||||
"Type":"Float"
|
||||
},
|
||||
{
|
||||
"Type":"Float"
|
||||
}
|
||||
],
|
||||
"Return":{
|
||||
"Type":"Bool"
|
||||
}
|
||||
},
|
||||
"Test_DistanceSqr":{
|
||||
"ParamList":[
|
||||
{
|
||||
"ClassName":"FVector",
|
||||
"Type":"Struct"
|
||||
}
|
||||
],
|
||||
"Return":{
|
||||
"Type":"Float"
|
||||
}
|
||||
},
|
||||
"Test_Fib":{
|
||||
"ParamList":[
|
||||
{
|
||||
"Type":"Int"
|
||||
}
|
||||
],
|
||||
"Return":{
|
||||
"Type":"Int"
|
||||
}
|
||||
},
|
||||
"Test_GetActorLocation":{
|
||||
"ParamList":[
|
||||
{
|
||||
"IsUObject":true,
|
||||
"Type":"Pointer"
|
||||
}
|
||||
],
|
||||
"Return":{
|
||||
"ClassName":"FVector",
|
||||
"Type":"Struct"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"WasmMain" : {
|
||||
"LinkCategory" : 0,
|
||||
"GlobalNameInTs" : "WasmMain"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user