shipthis
Version:
ShipThis manages building and uploading your Godot games to the App Store and Google Play.
1,176 lines (1,153 loc) • 39.5 kB
JavaScript
import { Flags } from '@oclif/core';
import { o as API_URL, p as getAuthedHeaders, P as Platform, a9 as getShortDateTime, F as castArrayObjectDates, J as JobStatus, aa as getShortTimeDelta, z as getJob, ab as JobStage, a2 as LogLevel, k as getProject, a3 as getShortAuthRequiredUrl, H as queryClient, ac as BuildType, W as WEB_URL, B as BaseCommand, ad as getSelf, ae as getTerms, a8 as updateProject } from './baseCommand-CTn3KGH3.js';
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
import { useStdin, useInput, Text, Box } from 'ink';
import Spinner from 'ink-spinner';
import crypto from 'node:crypto';
import fs__default from 'node:fs';
import path__default from 'node:path';
import { promises } from 'node:readline';
import { fileURLToPath } from 'node:url';
import readlineSync from 'readline-sync';
import 'luxon';
import axios from 'axios';
import 'isomorphic-git';
import { useQuery } from '@tanstack/react-query';
import React, { useState, useEffect, useContext, useRef } from 'react';
import 'fast-glob';
import 'uuid';
import 'yazl';
import 'socket.io-client';
import 'fullscreen-ink';
import 'string-length';
import 'strip-ansi';
import open from 'open';
import '@inkjs/ui';
import require$$0 from 'fs';
import require$$1 from 'path';
import { setOptions, parse } from 'marked';
import TerminalRenderer from 'marked-terminal';
import 'qrcode';
import 'crypto-js';
const cacheKeys = {
androidKeyTestResult: (props) => ["androidKeyTestResult", ...Object.values(props)],
androidSetupStatus: (props) => ["androidSetupStatus", ...Object.values(props)],
builds: (props) => ["builds", ...Object.values(props)],
googleStatus: () => ["googleStatus"],
job: (props) => ["job", ...Object.values(props)],
jobLogs: (props) => ["jobLogs", ...Object.values(props)],
jobs: (props) => ["jobs", ...Object.values(props)],
projectCredentials: (props) => ["projectCredentials", ...Object.values(props)],
userCredentials: (props) => ["userCredentials", ...Object.values(props)]
};
var KeyTestStatus = /* @__PURE__ */ ((KeyTestStatus2) => {
KeyTestStatus2["ERROR"] = "error";
KeyTestStatus2["SUCCESS"] = "success";
return KeyTestStatus2;
})(KeyTestStatus || {});
var KeyTestError = /* @__PURE__ */ ((KeyTestError2) => {
KeyTestError2["APP_NOT_FOUND"] = "app_not_found";
KeyTestError2["NO_PACKAGE_NAME"] = "no_package_name";
KeyTestError2["NO_SERVICE_ACCOUNT_KEY"] = "no_service_account_key";
KeyTestError2["NOT_INVITED"] = "not_invited";
return KeyTestError2;
})(KeyTestError || {});
const KeyTestErrorMessage = {
["app_not_found" /* APP_NOT_FOUND */]: "Application not found in Google Play Console",
["no_package_name" /* NO_PACKAGE_NAME */]: "Android Package Name has not been set",
["no_service_account_key" /* NO_SERVICE_ACCOUNT_KEY */]: "Service Account API Key not found in your account",
["not_invited" /* NOT_INVITED */]: "Service Account has not been invited to Google Play"
};
function niceError(keyError) {
return keyError ? KeyTestErrorMessage[keyError] : void 0;
}
const fetchKeyTestResult = async ({ projectId }, config) => {
if (!projectId) throw new Error("projectId is required");
const url = `${API_URL}/projects/${projectId}/credentials/android/key/test`;
const headers = getAuthedHeaders();
const { data } = await axios.post(url, {}, { headers, ...config });
return data;
};
const useAndroidServiceAccountTestResult = (props) => useQuery({
queryFn: () => fetchKeyTestResult(props),
queryKey: cacheKeys.androidKeyTestResult(props)
});
async function queryBuilds({ projectId, ...pageAndSortParams }) {
try {
const headers = getAuthedHeaders();
const url = `${API_URL}/projects/${projectId}/builds`;
const response = await axios.get(url, { headers, params: pageAndSortParams });
return {
...response.data,
data: castArrayObjectDates(response.data.data)
};
} catch (error) {
console.warn("queryBuilds Error", error);
throw error;
}
}
function getBuildSummary(build) {
const ext = build.buildType || (build.platform === Platform.IOS ? "IPA" : "AAB");
const filename = `game.${ext.toLowerCase()}`;
const details = getJobDetailsSummary(build.jobDetails);
const summary = {};
summary.id = getShortUUID(build.id);
summary.version = details.version;
summary.gitInfo = details.gitInfo;
summary.platform = getPlatformName(build.platform);
summary.jobId = getShortUUID(build.jobId);
summary.createdAt = getShortDateTime(build.createdAt);
summary.cmd = `shipthis game build download ${getShortUUID(build.id)} ${filename}`;
return summary;
}
const useBuilds = (props) => {
const queryResult = useQuery({
queryFn: async () => queryBuilds(props),
queryKey: cacheKeys.builds(props)
});
return queryResult;
};
function getJobDetailsSummary(jobDetails) {
const semanticVersion = jobDetails?.semanticVersion || "N/A";
const buildNumber = jobDetails?.buildNumber || "N/A";
const gitCommit = jobDetails?.gitCommitHash ? getShortUUID(jobDetails.gitCommitHash) : "";
const gitBranch = jobDetails?.gitBranch || "";
const details = {};
details.version = `${semanticVersion} (${buildNumber})`;
details.gitInfo = gitCommit ? `${gitCommit} (${gitBranch})` : "";
return details;
}
function getJobSummary(job, timeNow) {
const inProgress = ![JobStatus.COMPLETED, JobStatus.FAILED].includes(job.status);
const details = getJobDetailsSummary(job.details);
const summary = {};
summary.id = getShortUUID(job.id);
summary.version = details.version;
summary.gitInfo = details.gitInfo;
summary.platform = getPlatformName(job.type);
summary.status = job.status;
summary.createdAt = getShortDateTime(job.createdAt);
summary.runtime = getShortTimeDelta(job.createdAt, inProgress ? timeNow : job.updatedAt);
return summary;
}
const useJob = (props) => useQuery({
queryFn: () => getJob(props.jobId, props.projectId),
queryKey: cacheKeys.job(props)
});
const useSafeInput = (handler, options = { isActive: true }) => {
const { isRawModeSupported } = useStdin();
const isActive = isRawModeSupported === true && options.isActive !== false;
useInput(
(input, key) => {
const lowerInput = input.toLowerCase();
return handler(lowerInput, key);
},
{ isActive }
);
};
function getShortUUID(originalUuid) {
return originalUuid.slice(0, 8);
}
function getStageColor(stage) {
switch (stage) {
case JobStage.SETUP: {
return "#FFB3B3";
}
// pastel red
case JobStage.CONFIGURE: {
return "#FFD9B3";
}
// pastel orange
case JobStage.EXPORT: {
return "#FFFACD";
}
// pastel yellow
case JobStage.BUILD: {
return "#B3FFB3";
}
// pastel green
case JobStage.PUBLISH: {
return "#B3D9FF";
}
}
}
function getMessageColor(level) {
switch (level) {
case LogLevel.INFO: {
return "white";
}
case LogLevel.WARN: {
return "yellow";
}
case LogLevel.ERROR: {
return "red";
}
}
}
function getJobStatusColor(status) {
switch (status) {
case JobStatus.PENDING: {
return "yellow";
}
case JobStatus.PROCESSING: {
return "blue";
}
case JobStatus.COMPLETED: {
return "green";
}
case JobStatus.FAILED: {
return "red";
}
}
}
async function getFileHash(filename) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash("sha256");
const rs = fs__default.createReadStream(filename);
rs.on("error", reject);
rs.on("data", (chunk) => hash.update(chunk));
rs.on("end", () => resolve(hash.digest("hex")));
});
}
function isValidSemVer(versionString) {
const [semVer, major, minor, patch, prerelease, buildmetadata] = versionString.match(
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/
) ?? [];
return Boolean(semVer);
}
function makeHumanReadable(rawObject) {
const getLabel = (key) => {
const words = key.split(/(?=[A-Z])/);
return words.map((word) => word[0].toUpperCase() + word.slice(1)).join(" ").replaceAll(" ", " ");
};
const withLabels = Object.entries(rawObject).reduce((acc, [key, value]) => {
acc[getLabel(key)] = value;
return acc;
}, {});
return withLabels;
}
function getPlatformName(platform) {
switch (platform) {
case Platform.IOS: {
return "iOS";
}
case Platform.ANDROID: {
return "Android";
}
default: {
throw new Error(`Unknown platform: ${platform}`);
}
}
}
async function getMaskedInput(message) {
const password = readlineSync.question(message, {
hideEchoBack: true
// This will hide the input as the user types
});
return password;
}
async function getInput(message) {
const rl = promises.createInterface({
input: process.stdin,
output: process.stdout
});
const answer = await rl.question(message);
rl.close();
return answer;
}
function generatePackageName(gameName) {
let normalizedGameName = gameName.trim().toLowerCase();
normalizedGameName = normalizedGameName.replaceAll(/[\s_\-]+/g, ".");
normalizedGameName = normalizedGameName.replaceAll(/[^\d.a-z]/g, "");
normalizedGameName = normalizedGameName.replaceAll(/\.+/g, ".");
normalizedGameName = normalizedGameName.replace(/^\./, "").replace(/\.$/, "");
if (/^\d/.test(normalizedGameName)) {
normalizedGameName = "app." + normalizedGameName;
}
const prefix = "com.";
if (normalizedGameName === "") {
return null;
}
return prefix + normalizedGameName;
}
function scriptDir(importMeta) {
const filename = fileURLToPath(importMeta.url);
const dirname = path__default.dirname(filename);
return dirname;
}
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var ejs$1 = {};
var utils = {};
var hasRequiredUtils;
function requireUtils () {
if (hasRequiredUtils) return utils;
hasRequiredUtils = 1;
(function (exports) {
var regExpChars = /[|\\{}()[\]^$+*?.]/g;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var hasOwn = function(obj, key) {
return hasOwnProperty.apply(obj, [key]);
};
exports.escapeRegExpChars = function(string) {
if (!string) {
return "";
}
return String(string).replace(regExpChars, "\\$&");
};
var _ENCODE_HTML_RULES = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
};
var _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
return _ENCODE_HTML_RULES[c] || c;
}
var escapeFuncStr = `var _ENCODE_HTML_RULES = {
"&": "&"
, "<": "<"
, ">": ">"
, '"': """
, "'": "'"
}
, _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
return _ENCODE_HTML_RULES[c] || c;
};
`;
exports.escapeXML = function(markup) {
return markup == void 0 ? "" : String(markup).replace(_MATCH_HTML, encode_char);
};
function escapeXMLToString() {
return Function.prototype.toString.call(this) + ";\n" + escapeFuncStr;
}
try {
if (typeof Object.defineProperty === "function") {
Object.defineProperty(exports.escapeXML, "toString", { value: escapeXMLToString });
} else {
exports.escapeXML.toString = escapeXMLToString;
}
} catch (err) {
console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)");
}
exports.shallowCopy = function(to, from) {
from = from || {};
if (to !== null && to !== void 0) {
for (var p in from) {
if (!hasOwn(from, p)) {
continue;
}
if (p === "__proto__" || p === "constructor") {
continue;
}
to[p] = from[p];
}
}
return to;
};
exports.shallowCopyFromList = function(to, from, list) {
list = list || [];
from = from || {};
if (to !== null && to !== void 0) {
for (var i = 0; i < list.length; i++) {
var p = list[i];
if (typeof from[p] != "undefined") {
if (!hasOwn(from, p)) {
continue;
}
if (p === "__proto__" || p === "constructor") {
continue;
}
to[p] = from[p];
}
}
}
return to;
};
exports.cache = {
_data: {},
set: function(key, val) {
this._data[key] = val;
},
get: function(key) {
return this._data[key];
},
remove: function(key) {
delete this._data[key];
},
reset: function() {
this._data = {};
}
};
exports.hyphenToCamel = function(str) {
return str.replace(/-[a-z]/g, function(match) {
return match[1].toUpperCase();
});
};
exports.createNullProtoObjWherePossible = function() {
if (typeof Object.create == "function") {
return function() {
return /* @__PURE__ */ Object.create(null);
};
}
if (!({ __proto__: null } instanceof Object)) {
return function() {
return { __proto__: null };
};
}
return function() {
return {};
};
}();
exports.hasOwnOnlyObject = function(obj) {
var o = exports.createNullProtoObjWherePossible();
for (var p in obj) {
if (hasOwn(obj, p)) {
o[p] = obj[p];
}
}
return o;
};
} (utils));
return utils;
}
var version = "3.1.10";
var require$$3 = {
version: version};
var hasRequiredEjs;
function requireEjs () {
if (hasRequiredEjs) return ejs$1;
hasRequiredEjs = 1;
(function (exports) {
/**
* @file Embedded JavaScript templating engine. {@link http://ejs.co}
* @author Matthew Eernisse <mde@fleegix.org>
* @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
* @project EJS
* @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
*/
var fs = require$$0;
var path = require$$1;
var utils = requireUtils();
var scopeOptionWarned = false;
var _VERSION_STRING = require$$3.version;
var _DEFAULT_OPEN_DELIMITER = "<";
var _DEFAULT_CLOSE_DELIMITER = ">";
var _DEFAULT_DELIMITER = "%";
var _DEFAULT_LOCALS_NAME = "locals";
var _NAME = "ejs";
var _REGEX_STRING = "(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)";
var _OPTS_PASSABLE_WITH_DATA = [
"delimiter",
"scope",
"context",
"debug",
"compileDebug",
"client",
"_with",
"rmWhitespace",
"strict",
"filename",
"async"
];
var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat("cache");
var _BOM = /^\uFEFF/;
var _JS_IDENTIFIER = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/;
exports.cache = utils.cache;
exports.fileLoader = fs.readFileSync;
exports.localsName = _DEFAULT_LOCALS_NAME;
exports.promiseImpl = new Function("return this;")().Promise;
exports.resolveInclude = function(name, filename, isDir) {
var dirname = path.dirname;
var extname = path.extname;
var resolve = path.resolve;
var includePath = resolve(isDir ? filename : dirname(filename), name);
var ext = extname(name);
if (!ext) {
includePath += ".ejs";
}
return includePath;
};
function resolvePaths(name, paths) {
var filePath;
if (paths.some(function(v) {
filePath = exports.resolveInclude(name, v, true);
return fs.existsSync(filePath);
})) {
return filePath;
}
}
function getIncludePath(path2, options) {
var includePath;
var filePath;
var views = options.views;
var match = /^[A-Za-z]+:\\|^\//.exec(path2);
if (match && match.length) {
path2 = path2.replace(/^\/*/, "");
if (Array.isArray(options.root)) {
includePath = resolvePaths(path2, options.root);
} else {
includePath = exports.resolveInclude(path2, options.root || "/", true);
}
} else {
if (options.filename) {
filePath = exports.resolveInclude(path2, options.filename);
if (fs.existsSync(filePath)) {
includePath = filePath;
}
}
if (!includePath && Array.isArray(views)) {
includePath = resolvePaths(path2, views);
}
if (!includePath && typeof options.includer !== "function") {
throw new Error('Could not find the include file "' + options.escapeFunction(path2) + '"');
}
}
return includePath;
}
function handleCache(options, template) {
var func;
var filename = options.filename;
var hasTemplate = arguments.length > 1;
if (options.cache) {
if (!filename) {
throw new Error("cache option requires a filename");
}
func = exports.cache.get(filename);
if (func) {
return func;
}
if (!hasTemplate) {
template = fileLoader(filename).toString().replace(_BOM, "");
}
} else if (!hasTemplate) {
if (!filename) {
throw new Error("Internal EJS error: no file name or template provided");
}
template = fileLoader(filename).toString().replace(_BOM, "");
}
func = exports.compile(template, options);
if (options.cache) {
exports.cache.set(filename, func);
}
return func;
}
function tryHandleCache(options, data, cb) {
var result;
if (!cb) {
if (typeof exports.promiseImpl == "function") {
return new exports.promiseImpl(function(resolve, reject) {
try {
result = handleCache(options)(data);
resolve(result);
} catch (err) {
reject(err);
}
});
} else {
throw new Error("Please provide a callback function");
}
} else {
try {
result = handleCache(options)(data);
} catch (err) {
return cb(err);
}
cb(null, result);
}
}
function fileLoader(filePath) {
return exports.fileLoader(filePath);
}
function includeFile(path2, options) {
var opts = utils.shallowCopy(utils.createNullProtoObjWherePossible(), options);
opts.filename = getIncludePath(path2, opts);
if (typeof options.includer === "function") {
var includerResult = options.includer(path2, opts.filename);
if (includerResult) {
if (includerResult.filename) {
opts.filename = includerResult.filename;
}
if (includerResult.template) {
return handleCache(opts, includerResult.template);
}
}
}
return handleCache(opts);
}
function rethrow(err, str, flnm, lineno, esc) {
var lines = str.split("\n");
var start = Math.max(lineno - 3, 0);
var end = Math.min(lines.length, lineno + 3);
var filename = esc(flnm);
var context = lines.slice(start, end).map(function(line, i) {
var curr = i + start + 1;
return (curr == lineno ? " >> " : " ") + curr + "| " + line;
}).join("\n");
err.path = filename;
err.message = (filename || "ejs") + ":" + lineno + "\n" + context + "\n\n" + err.message;
throw err;
}
function stripSemi(str) {
return str.replace(/;(\s*$)/, "$1");
}
exports.compile = function compile(template, opts) {
var templ;
if (opts && opts.scope) {
if (!scopeOptionWarned) {
console.warn("`scope` option is deprecated and will be removed in EJS 3");
scopeOptionWarned = true;
}
if (!opts.context) {
opts.context = opts.scope;
}
delete opts.scope;
}
templ = new Template(template, opts);
return templ.compile();
};
exports.render = function(template, d, o) {
var data = d || utils.createNullProtoObjWherePossible();
var opts = o || utils.createNullProtoObjWherePossible();
if (arguments.length == 2) {
utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
}
return handleCache(opts, template)(data);
};
exports.renderFile = function() {
var args = Array.prototype.slice.call(arguments);
var filename = args.shift();
var cb;
var opts = { filename };
var data;
var viewOpts;
if (typeof arguments[arguments.length - 1] == "function") {
cb = args.pop();
}
if (args.length) {
data = args.shift();
if (args.length) {
utils.shallowCopy(opts, args.pop());
} else {
if (data.settings) {
if (data.settings.views) {
opts.views = data.settings.views;
}
if (data.settings["view cache"]) {
opts.cache = true;
}
viewOpts = data.settings["view options"];
if (viewOpts) {
utils.shallowCopy(opts, viewOpts);
}
}
utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
}
opts.filename = filename;
} else {
data = utils.createNullProtoObjWherePossible();
}
return tryHandleCache(opts, data, cb);
};
exports.Template = Template;
exports.clearCache = function() {
exports.cache.reset();
};
function Template(text, optsParam) {
var opts = utils.hasOwnOnlyObject(optsParam);
var options = utils.createNullProtoObjWherePossible();
this.templateText = text;
this.mode = null;
this.truncate = false;
this.currentLine = 1;
this.source = "";
options.client = opts.client || false;
options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
options.compileDebug = opts.compileDebug !== false;
options.debug = !!opts.debug;
options.filename = opts.filename;
options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
options.strict = opts.strict || false;
options.context = opts.context;
options.cache = opts.cache || false;
options.rmWhitespace = opts.rmWhitespace;
options.root = opts.root;
options.includer = opts.includer;
options.outputFunctionName = opts.outputFunctionName;
options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
options.views = opts.views;
options.async = opts.async;
options.destructuredLocals = opts.destructuredLocals;
options.legacyInclude = typeof opts.legacyInclude != "undefined" ? !!opts.legacyInclude : true;
if (options.strict) {
options._with = false;
} else {
options._with = typeof opts._with != "undefined" ? opts._with : true;
}
this.opts = options;
this.regex = this.createRegex();
}
Template.modes = {
EVAL: "eval",
ESCAPED: "escaped",
RAW: "raw",
COMMENT: "comment",
LITERAL: "literal"
};
Template.prototype = {
createRegex: function() {
var str = _REGEX_STRING;
var delim = utils.escapeRegExpChars(this.opts.delimiter);
var open = utils.escapeRegExpChars(this.opts.openDelimiter);
var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
str = str.replace(/%/g, delim).replace(/</g, open).replace(/>/g, close);
return new RegExp(str);
},
compile: function() {
var src;
var fn;
var opts = this.opts;
var prepended = "";
var appended = "";
var escapeFn = opts.escapeFunction;
var ctor;
var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : "undefined";
if (!this.source) {
this.generateSource();
prepended += ' var __output = "";\n function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
if (opts.outputFunctionName) {
if (!_JS_IDENTIFIER.test(opts.outputFunctionName)) {
throw new Error("outputFunctionName is not a valid JS identifier.");
}
prepended += " var " + opts.outputFunctionName + " = __append;\n";
}
if (opts.localsName && !_JS_IDENTIFIER.test(opts.localsName)) {
throw new Error("localsName is not a valid JS identifier.");
}
if (opts.destructuredLocals && opts.destructuredLocals.length) {
var destructuring = " var __locals = (" + opts.localsName + " || {}),\n";
for (var i = 0; i < opts.destructuredLocals.length; i++) {
var name = opts.destructuredLocals[i];
if (!_JS_IDENTIFIER.test(name)) {
throw new Error("destructuredLocals[" + i + "] is not a valid JS identifier.");
}
if (i > 0) {
destructuring += ",\n ";
}
destructuring += name + " = __locals." + name;
}
prepended += destructuring + ";\n";
}
if (opts._with !== false) {
prepended += " with (" + opts.localsName + " || {}) {\n";
appended += " }\n";
}
appended += " return __output;\n";
this.source = prepended + this.source + appended;
}
if (opts.compileDebug) {
src = "var __line = 1\n , __lines = " + JSON.stringify(this.templateText) + "\n , __filename = " + sanitizedFilename + ";\ntry {\n" + this.source + "} catch (e) {\n rethrow(e, __lines, __filename, __line, escapeFn);\n}\n";
} else {
src = this.source;
}
if (opts.client) {
src = "escapeFn = escapeFn || " + escapeFn.toString() + ";\n" + src;
if (opts.compileDebug) {
src = "rethrow = rethrow || " + rethrow.toString() + ";\n" + src;
}
}
if (opts.strict) {
src = '"use strict";\n' + src;
}
if (opts.debug) {
console.log(src);
}
if (opts.compileDebug && opts.filename) {
src = src + "\n//# sourceURL=" + sanitizedFilename + "\n";
}
try {
if (opts.async) {
try {
ctor = new Function("return (async function(){}).constructor;")();
} catch (e) {
if (e instanceof SyntaxError) {
throw new Error("This environment does not support async/await");
} else {
throw e;
}
}
} else {
ctor = Function;
}
fn = new ctor(opts.localsName + ", escapeFn, include, rethrow", src);
} catch (e) {
if (e instanceof SyntaxError) {
if (opts.filename) {
e.message += " in " + opts.filename;
}
e.message += " while compiling ejs\n\n";
e.message += "If the above error is not helpful, you may want to try EJS-Lint:\n";
e.message += "https://github.com/RyanZim/EJS-Lint";
if (!opts.async) {
e.message += "\n";
e.message += "Or, if you meant to create an async function, pass `async: true` as an option.";
}
}
throw e;
}
var returnedFn = opts.client ? fn : function anonymous(data) {
var include = function(path2, includeData) {
var d = utils.shallowCopy(utils.createNullProtoObjWherePossible(), data);
if (includeData) {
d = utils.shallowCopy(d, includeData);
}
return includeFile(path2, opts)(d);
};
return fn.apply(
opts.context,
[data || utils.createNullProtoObjWherePossible(), escapeFn, include, rethrow]
);
};
if (opts.filename && typeof Object.defineProperty === "function") {
var filename = opts.filename;
var basename = path.basename(filename, path.extname(filename));
try {
Object.defineProperty(returnedFn, "name", {
value: basename,
writable: false,
enumerable: false,
configurable: true
});
} catch (e) {
}
}
return returnedFn;
},
generateSource: function() {
var opts = this.opts;
if (opts.rmWhitespace) {
this.templateText = this.templateText.replace(/[\r\n]+/g, "\n").replace(/^\s+|\s+$/gm, "");
}
this.templateText = this.templateText.replace(/[ \t]*<%_/gm, "<%_").replace(/_%>[ \t]*/gm, "_%>");
var self = this;
var matches = this.parseTemplateText();
var d = this.opts.delimiter;
var o = this.opts.openDelimiter;
var c = this.opts.closeDelimiter;
if (matches && matches.length) {
matches.forEach(function(line, index) {
var closing;
if (line.indexOf(o + d) === 0 && line.indexOf(o + d + d) !== 0) {
closing = matches[index + 2];
if (!(closing == d + c || closing == "-" + d + c || closing == "_" + d + c)) {
throw new Error('Could not find matching close tag for "' + line + '".');
}
}
self.scanLine(line);
});
}
},
parseTemplateText: function() {
var str = this.templateText;
var pat = this.regex;
var result = pat.exec(str);
var arr = [];
var firstPos;
while (result) {
firstPos = result.index;
if (firstPos !== 0) {
arr.push(str.substring(0, firstPos));
str = str.slice(firstPos);
}
arr.push(result[0]);
str = str.slice(result[0].length);
result = pat.exec(str);
}
if (str) {
arr.push(str);
}
return arr;
},
_addOutput: function(line) {
if (this.truncate) {
line = line.replace(/^(?:\r\n|\r|\n)/, "");
this.truncate = false;
}
if (!line) {
return line;
}
line = line.replace(/\\/g, "\\\\");
line = line.replace(/\n/g, "\\n");
line = line.replace(/\r/g, "\\r");
line = line.replace(/"/g, '\\"');
this.source += ' ; __append("' + line + '")\n';
},
scanLine: function(line) {
var self = this;
var d = this.opts.delimiter;
var o = this.opts.openDelimiter;
var c = this.opts.closeDelimiter;
var newLineCount = 0;
newLineCount = line.split("\n").length - 1;
switch (line) {
case o + d:
case o + d + "_":
this.mode = Template.modes.EVAL;
break;
case o + d + "=":
this.mode = Template.modes.ESCAPED;
break;
case o + d + "-":
this.mode = Template.modes.RAW;
break;
case o + d + "#":
this.mode = Template.modes.COMMENT;
break;
case o + d + d:
this.mode = Template.modes.LITERAL;
this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")\n';
break;
case d + d + c:
this.mode = Template.modes.LITERAL;
this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")\n';
break;
case d + c:
case "-" + d + c:
case "_" + d + c:
if (this.mode == Template.modes.LITERAL) {
this._addOutput(line);
}
this.mode = null;
this.truncate = line.indexOf("-") === 0 || line.indexOf("_") === 0;
break;
default:
if (this.mode) {
switch (this.mode) {
case Template.modes.EVAL:
case Template.modes.ESCAPED:
case Template.modes.RAW:
if (line.lastIndexOf("//") > line.lastIndexOf("\n")) {
line += "\n";
}
}
switch (this.mode) {
// Just executing code
case Template.modes.EVAL:
this.source += " ; " + line + "\n";
break;
// Exec, esc, and output
case Template.modes.ESCAPED:
this.source += " ; __append(escapeFn(" + stripSemi(line) + "))\n";
break;
// Exec and output
case Template.modes.RAW:
this.source += " ; __append(" + stripSemi(line) + ")\n";
break;
case Template.modes.COMMENT:
break;
// Literal <%% mode, append as raw output
case Template.modes.LITERAL:
this._addOutput(line);
break;
}
} else {
this._addOutput(line);
}
}
if (self.opts.compileDebug && newLineCount) {
this.currentLine += newLineCount;
this.source += " ; __line = " + this.currentLine + "\n";
}
}
};
exports.escapeXML = utils.escapeXML;
exports.__express = exports.renderFile;
exports.VERSION = _VERSION_STRING;
exports.name = _NAME;
if (typeof window != "undefined") {
window.ejs = exports;
}
} (ejs$1));
return ejs$1;
}
var ejsExports = requireEjs();
var ejs = /*@__PURE__*/getDefaultExportFromCjs(ejsExports);
const cleanHyperlinks = (input) => (
// When we run in a <ScrollArea> the links break
// Remove OSC 8 hyperlink wrappers but preserve the styled content inside
input.replaceAll(/\u001B]8;;[^\u0007]*\u0007/g, "").replaceAll("\x1B]8;;\x07", "")
);
const getRenderedMarkdown = ({ filename, templateVars, ...options }) => {
setOptions({
renderer: new TerminalRenderer({
...options
})
});
const entrypointPath = fs__default.realpathSync(process.argv[1]);
const root = path__default.dirname(entrypointPath);
const mdPath = path__default.join(root, "..", "assets", "markdown", filename);
const mdTemplate = fs__default.readFileSync(mdPath, "utf8").trim();
const markdown = ejs.render(mdTemplate, templateVars ?? {}, {
filename: mdPath
});
const rendered = parse(markdown).trim();
const cleaned = cleanHyperlinks(rendered);
return cleaned;
};
const Markdown = ({ filename, templateVars, ...options }) => {
const [text, setText] = useState("");
useEffect(() => {
const cleaned = getRenderedMarkdown({ filename, templateVars, ...options });
setText(cleaned);
}, [filename, templateVars, options]);
return /* @__PURE__ */ jsx(Text, { children: text });
};
const CommandContext = React.createContext({
command: null,
setCommand(command) {
}
});
const CommandProvider = (props) => {
const [command, setCommand] = useState(props.command || null);
return /* @__PURE__ */ jsx(CommandContext.Provider, { value: { command, setCommand }, children: props.children });
};
const GameContext = React.createContext({
game: null,
gameId: null,
setGameId(gameId) {
}
});
const GameProvider = ({ children }) => {
const { command } = React.useContext(CommandContext);
const [gameId, setGameId] = useState(command?.getGameId() || null);
const [game, setGame] = useState(null);
const handleGameIdChange = async () => {
if (!gameId) {
setGame(null);
return;
}
const game2 = await getProject(gameId);
setGame(game2);
};
useEffect(() => {
handleGameIdChange();
}, [gameId]);
return /* @__PURE__ */ jsx(GameContext.Provider, { value: { game, gameId, setGameId }, children });
};
scriptDir(import.meta);
const getIsAppFound = (result) => {
const isFound = result?.status === KeyTestStatus.SUCCESS || result?.status === KeyTestStatus.ERROR && result?.error === KeyTestError.NOT_INVITED;
return isFound;
};
const CreateGooglePlayGame = (props) => {
const { gameId } = useContext(GameContext);
return /* @__PURE__ */ jsx(Fragment, { children: gameId && /* @__PURE__ */ jsx(Create, { gameId, ...props }) });
};
const Create = ({ gameId, onComplete, onError, ...boxProps }) => {
const { data: result, isFetching } = useAndroidServiceAccountTestResult({ projectId: gameId });
const { data: builds } = useBuilds({ pageNumber: 0, projectId: gameId });
const previousIsFound = useRef(false);
useEffect(() => {
const isFound = getIsAppFound(result);
if (previousIsFound.current === false && isFound) {
onComplete();
}
previousIsFound.current = isFound;
}, [result]);
useSafeInput(async (input) => {
if (!gameId) return;
switch (input) {
case "r": {
queryClient.invalidateQueries({
queryKey: cacheKeys.androidKeyTestResult({ projectId: gameId })
});
break;
}
case "d": {
const dashUrl = await getShortAuthRequiredUrl(`/games/${getShortUUID(gameId)}/builds`);
await open(dashUrl);
break;
}
}
});
const initialBuild = builds?.data.find(
(build) => build.platform === Platform.ANDROID && build.buildType === BuildType.AAB
);
const downloadCmd = initialBuild ? `${getBuildSummary(initialBuild).cmd}` : "Initial AAB build not found!";
const templateVars = {
dashboardURL: new URL(`/games/${getShortUUID(gameId)}/builds`, WEB_URL).toString(),
downloadCmd
};
return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", gap: 1, ...boxProps, children: [
/* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
/* @__PURE__ */ jsx(Text, { bold: true, children: isFetching ? "Checking..." : "ShipThis has not detected your game in Google Play. Press R to test again." }),
isFetching && /* @__PURE__ */ jsx(Spinner, { type: "dots" })
] }),
/* @__PURE__ */ jsx(Markdown, { filename: "create-google-play-game.md.ejs", templateVars })
] }) });
};
class BaseAuthenticatedCommand extends BaseCommand {
static flags = {};
async init() {
await super.init();
if (!this.isAuthenticated()) {
this.error("No auth config found. Please run `shipthis login` to authenticate.", { exit: 1 });
}
const self = await getSelf();
const accepted = Boolean(self.details?.hasAcceptedTerms);
if (!accepted) {
this.error("You must accept the agreements first. Please run `shipthis login --acceptAgreements` to do this.", {
exit: 1
});
}
const terms = await getTerms();
if (terms.changes.length > 0) {
const warningMD = getRenderedMarkdown({
filename: "agreement-update.md.ejs",
templateVars: {
changes: terms.changes.map((a) => {
return {
...a,
url: new URL(a.path, WEB_URL).toString()
};
})
}
});
console.log(warningMD);
}
}
}
class BaseGameCommand extends BaseAuthenticatedCommand {
static flags = {
...BaseAuthenticatedCommand.flags,
gameId: Flags.string({ char: "g", description: "The ID of the game" })
};
async getGame() {
try {
const gameId = await this.getGameId();
if (!gameId) this.error("No game ID found.");
return await getProject(gameId);
} catch (error) {
if (error?.response?.status === 404) {
this.error("Game not found - please check you have access");
} else throw error;
}
}
async updateGame(update) {
const project = await this.getGame();
const projectUpdate = {
...project,
...update
};
const updatedProject = await updateProject(project.id, projectUpdate);
await this.updateProjectConfig({ project: updatedProject });
return updatedProject;
}
}
export { CreateGooglePlayGame as A, BaseAuthenticatedCommand as B, CommandContext as C, GameContext as G, KeyTestStatus as K, Markdown as M, getRenderedMarkdown as a, getInput as b, BaseGameCommand as c, generatePackageName as d, getJobSummary as e, getJobStatusColor as f, getShortUUID as g, getStageColor as h, CommandProvider as i, GameProvider as j, cacheKeys as k, isValidSemVer as l, makeHumanReadable as m, fetchKeyTestResult as n, niceError as o, KeyTestError as p, ejs as q, getMaskedInput as r, getFileHash as s, getPlatformName as t, useBuilds as u, getBuildSummary as v, useSafeInput as w, useJob as x, getMessageColor as y, queryBuilds as z };