@minecraft/creator-tools
Version:
Minecraft Creator Tools command line and libraries.
1,149 lines • 64 kB
JavaScript
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var _Carto_data;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SidePaneMinWidth = exports.SidePaneMaxWidth = exports.CartoTargetStrings = exports.CartoMinecraftErrorStatus = exports.CartoMinecraftState = void 0;
const ICartoData_1 = require("./ICartoData");
const Project_1 = require("./Project");
const ste_events_1 = require("ste-events");
const Status_1 = require("./Status");
const StorageUtilities_1 = require("../storage/StorageUtilities");
const Utilities_1 = require("../core/Utilities");
const GitHubManager_1 = require("../github/GitHubManager");
const axios_1 = require("axios");
const Log_1 = require("../core/Log");
const AppServiceProxy_1 = require("../core/AppServiceProxy");
const CommandRunner_1 = require("./CommandRunner");
const CartoApp_1 = require("./CartoApp");
const WorldLevelDat_1 = require("../minecraft/WorldLevelDat");
const IWorldSettings_1 = require("../minecraft/IWorldSettings");
const Package_1 = require("./Package");
const CommandRegistry_1 = require("./CommandRegistry");
const ZipStorage_1 = require("../storage/ZipStorage");
const IProjectItemData_1 = require("./IProjectItemData");
const DeploymentStorageMinecraft_1 = require("./DeploymentStorageMinecraft");
const MinecraftUtilities_1 = require("../minecraft/MinecraftUtilities");
const IGalleryItem_1 = require("./IGalleryItem");
const ProjectItemRelations_1 = require("./ProjectItemRelations");
var CartoMinecraftState;
(function (CartoMinecraftState) {
CartoMinecraftState[CartoMinecraftState["none"] = 0] = "none";
CartoMinecraftState[CartoMinecraftState["initializing"] = 1] = "initializing";
// for remote server, this is authenticating
// for web sockets, this is opening up the web socket to receive connections from a client
CartoMinecraftState[CartoMinecraftState["initialized"] = 2] = "initialized";
CartoMinecraftState[CartoMinecraftState["preparing"] = 3] = "preparing";
CartoMinecraftState[CartoMinecraftState["prepared"] = 4] = "prepared";
CartoMinecraftState[CartoMinecraftState["starting"] = 5] = "starting";
// for remote server, this is creating a session on a socket
// for web sockets, note you have to wait for external connections to come in.
CartoMinecraftState[CartoMinecraftState["started"] = 6] = "started";
// for remote server, the session is ready and initial status has been established
// for web sockets, an external client has connected in
CartoMinecraftState[CartoMinecraftState["stopping"] = 7] = "stopping";
CartoMinecraftState[CartoMinecraftState["stopped"] = 8] = "stopped";
CartoMinecraftState[CartoMinecraftState["error"] = 9] = "error";
CartoMinecraftState[CartoMinecraftState["newMinecraft"] = 10] = "newMinecraft";
CartoMinecraftState[CartoMinecraftState["disconnected"] = 11] = "disconnected";
})(CartoMinecraftState = exports.CartoMinecraftState || (exports.CartoMinecraftState = {}));
var CartoMinecraftErrorStatus;
(function (CartoMinecraftErrorStatus) {
CartoMinecraftErrorStatus[CartoMinecraftErrorStatus["none"] = 0] = "none";
CartoMinecraftErrorStatus[CartoMinecraftErrorStatus["actionInProgress"] = 1] = "actionInProgress";
CartoMinecraftErrorStatus[CartoMinecraftErrorStatus["serverUnavailable"] = 2] = "serverUnavailable";
CartoMinecraftErrorStatus[CartoMinecraftErrorStatus["serverError"] = 3] = "serverError";
CartoMinecraftErrorStatus[CartoMinecraftErrorStatus["loginFailed"] = 4] = "loginFailed";
CartoMinecraftErrorStatus[CartoMinecraftErrorStatus["generalError"] = 5] = "generalError";
CartoMinecraftErrorStatus[CartoMinecraftErrorStatus["configuration"] = 6] = "configuration";
})(CartoMinecraftErrorStatus = exports.CartoMinecraftErrorStatus || (exports.CartoMinecraftErrorStatus = {}));
exports.CartoTargetStrings = [
"Latest Minecraft Bedrock",
"Latest Minecraft Bedrock preview",
"Latest Minecraft Education",
"Latest Minecraft Education preview",
];
exports.SidePaneMaxWidth = 880;
exports.SidePaneMinWidth = 280;
class Carto {
get isLoaded() {
return this._isLoaded;
}
get collapsedTypes() {
if (!__classPrivateFieldGet(this, _Carto_data, "f").collapsedTypes) {
__classPrivateFieldGet(this, _Carto_data, "f").collapsedTypes = [];
}
return __classPrivateFieldGet(this, _Carto_data, "f").collapsedTypes;
}
set collapsedTypes(newCollapsedTypes) {
__classPrivateFieldGet(this, _Carto_data, "f").collapsedTypes = newCollapsedTypes;
}
get worldSettings() {
return __classPrivateFieldGet(this, _Carto_data, "f").worldSettings;
}
get editorWorldSettings() {
return __classPrivateFieldGet(this, _Carto_data, "f").editorWorldSettings;
}
get activeMinecraftState() {
if (this.activeMinecraft === undefined) {
return CartoMinecraftState.none;
}
return this.activeMinecraft.state;
}
get onMinecraftStateChanged() {
return this._onMinecraftStateChanged.asEvent();
}
get onDeploymentStorageChanged() {
return this._onDeploymentStorageChanged.asEvent();
}
get formatBeforeSave() {
if (__classPrivateFieldGet(this, _Carto_data, "f").formatBeforeSave === undefined) {
return true;
}
return __classPrivateFieldGet(this, _Carto_data, "f").formatBeforeSave;
}
set formatBeforeSave(newValue) {
__classPrivateFieldGet(this, _Carto_data, "f").formatBeforeSave = newValue;
}
get conversionJarPath() {
return __classPrivateFieldGet(this, _Carto_data, "f").conversionJarPath;
}
set conversionJarPath(newValue) {
__classPrivateFieldGet(this, _Carto_data, "f").conversionJarPath = newValue;
}
get preferredTextSize() {
if (__classPrivateFieldGet(this, _Carto_data, "f").preferredTextSize === undefined) {
return 16;
}
return __classPrivateFieldGet(this, _Carto_data, "f").preferredTextSize;
}
set preferredTextSize(newValue) {
__classPrivateFieldGet(this, _Carto_data, "f").preferredTextSize = newValue;
}
get itemSidePaneWidth() {
if (__classPrivateFieldGet(this, _Carto_data, "f").itemSidePaneWidth === undefined) {
return 300;
}
if (__classPrivateFieldGet(this, _Carto_data, "f").itemSidePaneWidth < exports.SidePaneMinWidth) {
return exports.SidePaneMinWidth;
}
if (__classPrivateFieldGet(this, _Carto_data, "f").itemSidePaneWidth > exports.SidePaneMaxWidth) {
return exports.SidePaneMaxWidth;
}
return __classPrivateFieldGet(this, _Carto_data, "f").itemSidePaneWidth;
}
set itemSidePaneWidth(newValue) {
__classPrivateFieldGet(this, _Carto_data, "f").itemSidePaneWidth = newValue;
}
get preferredSuite() {
return __classPrivateFieldGet(this, _Carto_data, "f").preferredSuite;
}
set preferredSuite(newValue) {
__classPrivateFieldGet(this, _Carto_data, "f").preferredSuite = newValue;
}
get track() {
return __classPrivateFieldGet(this, _Carto_data, "f").track;
}
set track(newTrack) {
if (newTrack !== __classPrivateFieldGet(this, _Carto_data, "f").track) {
__classPrivateFieldGet(this, _Carto_data, "f").track = newTrack;
this._onPropertyChanged.dispatch(this, "track");
}
}
get effectiveTrack() {
if (__classPrivateFieldGet(this, _Carto_data, "f").track !== undefined) {
return __classPrivateFieldGet(this, _Carto_data, "f").track;
}
return ICartoData_1.MinecraftTrack.main;
}
get useEditor() {
return __classPrivateFieldGet(this, _Carto_data, "f").useEditor;
}
set useEditor(newUseEditor) {
if (newUseEditor !== __classPrivateFieldGet(this, _Carto_data, "f").useEditor) {
__classPrivateFieldGet(this, _Carto_data, "f").useEditor = newUseEditor;
}
}
get windowX() {
if (__classPrivateFieldGet(this, _Carto_data, "f").windowX === undefined) {
return 0;
}
return __classPrivateFieldGet(this, _Carto_data, "f").windowX;
}
set windowX(newVal) {
__classPrivateFieldGet(this, _Carto_data, "f").windowX = newVal;
}
get windowY() {
if (__classPrivateFieldGet(this, _Carto_data, "f").windowY === undefined) {
return 0;
}
return __classPrivateFieldGet(this, _Carto_data, "f").windowY;
}
set windowY(newVal) {
__classPrivateFieldGet(this, _Carto_data, "f").windowY = newVal;
}
get windowWidth() {
if (__classPrivateFieldGet(this, _Carto_data, "f").windowWidth === undefined) {
return 1200;
}
return __classPrivateFieldGet(this, _Carto_data, "f").windowWidth;
}
set windowWidth(newVal) {
__classPrivateFieldGet(this, _Carto_data, "f").windowWidth = newVal;
}
get windowHeight() {
if (__classPrivateFieldGet(this, _Carto_data, "f").windowHeight === undefined) {
return 900;
}
return __classPrivateFieldGet(this, _Carto_data, "f").windowHeight;
}
set windowHeight(newVal) {
__classPrivateFieldGet(this, _Carto_data, "f").windowHeight = newVal;
}
get windowSlot() {
if (__classPrivateFieldGet(this, _Carto_data, "f").windowSlot === undefined) {
return 0;
}
return __classPrivateFieldGet(this, _Carto_data, "f").windowSlot;
}
set windowSlot(newVal) {
__classPrivateFieldGet(this, _Carto_data, "f").windowSlot = newVal;
}
get creator() {
return __classPrivateFieldGet(this, _Carto_data, "f").creator;
}
set creator(newCreator) {
if (__classPrivateFieldGet(this, _Carto_data, "f").creator !== newCreator) {
__classPrivateFieldGet(this, _Carto_data, "f").creator = newCreator;
this._onPropertyChanged.dispatch(this, "creator");
}
}
get windowState() {
if (__classPrivateFieldGet(this, _Carto_data, "f").windowState === undefined) {
return ICartoData_1.WindowState.regular;
}
return __classPrivateFieldGet(this, _Carto_data, "f").windowState;
}
set windowState(newVal) {
__classPrivateFieldGet(this, _Carto_data, "f").windowState = newVal;
}
get lastActiveMinecraftFlavor() {
return __classPrivateFieldGet(this, _Carto_data, "f").lastActiveMinecraftFlavor;
}
set lastActiveMinecraftFlavor(lastActiveMinecraftFlavor) {
if (lastActiveMinecraftFlavor !== __classPrivateFieldGet(this, _Carto_data, "f").lastActiveMinecraftFlavor) {
__classPrivateFieldGet(this, _Carto_data, "f").lastActiveMinecraftFlavor = lastActiveMinecraftFlavor;
}
}
get remoteServerUrl() {
if (__classPrivateFieldGet(this, _Carto_data, "f").remoteServerUrl === undefined && CartoApp_1.default.baseUrl) {
return Utilities_1.default.getBaseUrl(CartoApp_1.default.baseUrl);
}
return __classPrivateFieldGet(this, _Carto_data, "f").remoteServerUrl;
}
get fullRemoteServerUrl() {
if (!this.remoteServerUrl) {
return undefined;
}
let url = this.remoteServerUrl.toLowerCase();
if (!url.startsWith("http") && url.indexOf("//") < 0) {
if (url.indexOf("localhost") >= 0) {
url = "http://" + url;
}
else {
url = "https://" + url;
}
}
url = Utilities_1.default.ensureEndsWithSlash(url);
return url;
}
set remoteServerUrl(newPath) {
if (newPath !== __classPrivateFieldGet(this, _Carto_data, "f").remoteServerUrl) {
__classPrivateFieldGet(this, _Carto_data, "f").remoteServerUrl = newPath;
}
}
get iAgreeToTheMinecraftEndUserLicenseAgreementAndPrivacyPolicyAtMinecraftDotNetSlashEula() {
return __classPrivateFieldGet(this, _Carto_data, "f").iAgreeToTheMinecraftEndUserLicenseAgreementAndPrivacyPolicyAtMinecraftDotNetSlashEula;
}
set iAgreeToTheMinecraftEndUserLicenseAgreementAndPrivacyPolicyAtMinecraftDotNetSlashEula(newPort) {
__classPrivateFieldGet(this, _Carto_data, "f").iAgreeToTheMinecraftEndUserLicenseAgreementAndPrivacyPolicyAtMinecraftDotNetSlashEula = newPort;
}
get dedicatedServerSlotCount() {
return __classPrivateFieldGet(this, _Carto_data, "f").dedicatedServerSlotCount;
}
set dedicatedServerSlotCount(newPort) {
__classPrivateFieldGet(this, _Carto_data, "f").dedicatedServerSlotCount = newPort;
}
get dedicatedServerMode() {
if (__classPrivateFieldGet(this, _Carto_data, "f").dedicatedServerMode === undefined) {
return ICartoData_1.DedicatedServerMode.auto;
}
return __classPrivateFieldGet(this, _Carto_data, "f").dedicatedServerMode;
}
set dedicatedServerMode(newMode) {
__classPrivateFieldGet(this, _Carto_data, "f").dedicatedServerMode = newMode;
}
get dedicatedServerPath() {
return __classPrivateFieldGet(this, _Carto_data, "f").dedicatedServerPath;
}
set minecraftGameMode(newMode) {
__classPrivateFieldGet(this, _Carto_data, "f").webSocketMode = newMode;
}
get minecraftGameMode() {
return __classPrivateFieldGet(this, _Carto_data, "f").webSocketMode;
}
set dedicatedServerPath(newPath) {
__classPrivateFieldGet(this, _Carto_data, "f").dedicatedServerPath = newPath;
}
get remoteServerPort() {
if (__classPrivateFieldGet(this, _Carto_data, "f").remoteServerPort === undefined) {
return 0;
}
return __classPrivateFieldGet(this, _Carto_data, "f").remoteServerPort;
}
set remoteServerPort(newPort) {
__classPrivateFieldGet(this, _Carto_data, "f").remoteServerPort = newPort;
}
get remoteServerAccessLevel() {
return __classPrivateFieldGet(this, _Carto_data, "f").remoteServerAccessLevel;
}
set remoteServerAccessLevel(newAccessLevel) {
__classPrivateFieldGet(this, _Carto_data, "f").remoteServerAccessLevel = newAccessLevel;
}
get remoteServerPasscode() {
return __classPrivateFieldGet(this, _Carto_data, "f").remoteServerPasscode;
}
set remoteServerPasscode(newPath) {
__classPrivateFieldGet(this, _Carto_data, "f").remoteServerPasscode = newPath;
}
get remoteServerAuthToken() {
return __classPrivateFieldGet(this, _Carto_data, "f").remoteServerAuthToken;
}
set remoteServerAuthToken(newPath) {
__classPrivateFieldGet(this, _Carto_data, "f").remoteServerAuthToken = newPath;
}
get editorViewMode() {
if (__classPrivateFieldGet(this, _Carto_data, "f").editorViewMode === undefined) {
return ICartoData_1.CartoEditorViewMode.itemsOnLeft;
}
return __classPrivateFieldGet(this, _Carto_data, "f").editorViewMode;
}
set editorViewMode(newViewMode) {
__classPrivateFieldGet(this, _Carto_data, "f").editorViewMode = newViewMode;
}
get gallery() {
return this._gallery;
}
get galleryLoaded() {
return this._galleryLoaded;
}
get userGitHub() {
if (this._userGitHub === undefined) {
this._userGitHub = new GitHubManager_1.default(this.prefsStorage.rootFolder.ensureFile("github.json"));
}
return this._userGitHub;
}
get anonGitHub() {
if (this._anonGitHub === undefined) {
this._anonGitHub = new GitHubManager_1.default();
}
return this._anonGitHub;
}
get onLoaded() {
return this._onLoaded.asEvent();
}
get onGalleryLoaded() {
return this._onGalleryLoaded.asEvent();
}
get onPropertyChanged() {
return this._onPropertyChanged.asEvent();
}
get onStatusAdded() {
return this._onStatusAdded.asEvent();
}
get onOperationCompleted() {
return this._onOperationCompleted.asEvent();
}
get successfullyConnectedWebSocketToMinecraft() {
if (__classPrivateFieldGet(this, _Carto_data, "f").successfullyConnectedWebSocketToMinecraft === undefined) {
return false;
}
return __classPrivateFieldGet(this, _Carto_data, "f").successfullyConnectedWebSocketToMinecraft;
}
set successfullyConnectedWebSocketToMinecraft(newValue) {
__classPrivateFieldGet(this, _Carto_data, "f").successfullyConnectedWebSocketToMinecraft = newValue;
}
get successfullyStartedMinecraftServer() {
if (__classPrivateFieldGet(this, _Carto_data, "f").successfullyStartedMinecraftServer === undefined) {
return false;
}
return __classPrivateFieldGet(this, _Carto_data, "f").successfullyStartedMinecraftServer;
}
set successfullyStartedMinecraftServer(newValue) {
__classPrivateFieldGet(this, _Carto_data, "f").successfullyStartedMinecraftServer = newValue;
}
get successfullyConnectedToRemoteMinecraft() {
if (__classPrivateFieldGet(this, _Carto_data, "f").successfullyConnectedToRemoteMinecraft === undefined) {
return false;
}
return __classPrivateFieldGet(this, _Carto_data, "f").successfullyConnectedToRemoteMinecraft;
}
set successfullyConnectedToRemoteMinecraft(newValue) {
__classPrivateFieldGet(this, _Carto_data, "f").successfullyConnectedToRemoteMinecraft = newValue;
}
get defaultMinecraftFlavor() {
if (__classPrivateFieldGet(this, _Carto_data, "f").lastActiveMinecraftFlavor === undefined) {
if (CartoApp_1.default.isAppServiceWeb) {
return ICartoData_1.MinecraftFlavor.processHostedProxy;
}
else {
return ICartoData_1.MinecraftFlavor.remote;
}
}
return __classPrivateFieldGet(this, _Carto_data, "f").lastActiveMinecraftFlavor;
}
subscribeStatusAddedAsync(fn) {
this._onStatusAddedAsync.push(fn);
}
unsubscribeStatusAddedAsync(fn) {
let newStatusAddedArr = [];
for (let i = 0; i < this._onStatusAddedAsync.length; i++) {
if (this._onStatusAddedAsync[i] !== fn) {
newStatusAddedArr.push(this._onStatusAddedAsync[i]);
}
}
this._onStatusAddedAsync = newStatusAddedArr;
}
setMinecraftFlavor(newValue) {
this.ensureMinecraft(newValue);
}
get autoStartMinecraft() {
if (__classPrivateFieldGet(this, _Carto_data, "f").autoStartMinecraft === undefined) {
return true;
}
return __classPrivateFieldGet(this, _Carto_data, "f").autoStartMinecraft;
}
set autoStartMinecraft(newValue) {
__classPrivateFieldGet(this, _Carto_data, "f").autoStartMinecraft = newValue;
}
get file() {
return this.prefsStorage.rootFolder.ensureFile("mctools.json");
}
get prefsProjectsFolder() {
return this.prefsStorage.rootFolder.ensureFolder("projects");
}
get deployBehaviorPacksFolder() {
return this._deployBehaviorPacksFolder;
}
get deployResourcePacksFolder() {
return this._deployResourcePacksFolder;
}
constructor(settingsStorage, projectsStorage, deploymentsStorage, previewDeploymentsStorage, worldStorage, packStorage, workingStorage, contentRoot) {
this.contentRoot = "";
this._pendingPackLoadRequests = [];
this._arePacksLoading = false;
_Carto_data.set(this, void 0);
this.mcLogs = {};
this._galleryLoaded = false;
this.isDeployingToComMojang = false;
this.hasAttemptedPersistentBrowserStorageSwitch = false;
this._onDeploymentStorageChanged = new ste_events_1.EventDispatcher();
this._onMinecraftStateChanged = new ste_events_1.EventDispatcher();
this._onMinecraftRefreshed = new ste_events_1.EventDispatcher();
this._onPropertyChanged = new ste_events_1.EventDispatcher();
this._onLoaded = new ste_events_1.EventDispatcher();
this._onStatusAdded = new ste_events_1.EventDispatcher();
this._onOperationCompleted = new ste_events_1.EventDispatcher();
this._onStatusAddedAsync = [];
this._onGalleryLoaded = new ste_events_1.EventDispatcher();
this.prefsStorage = settingsStorage;
this.projectsStorage = projectsStorage;
this.deploymentStorage = deploymentsStorage;
this.previewDeploymentStorage = previewDeploymentsStorage;
this.packStorage = packStorage;
this.worldStorage = worldStorage;
this.workingStorage = workingStorage;
this._deployBehaviorPacksFolder = null;
this._deployResourcePacksFolder = null;
if (contentRoot) {
this.contentRoot = contentRoot;
}
this._handleMessageFromAppService = this._handleMessageFromAppService.bind(this);
this._bubbleMinecraftStateChanged = this._bubbleMinecraftStateChanged.bind(this);
this._bubbleMinecraftRefreshed = this._bubbleMinecraftRefreshed.bind(this);
AppServiceProxy_1.default.onMessage.subscribe(this._handleMessageFromAppService);
__classPrivateFieldSet(this, _Carto_data, {
successfullyConnectedWebSocketToMinecraft: false,
successfullyStartedMinecraftServer: false,
successfullyConnectedToRemoteMinecraft: false,
autoStartMinecraft: true,
showScreenOnConnect: true,
customTools: [],
}, "f");
// in the case of a Minecraft Http Server self-hosted web page, assume all we want to do is connect back to our server
if (CartoApp_1.default.baseUrl) {
this.setMinecraftFlavor(ICartoData_1.MinecraftFlavor.remote);
this.successfullyConnectedWebSocketToMinecraft = true;
}
this._isLoaded = false;
this.projects = [];
this.status = [];
this.activeOperations = [];
this.updateDeploymentStorage(deploymentsStorage);
}
updateDeploymentStorage(deploymentStorage) {
this.deploymentStorage = deploymentStorage;
if (this.deploymentStorage != null) {
this._deployBehaviorPacksFolder = this.deploymentStorage.rootFolder.ensureFolder("development_behavior_packs");
this._deployResourcePacksFolder = this.deploymentStorage.rootFolder.ensureFolder("development_resource_packs");
}
else {
this._deployBehaviorPacksFolder = null;
this._deployResourcePacksFolder = null;
}
this._onDeploymentStorageChanged.dispatch(this, deploymentStorage);
}
initializeWorldSettings() {
if (__classPrivateFieldGet(this, _Carto_data, "f").worldSettings === undefined) {
__classPrivateFieldGet(this, _Carto_data, "f").worldSettings = {
gameType: WorldLevelDat_1.GameType.creative,
generator: WorldLevelDat_1.Generator.infinite,
randomSeed: "2000",
backupType: IWorldSettings_1.BackupType.every5Minutes,
useCustomSettings: false,
isEditor: false,
packageReferences: [],
};
this.ensureDefaultWorldName();
}
}
ensureDefaultWorldName() {
if (this.worldSettings && this.worldSettings.name === undefined) {
this.worldSettings.name = "world " + Utilities_1.default.getDateStr(new Date());
}
}
initializeEditorWorldSettings() {
if (__classPrivateFieldGet(this, _Carto_data, "f").editorWorldSettings === undefined) {
__classPrivateFieldGet(this, _Carto_data, "f").editorWorldSettings = {
gameType: WorldLevelDat_1.GameType.creative,
generator: WorldLevelDat_1.Generator.infinite,
backupType: IWorldSettings_1.BackupType.every5Minutes,
useCustomSettings: false,
isEditor: true,
packageReferences: [],
};
this.ensureDefaultEditorWorldName();
}
}
ensureDefaultEditorWorldName() {
if (this.editorWorldSettings && this.editorWorldSettings.name === undefined) {
this.editorWorldSettings.name = "editor project " + Utilities_1.default.getDateStr(new Date());
}
}
getCustomTool(index) {
if (__classPrivateFieldGet(this, _Carto_data, "f").customTools === undefined) {
__classPrivateFieldGet(this, _Carto_data, "f").customTools = [];
}
while (__classPrivateFieldGet(this, _Carto_data, "f").customTools.length <= index) {
__classPrivateFieldGet(this, _Carto_data, "f").customTools.push({
name: "",
type: 0,
text: undefined,
lastRunResult: undefined,
});
}
return __classPrivateFieldGet(this, _Carto_data, "f").customTools[index];
}
get defaultFunction() {
if (__classPrivateFieldGet(this, _Carto_data, "f") === undefined || __classPrivateFieldGet(this, _Carto_data, "f").defaultFunction === undefined) {
return "";
}
return __classPrivateFieldGet(this, _Carto_data, "f").defaultFunction;
}
set defaultFunction(newFunction) {
if (__classPrivateFieldGet(this, _Carto_data, "f") === undefined) {
return;
}
__classPrivateFieldGet(this, _Carto_data, "f").defaultFunction = Utilities_1.default.makeSafeForJson(newFunction);
}
async runCommand(command, project) {
return await CommandRegistry_1.default.main.runCommand({
carto: this,
project: project,
minecraft: this.activeMinecraft,
host: CartoApp_1.default.hostManager,
}, command);
}
async runMinecraftCommand(command) {
if (this.activeMinecraft === undefined) {
throw new Error("No minecraft active.");
}
const result = await this.activeMinecraft.runCommand(command);
return result;
}
async loadPacks() {
if (!this.packStorage) {
throw new Error("Could not find pack storage");
}
if (this._arePacksLoading) {
const pendingLoad = this._pendingPackLoadRequests;
const prom = (resolve, reject) => {
pendingLoad.push(resolve);
};
await new Promise(prom);
}
else {
this._arePacksLoading = true;
this.packs = [];
// console.log("Loading packs from '" + this.packStorage.rootFolder.fullPath + "'");
await this.loadPacksFromFolder(this.packStorage.rootFolder);
this._arePacksLoading = false;
const pendingLoad = this._pendingPackLoadRequests;
this._pendingPackLoadRequests = [];
for (const prom of pendingLoad) {
prom(undefined);
}
}
}
ensureAllTypesCollapsedExcept(itemType) {
const newCollapsedTypes = [];
for (let i = 0; i < IProjectItemData_1.MaxItemTypes; i++) {
if (i !== itemType) {
newCollapsedTypes.push(i);
}
}
this.collapsedTypes = newCollapsedTypes;
}
ensureTypeIsCollapsed(itemType) {
for (const itemTypeCollapsed of this.collapsedTypes) {
if (itemTypeCollapsed === itemType) {
return;
}
}
this.collapsedTypes.push(itemType);
}
ensureTypeIsNotCollapsed(itemType) {
const newCollapsedTypes = [];
for (const itemTypeCollapsed of this.collapsedTypes) {
if (itemTypeCollapsed !== itemType) {
newCollapsedTypes.push(itemTypeCollapsed);
}
}
__classPrivateFieldGet(this, _Carto_data, "f").collapsedTypes = newCollapsedTypes;
}
async loadPacksFromFolder(folder) {
await folder.load();
for (let fileName in folder.files) {
const file = folder.files[fileName];
if (file && StorageUtilities_1.default.isContainerFile(file.storageRelativePath)) {
await this.ensurePackForFile(file);
}
}
}
getPackByName(packName, isWorldFocused) {
if (!this.packs) {
Log_1.default.unexpectedUndefined("GPN");
return;
}
for (let i = 0; i < this.packs.length; i++) {
if (this.packs[i].matches(packName, isWorldFocused)) {
return this.packs[i];
}
}
return undefined;
}
getPackageByNameAndHash(packName, hash) {
if (!this.packs) {
Log_1.default.unexpectedUndefined("GPNH");
return;
}
for (let i = 0; i < this.packs.length; i++) {
if (this.packs[i].matches(packName, false) && (hash === undefined || hash === this.packs[i].data?.sourceHash)) {
return this.packs[i];
}
}
return this.getPackByName(packName);
}
async ensurePackForFile(file) {
const pack = this._ensurePack(file.storageRelativePath);
await pack.ensureData(this, file);
return pack;
}
_ensurePack(storagePath) {
if (this.packs === undefined) {
this.packs = [];
}
for (let i = 0; i < this.packs.length; i++) {
if (this.packs[i].storagePath === storagePath) {
return this.packs[i];
}
}
const pack = new Package_1.default(StorageUtilities_1.default.getLeafName(storagePath), storagePath);
this.packs.push(pack);
return pack;
}
_handleMessageFromAppService(command, data) {
switch (command) {
case "externalKeyPress":
if (data.startsWith("command")) {
const commandIndex = parseInt(data.substring(7, data.length));
CommandRunner_1.default.runCustomTool(this, commandIndex);
}
break;
case "statusMessage":
const firstPipe = data.indexOf("|");
const content = data.substring(firstPipe + 1, data.length);
try {
const contentO = JSON.parse(content);
this.notifyExternalStatus(contentO);
}
catch (e) { }
break;
case "mctSavedInAppService":
this.load(true);
break;
case "logFileUpdated":
try {
if (data) {
const firstPipe = data.indexOf("|");
if (firstPipe > 0) {
const fileName = data.substring(0, firstPipe);
const content = data.substring(firstPipe + 1, data.length);
this._handleLogFileUpdated(fileName, content);
}
}
}
catch (e) {
Log_1.default.fail("Error parsing inbound log: " + e);
}
break;
default:
if (this.deploymentStorageMinecraft) {
this.deploymentStorageMinecraft.processExternalMessage(command, data);
}
if (this.processHostedMinecraft) {
this.processHostedMinecraft.processExternalMessage(command, data);
}
if (this.gameMinecraft) {
this.gameMinecraft.processExternalMessage(command, data);
}
if (this.remoteMinecraft) {
this.remoteMinecraft.processExternalMessage(command, data);
}
break;
}
}
_handleLogFileUpdated(fileName, contents) {
if (contents === null || contents === undefined || fileName === null || fileName === undefined) {
return;
}
let arr = this.mcLogs[fileName];
if (arr === undefined) {
arr = [];
this.mcLogs[fileName] = arr;
}
const logItems = contents.split("\r");
for (let i = logItems.length - 1; i >= 0; i--) {
const logItem = logItems[i];
if (logItem !== undefined && logItem.length > 3) {
if (!arr.includes(logItem)) {
arr.push(logItem);
this.notifyStatusUpdate(logItem);
}
}
}
}
async notifyStatusUpdate(message, topic) {
const messageCanon = message.trim().toLowerCase();
if (messageCanon.length > 1) {
const status = {
time: new Date(),
message: message,
topic: topic,
type: Status_1.StatusType.message,
};
this.status.push(status);
await this.callStatusAddedListeners(status);
this.ensureStatusArrayIsTrimmed();
}
}
ensureStatusArrayIsTrimmed() {
if (this.status.length > 10000) {
const newStatusArr = [];
for (let i = this.status.length - 9000; i < this.status.length; i++) {
newStatusArr.push(this.status[i]);
}
this.status = newStatusArr;
}
}
async callStatusAddedListeners(status) {
this._onStatusAdded.dispatch(this, status);
if (this._onStatusAddedAsync.length > 0) {
let promises = [];
for (let i = 0; i < this._onStatusAddedAsync.length; i++) {
promises.push(this._onStatusAddedAsync[i](this, status));
}
await Promise.all(promises);
}
}
notifyExternalStatus(status) {
this.status.push(status);
if (status.type === Status_1.StatusType.operationStarted) {
this.activeOperations.push(status);
}
else if ((status.type === Status_1.StatusType.operationEndedComplete || status.type === Status_1.StatusType.operationEndedErrors) &&
status.operationId !== null &&
status.operationId !== undefined) {
this.removeOperation(status.operationId);
}
this.callStatusAddedListeners(status);
return status.operationId;
}
async notifyOperationStarted(message, topic) {
const status = {
time: new Date(),
message: message,
type: Status_1.StatusType.operationStarted,
topic: topic,
};
status.operationId = status.time.getTime();
this.status.push(status);
this.activeOperations.push(status);
this.ensureStatusArrayIsTrimmed();
await this.callStatusAddedListeners(status);
return status.operationId;
}
async notifyOperationEnded(endedOperationId, message, topic, endedWithErrors) {
this.ensureStatusArrayIsTrimmed();
this.removeOperation(endedOperationId);
this._onOperationCompleted.dispatch(this, endedOperationId);
if (!message) {
return;
}
const status = {
message: message,
operationId: endedOperationId,
type: endedWithErrors ? Status_1.StatusType.operationEndedErrors : Status_1.StatusType.operationEndedComplete,
time: new Date(),
topic: topic,
};
this.status.push(status);
await this.callStatusAddedListeners(status);
}
removeOperation(id) {
// remove operation from list of active operations.
const newActiveOperations = [];
for (let i = 0; i < this.activeOperations.length; i++) {
const oper = this.activeOperations[i];
if (oper.operationId !== id) {
newActiveOperations.push(oper);
}
}
this.activeOperations = newActiveOperations;
}
async save() {
const configFile = this.file;
configFile.setContent(JSON.stringify(__classPrivateFieldGet(this, _Carto_data, "f"), null, 2));
await configFile.saveContent();
if (AppServiceProxy_1.default.hasAppService) {
AppServiceProxy_1.default.sendAsync(AppServiceProxy_1.AppServiceProxyCommands.reloadMct, "");
}
}
async loadGallery() {
let result = null;
// @ts-ignore
if (typeof window !== "undefined") {
const url = this.contentRoot + "data/gallery.json";
try {
result = await axios_1.default.get(url);
if (result) {
this._gallery = result.data;
}
}
catch (e) {
Log_1.default.fail("Could not load gallery: " + e + " from '" + url + "'");
}
}
else if (this.local) {
try {
result = await this.local.readJsonFile("data/gallery.json");
}
catch (e) {
Log_1.default.fail("Could not load local file: " + e + " from 'data/gallery.json'");
}
if (result !== null) {
this._gallery = result;
}
}
if (this._gallery) {
for (const item of this._gallery.items) {
if (item.sampleSet) {
item.gitHubOwner = "microsoft";
item.gitHubRepoName = "minecraft-scripting-samples";
if (item.type === IGalleryItem_1.GalleryItemType.editorCodeSample) {
item.gitHubFolder = "/editor-script-box";
if (!item.tags) {
item.tags = ["editor"];
}
}
else {
item.gitHubFolder = "/script-box";
}
}
if (item.fileList) {
const newFileList = [];
for (const fileItem of item.fileList) {
newFileList.push(MinecraftUtilities_1.default.replaceMinecraftPathTokens(fileItem));
}
item.fileList = newFileList;
}
}
}
this._galleryLoaded = true;
this._onGalleryLoaded.dispatch(this, this._gallery);
return this._gallery;
}
async getGalleryProjectByGitHub(repoName, owner, branch, folder, withFiles) {
if (!this._galleryLoaded) {
await this.loadGallery();
}
if (this._galleryLoaded === false || this._gallery === undefined || this._gallery.items === undefined) {
return undefined;
}
repoName = repoName.toLowerCase();
owner = owner.toLowerCase();
for (const galProj of this._gallery.items) {
if (galProj.gitHubRepoName.toLowerCase() === repoName &&
galProj.gitHubOwner.toLowerCase() === owner &&
branch === galProj.gitHubBranch &&
folder === galProj.gitHubFolder &&
(!withFiles || galProj.fileList)) {
return galProj;
}
}
return undefined;
}
async getGalleryProjectById(galleryProjectId) {
if (!this._galleryLoaded) {
await this.loadGallery();
}
if (this._galleryLoaded === false || this._gallery === undefined || this._gallery.items === undefined) {
return undefined;
}
galleryProjectId = galleryProjectId.toLowerCase();
galleryProjectId = galleryProjectId.replace(/-/gi, "");
for (const galProj of this._gallery.items) {
if (galProj.id.toLowerCase() === galleryProjectId) {
return galProj;
}
}
return undefined;
}
async getNewProjectName(seedName) {
await this.load();
let newProjectName = seedName;
let counter = 0;
while (this.prefsProjectsFolder.fileExists(newProjectName + ".json") ||
this.projectsStorage.rootFolder.folderExists(newProjectName)) {
counter++;
newProjectName = seedName + " " + counter;
}
return newProjectName;
}
async createNewProject(newProjectName, newProjectPath, newProjectFolder, newProjectFolderTitle, focus, includeDefaultItems, projectLanguage) {
await this.load();
const targetProjectName = await this.getNewProjectName(newProjectName);
let projectPrefs;
if (newProjectFolder) {
projectPrefs = await newProjectFolder.ensureFileFromRelativePath("/.mct/prefs.mctp.json");
}
else {
projectPrefs = await this.prefsProjectsFolder.createFile(targetProjectName + ".json");
}
const newProject = new Project_1.default(this, targetProjectName, projectPrefs);
if (newProjectPath && !newProjectFolder) {
newProject.mainDeployFolderPath = newProjectPath;
}
if (projectLanguage) {
newProject.preferredScriptLanguage = projectLanguage;
}
if (newProjectFolder) {
newProject.setProjectFolder(newProjectFolder);
newProject.projectFolderTitle = newProjectFolderTitle;
}
else {
await newProject.ensureProjectFolder();
}
newProject.focus = focus;
if (includeDefaultItems) {
await newProject.ensureDefaultItems();
}
this.projects.push(newProject);
return newProject;
}
async createNewProjectFromFolder(path) {
await this.load();
let newProjectName = StorageUtilities_1.default.getLeafName(path);
let counter = 0;
while (this.prefsProjectsFolder.fileExists(newProjectName + ".json") ||
this.projectsStorage.rootFolder.folderExists(newProjectName)) {
counter++;
newProjectName = StorageUtilities_1.default.getLeafName(path) + " " + counter;
}
const projectPrefs = await this.prefsProjectsFolder.createFile(newProjectName + ".json");
const newProject = new Project_1.default(this, newProjectName, projectPrefs);
newProject.mainDeployFolderPath = path;
await newProject.ensureProjectFolder();
await newProject.ensureInflated();
await newProject.inferProjectItemsFromFiles();
this.projects.push(newProject);
return newProject;
}
async deleteProjectByName(projectName) {
let projectToDelete;
for (let i = 0; i < this.projects.length; i++) {
const proj = this.projects[i];
if (proj.name === projectName) {
if (projectToDelete !== undefined) {
Log_1.default.fail("Encountered multiple projects with the same name.");
return;
}
projectToDelete = proj;
}
}
if (projectToDelete) {
await projectToDelete.deleteThisProject();
this.removeProject(projectToDelete);
projectToDelete.dispose();
}
}
removeProject(project) {
const newProjects = [];
for (let i = 0; i < this.projects.length; i++) {
const proj = this.projects[i];
if (proj !== project) {
newProjects.push(proj);
}
}
this.projects = newProjects;
}
getProjectByName(projectName) {
for (let i = 0; i < this.projects.length; i++) {
const proj = this.projects[i];
if (proj.name === projectName) {
return proj;
}
}
return undefined;
}
getProjectByMainLocalFolderPath(localPath) {
localPath = StorageUtilities_1.default.canonicalizePath(localPath);
for (let i = 0; i < this.projects.length; i++) {
const proj = this.projects[i];
if (proj.mainDeployFolderPath && StorageUtilities_1.default.canonicalizePath(proj.mainDeployFolderPath) === localPath) {
return proj;
}
}
return undefined;
}
async ensureProjectFromLocalStoragePath(messageProjectPath) {
if (!this.local) {
Log_1.default.fail("Could not find local utilities.");
return;
}
await this.load();
let desiredProjectName = StorageUtilities_1.default.canonicalizePathAsFileName(messageProjectPath);
// check to see if the expected project with the expected name exists, and use that if possible.
const project = this.getProjectByName(desiredProjectName);
const canonPath = StorageUtilities_1.default.canonicalizePath(messageProjectPath);
if (project !== undefined) {
await project.ensurePreferencesAndFolderLoadedFromFile();
if (project.mainDeployFolderPath !== undefined) {
if (canonPath === StorageUtilities_1.default.canonicalizePath(project.mainDeployFolderPath)) {
await project.ensureInflated();
await project.inferProjectItemsFromFiles();
return project;
}
}
}
// OK, a project doesn't exist, let's create one.
let counter = 0;
while (this.prefsProjectsFolder.fileExists(desiredProjectName + ".json") ||
this.projectsStorage.rootFolder.folderExists(desiredProjectName)) {
counter++;
desiredProjectName = StorageUtilities_1.default.canonicalizePathAsFileName(messageProjectPath) + " " + counter;
}
const projectPrefs = await this.prefsProjectsFolder.createFile(desiredProjectName + ".json");
const newProject = new Project_1.default(this, desiredProjectName, projectPrefs);
newProject.mainDeployFolderPath = messageProjectPath;
newProject.originalFullPath = messageProjectPath;
const localStorage = await this.local.createStorage(messageProjectPath);
if (localStorage === null) {
Log_1.default.fail("Could not create local storage.");
return;
}
newProject.setProjectFolder(localStorage.rootFolder);
await newProject.ensureProjectFolder();
await ProjectItemRelations_1.default.calculate(newProject);
await newProject.inferProjectItemsFromFiles();
this.projects.push(newProject);
return newProject;
}
async ensureProjectForFolder(folderPath, newProjectName, openDirect) {
await this.load();
let desiredProjectName = "";
if (newProjectName !== undefined) {
desiredProjectName = newProjectName;
}
else {
desiredProjectName = StorageUtilities_1.default.getLeafName(folderPath);
}
let canonPath = StorageUtilities_1.default.canonicalizePath(folderPath);
let project = this.getProjectByMainLocalFolderPath(folderPath);
// check to see if the expected project with the expected name exists, and use that if possible.
if (!project) {
project = this.getProjectByName(desiredProjectName);
}
if (project !== undefined && !openDirect) {
await project.ensurePreferencesAndFolderLoadedFromFile();
if (project.mainDeployFolderPath !== undefined) {
if (canonPath === StorageUtilities_1.default.canonicalizePath(project.mainDeployFolderPath)) {
await project.ensureInflated();
await project.inferProjectItemsFromFiles();
return project;
}
}
}
else if (project && openDirect) {
for (let i = 1; i < 99; i++) {
desiredProjectName = StorageUtilities_1.default.getLeafName(folderPath) + " " + i;
canonPath = StorageUtilities_1.default.canonicalizePath(folderPath) + " " + i;
if (newProjectName !== undefined) {
desiredProjectName = newProjectName;
}
// check to see if the expected project with the expected name exists, and use that if possible.
let project = this.getProjectByName(desiredProjectName);
if (!project) {
break;
}
}
}
// now check all other projects to see if one exists.
for (let i = 0; i < this.projects.length; i++) {
project = this.projects[i];
await project.ensurePreferencesAndFolderLoadedFromFile();
if (project.mainDeployFolderPath !== undefined) {
if (canonPath === StorageUtilities_1.default.canonicalizePath(project.mainDeployFolderPath)) {
await project.ensureInflated();
await project.infer