/* eslint-disable @typescript-eslint/no-for-in-array */
///
///
///
///
(global as any).pxt = pxt;
import * as nodeutil from './nodeutil';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as child_process from 'child_process';
import { promisify } from "util";
const chalk = require('chalk');
import U = pxt.Util;
import Cloud = pxt.Cloud;
import Map = pxt.Map;
import * as server from './server';
import * as localrepos from './localrepos';
import * as build from './buildengine';
import * as commandParser from './commandparser';
import * as hid from './hid';
import * as gdb from './gdb';
import * as clidbg from './clidbg';
import * as pyconv from './pyconv';
import * as gitfs from './gitfs';
import * as crowdin from './crowdin';
import * as youtube from './youtube';
import { SUB_WEBAPPS } from './subwebapp';
const rimraf: (f: string, opts: any, cb: (err: Error, res: any) => void) => void = require('rimraf');
// dompurify requires a DOM implementation; sanitize-html does not.
// sanitize-html is a bit more aggressive and culls class names by default from code snippets
// Need to wrap to prevent that. Possibly worth swapping to jsdom + dompurify later for consistency.
pxt.docs.requireDOMSanitizer = () => {
const sanitizeHtml = require("sanitize-html");
const defaults = sanitizeHtml.defaults || {};
const baseAllowedAttrs = defaults.allowedAttributes || {};
const allowedTags = defaults.allowedTags || [];
const mergeClassAttribute = (tag: string, ...otherAttributes: string[]) => {
const existing: string[] = baseAllowedAttrs[tag] || [];
return Array.from(new Set([...existing, "class", ...otherAttributes]));
};
const options = {
...defaults,
allowedTags: [...allowedTags, "img"],
allowedAttributes: {
...baseAllowedAttrs,
code: mergeClassAttribute("code"),
pre: mergeClassAttribute("pre"),
div: mergeClassAttribute("div", "data-youtube", "title"),
img: mergeClassAttribute("img"),
},
};
return (html: string) => sanitizeHtml(html, options);
};
let forceCloudBuild = process.env["KS_FORCE_CLOUD"] !== "no";
let forceLocalBuild = !!process.env["PXT_FORCE_LOCAL"];
let forceBuild = false; // don't use cache
let useCompileServiceDocker = false;
Error.stackTraceLimit = 100;
function parseHwVariant(parsed: commandParser.ParsedCommand) {
let hwvariant = parsed && parsed.flags["hwvariant"] as string;
if (hwvariant) {
// map known variants
const knowVariants: pxt.Map = {
"f4": "stm32f401",
"f401": "stm32f401",
"d5": "samd51",
"d51": "samd51",
"p0": "rpi",
"pi0": "rpi",
"pi": "rpi"
}
hwvariant = knowVariants[hwvariant.toLowerCase()] || hwvariant;
if (!/^hw---/.test(hwvariant)) hwvariant = 'hw---' + hwvariant;
}
return hwvariant;
}
function parseBuildInfo(parsed?: commandParser.ParsedCommand) {
const cloud = parsed && parsed.flags["cloudbuild"];
const local = parsed && parsed.flags["localbuild"];
const useCompService = parsed?.flags["localcompileservice"]
const hwvariant = parseHwVariant(parsed);
forceBuild = parsed && !!parsed.flags["force"];
if (cloud && local)
U.userError("cannot specify local-build and cloud-build together");
if (cloud) {
forceCloudBuild = true;
forceLocalBuild = false;
}
if (local) {
forceCloudBuild = false;
forceLocalBuild = true;
}
if (useCompService) {
forceCloudBuild = false;
forceLocalBuild = true;
useCompileServiceDocker = true;
}
if (hwvariant) {
pxt.log(`setting hardware variant to ${hwvariant}`);
pxt.setHwVariant(hwvariant)
}
}
const p = new commandParser.CommandParser();
function initTargetCommands() {
let cmdsjs = path.join(nodeutil.targetDir, 'built/cmds.js');
if (fs.existsSync(cmdsjs)) {
pxt.debug(`loading cli extensions...`)
let cli = require.main.require(cmdsjs)
if (cli.deployAsync) {
pxt.commands.deployFallbackAsync = cli.deployAsync
}
if (cli.addCommands) {
cli.addCommands(p)
}
}
}
let prevExports = (global as any).savedModuleExports
if (prevExports) {
module.exports = prevExports
}
export interface UserConfig {
localToken?: string;
noAutoBuild?: boolean;
noAutoStart?: boolean;
localBuild?: boolean;
noSerial?: boolean;
}
interface TargetPackageInfo {
options: pxtc.CompileOptions;
api: pxtc.ApisInfo;
sha: string;
}
let reportDiagnostic = reportDiagnosticSimply;
const targetJsPrefix = "var pxtTargetBundle = "
function reportDiagnostics(diagnostics: pxtc.KsDiagnostic[]): void {
for (const diagnostic of diagnostics) {
reportDiagnostic(diagnostic);
}
}
function reportDiagnosticSimply(diagnostic: pxtc.KsDiagnostic): void {
let output = pxtc.getDiagnosticString(diagnostic)
pxt.log(output);
}
function fatal(msg: string): Promise {
pxt.log("Fatal error: " + msg)
throw new Error(msg)
}
export let globalConfig: UserConfig = {}
function homePxtDir() {
return path.join(process.env["HOME"] || process.env["UserProfile"], ".pxt")
}
function cacheDir() {
return path.join(homePxtDir(), "cache")
}
function configPath() {
return path.join(homePxtDir(), "config.json")
}
let homeDirsMade = false
function mkHomeDirs() {
if (homeDirsMade) return
homeDirsMade = true
if (!fs.existsSync(homePxtDir()))
fs.mkdirSync(homePxtDir())
if (!fs.existsSync(cacheDir()))
fs.mkdirSync(cacheDir())
}
function saveConfig() {
mkHomeDirs()
nodeutil.writeFileSync(configPath(), JSON.stringify(globalConfig, null, 4) + "\n")
}
function initConfigAsync(): Promise {
let p = Promise.resolve();
let atok: string = process.env["PXT_ACCESS_TOKEN"]
if (fs.existsSync(configPath())) {
let config = readJson(configPath())
globalConfig = config;
}
p.then(() => {
if (atok) {
let mm = /^(https?:.*)\?access_token=([\w\-\.]+)/.exec(atok)
if (!mm) {
console.error("Invalid accessToken format, expecting something like 'https://example.com/?access_token=0.abcd.XXXX'")
return
}
Cloud.apiRoot = mm[1].replace(/\/$/, "").replace(/\/api$/, "") + "/api/"
Cloud.accessToken = mm[2]
}
});
return p;
}
function loadGithubToken() {
if (!pxt.github.token)
pxt.github.token = process.env["GITHUB_ACCESS_TOKEN"] || process.env["GITHUB_TOKEN"];
pxt.github.db = new FileGithubDb(pxt.github.db);
}
/**
* Caches github releases under pxt_modules/.githubcache/...
*/
class FileGithubDb implements pxt.github.IGithubDb {
constructor(public readonly db: pxt.github.IGithubDb) {
}
private loadAsync(repopath: string, tag: string, suffix: string,
loader: (r: string, t: string) => Promise): Promise {
// only cache releases
if (!/^v\d+\.\d+\.\d+$/.test(tag))
return loader(repopath, tag);
const dir = path.join(`pxt_modules`, `.githubcache`, ...repopath.split(/\//g), tag);
const fn = path.join(dir, suffix + ".json");
// cache hit
if (fs.existsSync(fn)) {
const json = fs.readFileSync(fn, "utf8");
const p = pxt.Util.jsonTryParse(json) as T;
if (p) {
pxt.debug(`cache hit ${fn}`)
return Promise.resolve(p);
}
}
// download and cache
return loader(repopath, tag)
.then(p => {
if (p) {
pxt.debug(`cached ${fn}`)
nodeutil.mkdirP(dir);
fs.writeFileSync(fn, JSON.stringify(p), "utf8");
}
return p;
})
}
latestVersionAsync(repopath: string, config: pxt.PackagesConfig): Promise {
return this.db.latestVersionAsync(repopath, config)
}
loadConfigAsync(repopath: string, tag: string): Promise {
return this.loadAsync(repopath, tag, "pxt", (r, t) => this.db.loadConfigAsync(r, t));
}
loadPackageAsync(repopath: string, tag: string, fallbackPackageFiles?: pxt.Map): Promise {
return this.loadAsync(repopath, tag, "pkg", (r, t) => this.db.loadPackageAsync(r, t, fallbackPackageFiles));
}
loadTutorialMarkdown(repopath: string, tag?: string): Promise {
return this.loadAsync(repopath, tag, "tutorial", (r, t) => this.db.loadTutorialMarkdown(r, t));
}
cacheReposAsync(resp: pxt.github.GHTutorialResponse) {
return this.db.cacheReposAsync(resp);
}
}
function searchAsync(...query: string[]) {
return pxt.packagesConfigAsync()
.then(config => pxt.github.searchAsync(query.join(" "), config))
.then(res => {
for (let r of res) {
console.log(`${r.fullName}: ${r.description}`)
}
})
}
export function pokeRepoAsync(parsed: commandParser.ParsedCommand): Promise {
const repo = parsed.args[0];
let data = {
repo: repo,
getkey: false
}
if (parsed.flags["u"]) data.getkey = true
return Cloud.privatePostAsync("pokerepo", data)
.then(resp => {
console.log(resp)
})
}
export function apiAsync(path: string, postArguments?: string): Promise {
if (postArguments == "delete") {
return Cloud.privateDeleteAsync(path)
.then(resp => console.log(resp))
}
if (postArguments == "-") {
return nodeutil.readResAsync(process.stdin)
.then(buf => buf.toString("utf8"))
.then(str => apiAsync(path, str))
}
if (postArguments && fs.existsSync(postArguments))
postArguments = fs.readFileSync(postArguments, "utf8");
let dat = postArguments ? JSON.parse(postArguments) : null
if (dat)
console.log("POST", "/api/" + path, JSON.stringify(dat, null, 2))
return Cloud.privateRequestAsync({
url: path,
data: dat
})
.then(resp => {
if (resp.json)
console.log(JSON.stringify(resp.json, null, 2))
else console.log(resp.text)
})
}
function uploadFileAsync(parsed: commandParser.ParsedCommand) {
const path = parsed.args[0];
let buf = fs.readFileSync(path)
let mime = U.getMime(path)
console.log("Upload", path)
return Cloud.privatePostAsync("upload/files", {
filename: path,
encoding: "base64",
content: buf.toString("base64"),
contentType: mime
})
.then(resp => {
console.log(resp)
})
}
let readlineCount = 0
function readlineAsync() {
process.stdin.resume();
process.stdin.setEncoding('utf8');
readlineCount++
return new Promise((resolve, reject) => {
process.stdin.once('data', (text: string) => {
resolve(text)
})
})
}
export function queryAsync(msg: string, defl: string) {
process.stdout.write(`${msg} [${defl}]: `)
return readlineAsync()
.then(text => {
text = text.trim()
if (!text) return defl
else return text
})
}
export function yesNoAsync(msg: string): Promise {
process.stdout.write(msg + " (y/n): ")
return readlineAsync()
.then(text => {
if (text.trim().toLowerCase() == "y")
return Promise.resolve(true)
else if (text.trim().toLowerCase() == "n")
return Promise.resolve(false)
else return yesNoAsync(msg)
})
}
function onlyExts(files: string[], exts: string[]) {
return files.filter(f => exts.indexOf(path.extname(f)) >= 0)
}
function pxtFileList(pref: string) {
let allFiles = nodeutil.allFiles(pref + "webapp/public")
.concat(onlyExts(nodeutil.allFiles(pref + "built/web", { maxDepth: 1 }), [".js", ".css"]))
.concat(nodeutil.allFiles(pref + "built/web/fonts", { maxDepth: 1 }))
.concat(nodeutil.allFiles(pref + "built/web/vs", { maxDepth: 4 }));
for (const subapp of SUB_WEBAPPS) {
allFiles = allFiles.concat(nodeutil.allFiles(pref + `built/web/${subapp.name}`, { maxDepth: 4 }))
}
return allFiles;
}
function checkIfTaggedCommitAsync() {
return nodeutil.gitInfoAsync(["tag", "--points-at", "HEAD"])
.then(info => {
return info
.split("\n")
.some(tag => /^v\d+\.\d+\.\d+$/.test(tag.trim()));
});
}
let readJson = nodeutil.readJson;
async function ciAsync(parsed?: commandParser.ParsedCommand) {
const intentToPublish = parsed && parsed.flags["publish"];
const tagOverride = parsed && parsed.flags["tag"] as string;
forceCloudBuild = true;
const buildInfo = await ciBuildInfoAsync();
pxt.log(`ci build using ${buildInfo.ci}`);
if (!buildInfo.tag)
buildInfo.tag = "";
if (!buildInfo.branch)
buildInfo.branch = "local"
let { tag, branch, pullRequest } = buildInfo
if (tagOverride) {
tag = tagOverride;
pxt.log(`overriding tag to ${tag}`);
}
const npmPublish = (intentToPublish || /^v\d+\.\d+\.\d+$/.exec(tag)) && process.env.NPM_PUBLISH;
if (npmPublish) {
pxt.log(`npm publish is true`)
} else if (intentToPublish) {
pxt.log("not publishing, no tag or access token")
}
process.env["PXT_ENV"] = "production";
const latest = branch == "master" ? "latest" : "git-" + branch
// upload locs on build on master
const masterOrReleaseBranchRx = /^(master|v\d+\.\d+\.\d+)$/;
const apiStringBranchRx = pxt.appTarget.uploadApiStringsBranchRx
? new RegExp(pxt.appTarget.uploadApiStringsBranchRx)
: masterOrReleaseBranchRx;
const uploadDocs = !pullRequest
&& !!pxt.appTarget.uploadDocs
&& masterOrReleaseBranchRx.test(branch);
const uploadApiStrings = !pullRequest
&& (!!pxt.appTarget.uploadDocs || pxt.appTarget.uploadApiStringsBranchRx)
&& apiStringBranchRx.test(branch);
pxt.log(`tag: ${tag}`);
pxt.log(`branch: ${branch}`);
pxt.log(`latest: ${latest}`);
pxt.log(`pull request: ${pullRequest}`);
pxt.log(`upload api strings: ${uploadApiStrings}`);
pxt.log(`upload docs: ${uploadDocs}`);
lintJSONInDirectory(path.resolve("."));
lintJSONInDirectory(path.resolve("docs"));
let pkg = readJson("package.json")
async function npmPublishAsync() {
if (!npmPublish) return Promise.resolve();
let latest: pxt.semver.Version;
try {
const version = await nodeutil.npmLatestVersionAsync(pkg["name"]);
latest = pxt.semver.parse(version);
}
catch (e) {
// no latest tag
}
let distTag: string;
if (latest) {
const current = pxt.semver.parse(pkg["version"]);
if (pxt.semver.cmp(current, latest) < 0) {
distTag = `stable${current.major}.${current.minor}`;
}
}
if (distTag) {
return nodeutil.runNpmAsync("publish", "--tag", distTag);
}
return nodeutil.runNpmAsync("publish");
}
if (pkg["name"] == "pxt-core") {
pxt.log("pxt-core build");
const isTaggedCommit = await checkIfTaggedCommitAsync();
pxt.log(`is tagged commit: ${isTaggedCommit}`);
await npmPublishAsync();
if (branch === "master" && (intentToPublish || isTaggedCommit)) {
if (uploadDocs) {
await buildWebStringsAsync();
await crowdin.uploadBuiltStringsAsync("built/webstrings.json");
for (const subapp of SUB_WEBAPPS) {
await crowdin.uploadBuiltStringsAsync(`built/${subapp.name}-strings.json`);
}
}
if (uploadApiStrings) {
await crowdin.uploadBuiltStringsAsync("built/strings.json");
}
if (uploadDocs || uploadApiStrings) {
await crowdin.internalUploadTargetTranslationsAsync(uploadApiStrings, uploadDocs);
pxt.log("translations uploaded");
}
else {
pxt.log("skipping translations upload");
}
}
} else {
pxt.log("target build");
await internalBuildTargetAsync();
await internalCheckDocsAsync(true);
await blockTestsAsync();
await npmPublishAsync();
if (!process.env["PXT_ACCESS_TOKEN"]) {
// pull request, don't try to upload target
pxt.log('no token, skipping upload')
return;
}
const trg = readLocalPxTarget();
const label = `${trg.id}/${tag || latest}`;
pxt.log(`uploading target with label ${label}...`);
await uploadTargetAsync(label);
pxt.log("target uploaded");
if (uploadDocs || uploadApiStrings) {
await crowdin.internalUploadTargetTranslationsAsync(uploadApiStrings, uploadDocs);
pxt.log("translations uploaded");
} else {
pxt.log("skipping translations upload");
}
}
}
function lintJSONInDirectory(dir: string) {
for (const file of fs.readdirSync(dir)) {
const fullPath = path.join(dir, file);
if (file.endsWith(".json")) {
const contents = fs.readFileSync(fullPath, "utf8");
try {
JSON.parse(contents)
}
catch (e) {
console.log("Could not parse " + fullPath)
process.exit(1);
}
}
}
}
function bumpPxtCoreDepAsync(): Promise {
let pkg = readJson("package.json")
if (pkg["name"] == "pxt-core") return Promise.resolve(pkg)
let gitPull = Promise.resolve();
let commitMsg: string = "";
["pxt-core", "pxt-common-packages"].forEach(knownPackage => {
const modulePath = path.join("node_modules", knownPackage)
if (fs.existsSync(path.join(modulePath, ".git"))) {
gitPull = gitPull.then(() => nodeutil.spawnAsync({
cmd: "git",
args: ["pull"],
cwd: modulePath
}))
}
// not referenced
if (!fs.existsSync(path.join(modulePath, "package.json")))
return;
gitPull
.then(() => {
let kspkg = readJson(path.join(modulePath, "package.json"));
let currVer = pkg["dependencies"][knownPackage]
if (!currVer) return; // not referenced
let newVer = kspkg["version"]
if (currVer == newVer) {
console.log(`Referenced ${knownPackage} dep up to date: ${currVer}`)
return;
}
console.log(`Bumping ${knownPackage} dep version: ${currVer} -> ${newVer}`)
if (currVer != "*" && pxt.semver.strcmp(currVer, newVer) > 0) {
U.userError(`Trying to downgrade ${knownPackage}.`)
}
if (currVer != "*" && pxt.semver.majorCmp(currVer, newVer) < 0) {
U.userError(`Trying to automatically update major version, please edit package.json manually.`)
}
pkg["dependencies"][knownPackage] = newVer
nodeutil.writeFileSync("package.json", nodeutil.stringify(pkg) + "\n")
commitMsg += `${commitMsg ? ", " : ""}bump ${knownPackage} to ${newVer}`;
})
})
gitPull = gitPull
.then(() => commitMsg ? nodeutil.runGitAsync("commit", "-m", commitMsg, "--", "package.json") : Promise.resolve());
return gitPull;
}
function updateAsync() {
return Promise.resolve()
.then(() => nodeutil.runGitAsync("pull"))
.then(() => bumpPxtCoreDepAsync())
.then(() => nodeutil.runNpmAsync("install"));
}
async function justBumpPkgAsync(bumpType: "patch" | "major" | "minor" | string, tagCommit: boolean = true): Promise {
ensurePkgDir()
await nodeutil.needsGitCleanAsync();
await mainPkg.loadAsync();
const curVer = pxt.semver.parse(mainPkg.config.version);
const newVer = pxt.semver.bump(curVer, bumpType);
mainPkg.config.version = await queryAsync("New version", pxt.semver.stringify(newVer));
mainPkg.saveConfig();
await nodeutil.runGitAsync("commit", "-a", "-m", mainPkg.config.version);
if (tagCommit) { await nodeutil.runGitAsync("tag", "v" + mainPkg.config.version); }
return mainPkg.config.version;
}
function tagReleaseAsync(parsed: commandParser.ParsedCommand) {
const tag = parsed.args[0] as string;
const version = parsed.args[1] as string;
const npm = !!parsed.flags["npm"];
// check that ...-ref.json exists for that tag
const fn = path.join('docs', tag + "-ref.json");
pxt.log(`checking ${fn}`)
if (!fn)
U.userError(`file ${fn} does not exist`);
const v = pxt.semver.normalize(version);
const npmPkg = `pxt-${pxt.appTarget.id}`;
if (!pxt.appTarget.appTheme.githubUrl)
U.userError('pxtarget theme missing "githubUrl" entry');
// check that tag exists in github
pxt.log(`checking github ${pxt.appTarget.appTheme.githubUrl} tag v${v}`);
return U.requestAsync({
url: pxt.appTarget.appTheme.githubUrl.replace(/\/$/, '') + "/releases/tag/v" + v,
method: "GET"
})
// check that release exists in npm
.then(() => {
if (!npm) return Promise.resolve();
pxt.log(`checking npm ${npmPkg} release`)
return nodeutil.npmRegistryAsync(npmPkg)
.then(registry => {
// verify that npm version exists
if (!registry.versions[v])
U.userError(`cannot find npm package ${npmPkg}@${v}`);
const npmTag = tag == "index" ? "latest" : tag;
return nodeutil.runNpmAsync(`dist-tag`, `add`, `${npmPkg}@v${v}`, npmTag);
})
})
// all good update ref file
.then(() => {
// update index file
nodeutil.writeFileSync(fn, JSON.stringify({
"appref": "v" + v
}, null, 4))
// TODO commit changes
console.log(`please commit ${fn} changes`);
})
}
async function bumpAsync(parsed?: commandParser.ParsedCommand) {
const bumpPxt = parsed && parsed.flags["update"];
const upload = parsed && parsed.flags["upload"];
let pr = parsed && parsed.flags["pr"];
let nopr = parsed && parsed.flags["nopr"];
let bumpType = parsed && parsed.flags["version"] as string;
if (!bumpType) bumpType = "patch";
if (bumpType.startsWith("v")) bumpType = bumpType.slice(1);
let currBranchName = "";
let token = "";
let user = "";
let owner = "";
let repo = "";
let branchProtected = false;
try {
currBranchName = await nodeutil.getCurrentBranchNameAsync();
token = await nodeutil.getGitHubTokenAsync();
user = await nodeutil.getGitHubUserAsync(token);
({ owner, repo } = await nodeutil.getGitHubOwnerAndRepoAsync());
branchProtected = await nodeutil.isBranchProtectedAsync(token, owner, repo, currBranchName);
if (branchProtected) {
console.log(chalk.yellow(`Branch ${currBranchName} is protected.`));
pr = true;
}
} catch (e) {
console.warn(chalk.yellow("Unable to determine branch protection status."), e.message);
pr = true;
}
if (nopr) {
pr = false;
}
if (pr && (!currBranchName || !token || !user || !owner || !repo)) {
U.userError("Unable to prepare a bump pull request. Check GitHub credentials and the origin URL, or explicitly use --nopr for a direct push.");
}
if (fs.existsSync(pxt.CONFIG_NAME)) {
if (upload) {
U.userError("upload only supported on targets");
}
if (pr) {
console.log("Bumping via pull request.");
const newBranchName = `${user}/pxt-bump-${nodeutil.timestamp()}`;
return Promise.resolve()
.then(() => nodeutil.needsGitCleanAsync())
.then(() => nodeutil.runGitAsync("pull"))
.then(() => nodeutil.createBranchAsync(newBranchName))
.then(() => justBumpPkgAsync(bumpType, false)) // don't tag when creating a PR
.then((version) => nodeutil.gitPushAsync(false).then(() => version))
.then((version) => nodeutil.createPullRequestAsync({
title: `[pxt-cli] bump version to ${version}`,
body: "__Do not edit the PR title.__\n" +
"It was automatically generated by `pxt bump` and must follow a specific pattern.\n" +
"GitHub workflows rely on it to trigger version tagging and publishing to npm.",
head: newBranchName,
base: currBranchName,
token,
owner,
repo,
}))
.then((prUrl) => nodeutil.switchBranchAsync(currBranchName).then(() => prUrl))
.then((prUrl) => console.log(`${chalk.green('PR created:')} ${chalk.green.underline(prUrl)}`))
} else {
console.log("Bumping via direct push.");
return Promise.resolve()
.then(() => nodeutil.runGitAsync("pull"))
.then(() => justBumpPkgAsync(bumpType))
.then(() => nodeutil.runGitAsync("push", "--atomic", "--follow-tags"))
}
}
else if (fs.existsSync("pxtarget.json"))
if (pr) {
console.log("Bumping via pull request.");
const newBranchName = `${user}/pxt-bump-${nodeutil.timestamp()}`;
return Promise.resolve()
.then(() => nodeutil.needsGitCleanAsync())
.then(() => nodeutil.runGitAsync("pull"))
.then(() => nodeutil.createBranchAsync(newBranchName))
.then(() => bumpPxt ? bumpPxtCoreDepAsync() : Promise.resolve())
.then(() => nodeutil.npmVersionBumpAsync(bumpType, false)) // don't tag when creating a PR
.then((version) => nodeutil.gitPushAsync(false).then(() => version))
.then((version) => nodeutil.createPullRequestAsync({
title: `[pxt-cli] bump version to ${version}`,
body: "__Do not edit the PR title.__\n" +
"It was automatically generated by `pxt bump` and must follow a specific pattern.\n" +
"GitHub workflows rely on it to trigger version tagging and publishing to npm.",
head: newBranchName,
base: currBranchName,
token,
owner,
repo,
}))
.then((prUrl) => nodeutil.switchBranchAsync(currBranchName).then(() => prUrl))
.then((prUrl) => console.log(`${chalk.green('PR created:')} ${chalk.green.underline(prUrl)}`))
} else {
console.log("Bumping via direct push.");
return Promise.resolve()
.then(() => nodeutil.runGitAsync("pull"))
.then(() => bumpPxt ? bumpPxtCoreDepAsync().then(() => nodeutil.runGitAsync("push", "--atomic", "--no-follow-tags")) : Promise.resolve())
.then(() => nodeutil.runNpmAsync("version", bumpType))
.then(() => nodeutil.runGitAsync("push", "--atomic", "--follow-tags"))
.then(() => upload ? uploadTaggedTargetAsync() : Promise.resolve())
}
else {
U.userError("Couldn't find package or target JSON file; nothing to bump")
}
}
function uploadTaggedTargetAsync() {
forceCloudBuild = true
if (!pxt.github.token) {
fatal("GitHub token not found, please use 'pxt login' to login with your GitHub account to push releases.");
return Promise.resolve();
}
return nodeutil.needsGitCleanAsync()
.then(() => Promise.all([
nodeutil.currGitTagAsync(),
nodeutil.gitInfoAsync(["rev-parse", "--abbrev-ref", "HEAD"]),
nodeutil.gitInfoAsync(["rev-parse", "HEAD"])
]))
// only build target after getting all the info
.then(info =>
internalBuildTargetAsync()
.then(() => internalCheckDocsAsync(true))
.then(() => info))
.then(async info => {
const repoSlug = "microsoft/pxt-" + pxt.appTarget.id
setCiBuildInfo(info[0], info[1], info[2], repoSlug)
process.env['PXT_RELEASE_REPO'] = "https://git:" + pxt.github.token + "@github.com/" + repoSlug + "-built"
let v = await pkgVersionAsync()
pxt.log("uploading " + v)
return uploadCoreAsync({
label: "v" + v,
fileList: pxtFileList("node_modules/pxt-core/").concat(targetFileList()),
pkgversion: v,
githubOnly: true,
fileContent: {}
})
})
}
async function pkgVersionAsync() {
let ver = readJson("package.json")["version"]
const info = await ciBuildInfoAsync()
if (!info.tag)
ver += "-" + (info.commit ? info.commit.slice(0, 6) : "local")
return ver
}
function targetFileList() {
let lst = onlyExts(nodeutil.allFiles("built"), [".js", ".css", ".json", ".webmanifest"])
.concat(nodeutil.allFiles(path.join(simDir(), "public")));
if (simDir() != "sim")
lst = lst.concat(nodeutil.allFiles(path.join("sim", "public"), { maxDepth: 5, allowMissing: true }))
pxt.debug(`target files (on disk): ${lst.join('\r\n ')}`)
return lst;
}
async function uploadTargetAsync(label: string) {
return uploadCoreAsync({
label,
fileList: pxtFileList("node_modules/pxt-core/").concat(targetFileList()),
pkgversion: await pkgVersionAsync(),
fileContent: {}
})
}
export function uploadTargetReleaseAsync(parsed?: commandParser.ParsedCommand) {
parseBuildInfo(parsed);
const label = parsed.args[0];
const rebundle = !!parsed.flags["rebundle"];
return (rebundle ? rebundleAsync() : internalBuildTargetAsync())
.then(() => {
return uploadTargetAsync(label);
});
}
export function uploadTargetRefsAsync(repoPath: string) {
if (repoPath) process.chdir(repoPath);
return nodeutil.needsGitCleanAsync()
.then(() => Promise.all([
nodeutil.gitInfoAsync(["rev-parse", "HEAD"]),
nodeutil.gitInfoAsync(["config", "--get", "remote.origin.url"])
]))
.then(info => {
return gitfs.uploadRefs(info[0], info[1])
.then(() => {
return Promise.resolve();
});
})
}
interface UploadOptions {
fileList: string[];
pkgversion: string;
fileContent?: Map;
label?: string
legacyLabel?: boolean;
target?: string;
localDir?: string;
githubOnly?: boolean;
builtPackaged?: string;
minify?: boolean;
noAppCache?: boolean;
}
interface BlobReq {
hash: string;
content: string;
encoding: string;
filename: string; // comment only
size: number; // ditto
}
type GitTree = Map;
interface GitEntry {
hash?: string;
subtree?: GitTree;
}
interface CommitInfo {
tree: GitTree;
parents: string[];
message: string;
target: string;
}
function uploadFileName(p: string) {
// normalize /, \ before filtering
return p.replace(/\\/g, '\/')
.replace(/^.*(built\/web\/|\w+\/public\/|built\/)/, "")
}
function gitUploadAsync(opts: UploadOptions, uplReqs: Map) {
let reqs = U.unique(U.values(uplReqs), r => r.hash)
console.log("Asking for", reqs.length, "hashes")
return Promise.resolve()
.then(() => Cloud.privatePostAsync("upload/status", {
hashes: reqs.map(r => r.hash)
}))
.then(resp => {
let missing = U.toDictionary(resp.missing as string[], s => s)
let missingReqs = reqs.filter(r => !!U.lookup(missing, r.hash))
let size = 0
for (let r of missingReqs) size += r.size
console.log("files missing: ", missingReqs.length, size, "bytes")
return U.promiseMapAll(missingReqs,
r => Cloud.privatePostAsync("upload/blob", r)
.then(() => {
console.log(r.filename + ": OK," + r.size + " " + r.hash)
}))
})
.then(async () => {
let roottree: Map = {}
let get = (tree: GitTree, path: string): GitEntry => {
let subt = U.lookup(tree, path)
if (!subt)
subt = tree[path] = {}
return subt
}
let lookup = (tree: GitTree, path: string): GitEntry => {
let m = /^([^\/]+)\/(.*)/.exec(path)
if (m) {
let subt = get(tree, m[1])
U.assert(!subt.hash)
if (!subt.subtree) subt.subtree = {}
return lookup(subt.subtree, m[2])
} else {
return get(tree, path)
}
}
for (let fn of Object.keys(uplReqs)) {
let e = lookup(roottree, fn)
e.hash = uplReqs[fn].hash
}
const info = await ciBuildInfoAsync()
let data: CommitInfo = {
message: "Upload from " + info.commitUrl,
parents: [],
target: pxt.appTarget.id,
tree: roottree,
}
console.log("Creating commit...")
return Cloud.privatePostAsync("upload/commit", data)
})
.then(res => {
console.log("Commit:", res)
return uploadToGitRepoAsync(opts, uplReqs)
})
}
async function uploadToGitRepoAsync(opts: UploadOptions, uplReqs: Map) {
if (process.env["PXT_SKIP_GIT_COMMIT"]) {
return writeFilesToPushAsync(opts, uplReqs);
}
let label = opts.label
if (!label) {
console.log('no label; skip release upload');
return Promise.resolve();
}
let tid = pxt.appTarget.id
if (U.startsWith(label, tid + "/"))
label = label.slice(tid.length + 1)
if (!/^v\d/.test(label)) {
console.log(`label "${label}" is not a version; skipping release upload`);
return Promise.resolve();
}
let repoUrl = process.env["PXT_RELEASE_REPO"]
if (!repoUrl) {
console.log("no $PXT_RELEASE_REPO variable; not uploading label " + label)
return Promise.resolve()
}
nodeutil.mkdirP("tmp")
let trgPath = "tmp/releases"
let mm = /^https:\/\/([^:]+):([^@]+)@([^\/]+)(.*)/.exec(repoUrl)
if (!mm) {
U.userError("wrong format for $PXT_RELEASE_REPO")
}
console.log(`create release ${label} in ${repoUrl}`);
let user = mm[1]
let pass = mm[2]
let host = mm[3]
let netRcLine = `machine ${host} login ${user} password ${pass}\n`
repoUrl = `https://${user}@${host}${mm[4]}`
let homePath = process.env["HOME"] || process.env["UserProfile"]
let netRcPath = path.join(homePath, /^win/.test(process.platform) ? "_netrc" : ".netrc")
let prevNetRc = fs.existsSync(netRcPath) ? fs.readFileSync(netRcPath, "utf8") : null
let newNetRc = prevNetRc ? prevNetRc + "\n" + netRcLine : netRcLine
console.log("Adding credentials to " + netRcPath)
fs.writeFileSync(netRcPath, newNetRc, {
encoding: "utf8",
mode: '600'
})
let cuser = process.env["USER"] || ""
if (cuser && !/travis/.test(cuser))
user += "-" + cuser
const cred = [
"-c", "credential.helper=",
"-c", "user.name=" + user,
"-c", "user.email=" + user + "@build.pxt.io",
]
const gitAsync = (args: string[]) => nodeutil.spawnAsync({
cmd: "git",
cwd: trgPath,
args: cred.concat(args)
})
const info = await ciBuildInfoAsync()
return Promise.resolve()
.then(() => {
if (fs.existsSync(trgPath)) {
let cfg = fs.readFileSync(trgPath + "/.git/config", "utf8")
if (cfg.indexOf("url = " + repoUrl) > 0) {
return gitAsync(["pull", "--depth=3"])
} else {
U.userError(trgPath + " already exists; please remove it")
}
} else {
return nodeutil.spawnAsync({
cmd: "git",
args: cred.concat(["clone", "--depth", "3", repoUrl, trgPath]),
cwd: "."
})
}
})
.then(() => {
for (let u of U.values(uplReqs)) {
let fpath = path.join(trgPath, u.filename)
nodeutil.mkdirP(path.dirname(fpath))
fs.writeFileSync(fpath, u.content, { encoding: u.encoding })
}
// make sure there's always something to commit
fs.writeFileSync(trgPath + "/stamp.txt", new Date().toString())
})
.then(() => gitAsync(["add", "."]))
.then(() => gitAsync(["commit", "-m", "Release " + label + " from " + info.commitUrl]))
.then(() => gitAsync(["tag", label]))
.then(() => gitAsync(["push"]))
.then(() => gitAsync(["push", "--tags"]))
.then(() => {
})
.finally(() => {
if (prevNetRc == null) {
console.log("Removing " + netRcPath)
fs.unlinkSync(netRcPath)
} else {
console.log("Restoring " + netRcPath)
fs.writeFileSync(netRcPath, prevNetRc, {
mode: '600'
})
}
})
}
async function writeFilesToPushAsync(opts: UploadOptions, uplReqs: Map) {
let label = opts.label
if (!label) {
console.log('no label; skip release upload');
return Promise.resolve();
}
let tid = pxt.appTarget.id
if (U.startsWith(label, tid + "/"))
label = label.slice(tid.length + 1)
if (!/^v\d/.test(label)) {
console.log(`label "${label}" is not a version; skipping release upload`);
return Promise.resolve();
}
const releasesDir = path.resolve("tmp/releases")
const outDir = path.join(releasesDir, "built");
console.log("writing release files to " + releasesDir)
nodeutil.mkdirP(outDir);
const info = await ciBuildInfoAsync();
const releaseInfo = {
url: info.commitUrl,
tag: label
};
// this gets read by the github actions workflow
fs.writeFileSync(path.join(releasesDir, "release.json"), JSON.stringify(releaseInfo, null, 2), { encoding: "utf8" });
// copy the files into the built directory. the actual push to the git repo will be
// handled by the github actions workflow
for (let u of U.values(uplReqs)) {
let fpath = path.join(outDir, u.filename)
nodeutil.mkdirP(path.dirname(fpath))
fs.writeFileSync(fpath, u.content, { encoding: u.encoding })
}
// make sure there's always something to commit
fs.writeFileSync(path.join(outDir, "stamp.txt"), new Date().toString())
}
function uploadedArtFileCdnUrl(fn: string): string {
if (!fn || /^(https?|data):/.test(fn)) return fn; // nothing to do
fn = fn.replace(/^\.?\/*/, "/")
const cdnBlobUrl = "@cdnUrl@/blob/" + gitHash(fs.readFileSync("docs" + fn)) + "" + fn;
return cdnBlobUrl;
}
function gitHash(buf: Buffer) {
let hash = crypto.createHash("sha1")
hash.update(Buffer.from("blob " + buf.length + "\u0000", "utf8"))
hash.update(buf)
return hash.digest("hex")
}
function uploadCoreAsync(opts: UploadOptions) {
const targetConfig = readLocalPxTarget();
const defaultLocale = targetConfig.appTheme.defaultLocale;
const hexCache = path.join("built", "hexcache");
let hexFiles: string[] = [];
if (fs.existsSync(hexCache)) {
hexFiles = fs.readdirSync(hexCache)
.filter(f => /\.hex$/.test(f))
.filter(f => fs.readFileSync(path.join(hexCache, f), { encoding: "utf8" }) != "SKIP")
.map((f) => `@cdnUrl@/compile/${f}`);
pxt.log(`hex cache:\n\t${hexFiles.join('\n\t')}`)
}
const targetUsedImages: pxt.Map = {};
const cdnCachedAppTheme = replaceStaticImagesInJsonBlob(readLocalPxTarget(), fn => {
const fp = path.join("docs", fn);
if (!targetUsedImages[fn] && !opts.fileList.includes(fp)) {
opts.fileList.push(fp);
}
targetUsedImages[fn] = uploadedArtFileCdnUrl(fn);
return targetUsedImages[fn];
}).appTheme;
const targetImagePaths = Object.keys(targetUsedImages);
const targetImagesHashed = Object.values(targetUsedImages);
let targetEditorJs = "";
if (pxt.appTarget.appTheme?.extendEditor)
targetEditorJs = "@commitCdnUrl@editor.js";
let targetFieldEditorsJs = "";
if (pxt.appTarget.appTheme?.extendFieldEditors)
targetFieldEditorsJs = "@commitCdnUrl@fieldeditors.js";
let targetScriptPageJs = "";
if (pxt.appTarget.appTheme?.extendScriptPage)
targetScriptPageJs = "@commitCdnUrl@scriptPage.js";
let replacements: Map = {
"/sim/simulator.html": "@simUrl@",
"/sim/siminstructions.html": "@partsUrl@",
"/sim/sim.webmanifest": "@relprefix@webmanifest",
"/embed.js": "@targetUrl@@relprefix@embed",
"/cdn/": "@commitCdnUrl@",
"/doccdn/": "@commitCdnUrl@",
"/sim/": "@commitCdnUrl@",
"/blb/": "@blobCdnUrl@",
"/trgblb/": "@targetBlobUrl@",
"@timestamp@": "",
"data-manifest=\"\"": "@manifest@",
"var pxtConfig = null": "var pxtConfig = @cfg@",
"var pxtConfig=null": "var pxtConfig = @cfg@",
"@defaultLocaleStrings@": defaultLocale ? "@commitCdnUrl@" + "locales/" + defaultLocale + "/strings.json" : "",
"@cachedHexFiles@": hexFiles.length ? hexFiles.join("\n") : "",
"@cachedHexFilesEncoded@": encodeURLs(hexFiles),
"@targetEditorJs@": targetEditorJs,
"@targetFieldEditorsJs@": targetFieldEditorsJs,
"@targetScriptPageJs@": targetScriptPageJs,
"@targetImages@": targetImagesHashed.length ? targetImagesHashed.join('\n') : '',
"@targetImagesEncoded@": targetImagesHashed.length ? encodeURLs(targetImagesHashed) : ""
}
if (opts.localDir) {
let cfg: Partial = {
"relprefix": opts.localDir,
"verprefix": "",
"workerjs": opts.localDir + "worker.js",
"monacoworkerjs": opts.localDir + "monacoworker.js",
"gifworkerjs": opts.localDir + "gifjs/gif.worker.js",
"serviceworkerjs": opts.localDir + "serviceworker.js",
"typeScriptWorkerJs": opts.localDir + "tsworker.js",
"pxtVersion": pxtVersion(),
"pxtRelId": "localDirRelId",
"pxtCdnUrl": opts.localDir,
"commitCdnUrl": opts.localDir,
"blobCdnUrl": opts.localDir,
"cdnUrl": opts.localDir,
"targetVersion": opts.pkgversion,
"targetRelId": "",
"targetUrl": "",
"targetId": opts.target,
"simUrl": opts.localDir + "simulator.html",
"simserviceworkerUrl": opts.localDir + "simulatorserviceworker.js",
"simworkerconfigUrl": opts.localDir + "workerConfig.js",
"partsUrl": opts.localDir + "siminstructions.html",
"runUrl": opts.localDir + "run.html",
"docsUrl": opts.localDir + "docs.html",
"multiUrl": opts.localDir + "multi.html",
"asseteditorUrl": opts.localDir + "asseteditor.html",
"isStatic": true,
}
for (const subapp of SUB_WEBAPPS) {
(cfg as any)[subapp.name + "Url"] = opts.localDir + subapp.name + ".html";
}
const targetImageLocalPaths = targetImagePaths.map(k =>
`${opts.localDir}${path.join('./docs', k)}`);
replacements = {
"/embed.js": opts.localDir + "embed.js",
"/cdn/": opts.localDir,
"/doccdn/": opts.localDir,
"/sim/": opts.localDir,
"/blb/": opts.localDir,
"/trgblb/": opts.localDir,
"@monacoworkerjs@": `${opts.localDir}monacoworker.js`,
"@gifworkerjs@": `${opts.localDir}gifjs/gif.worker.js`,
"@workerjs@": `${opts.localDir}worker.js`,
"@serviceworkerjs@": `${opts.localDir}serviceworker.js`,
"@timestamp@": `# ver ${new Date().toString()}`,
"var pxtConfig = null": "var pxtConfig = " + JSON.stringify(cfg, null, 4),
"@defaultLocaleStrings@": "",
"@cachedHexFiles@": "",
"@cachedHexFilesEncoded@": "",
"@targetEditorJs@": targetEditorJs ? `${opts.localDir}editor.js` : "",
"@targetFieldEditorsJs@": targetFieldEditorsJs ? `${opts.localDir}fieldeditors.js` : "",
"@targetScriptPageJs@": targetScriptPageJs ? `${opts.localDir}scriptPage.js` : "",
"@targetImages@": targetImagePaths.length ? targetImageLocalPaths.join('\n') : '',
"@targetImagesEncoded@": targetImagePaths.length ? encodeURLs(targetImageLocalPaths) : ''
}
if (!opts.noAppCache) {
replacements["data-manifest=\"\""] = `manifest="${opts.localDir}release.manifest"`;
}
}
const replFiles = [
"index.html",
"embed.js",
"run.html",
"docs.html",
"siminstructions.html",
"codeembed.html",
"release.manifest",
"worker.js",
"serviceworker.js",
"simulatorserviceworker.js",
"monacoworker.js",
"simulator.html",
"sim.manifest",
"sim.webmanifest",
"workerConfig.js",
"multi.html",
"asseteditor.html"
]
// expandHtml is manually called on these files before upload
// runs substitutions, fills in locale, etc
const expandFiles = [
"index.html"
]
for (const subapp of SUB_WEBAPPS) {
replFiles.push(`${subapp.name}.html`);
expandFiles.push(`${subapp.name}.html`);
}
nodeutil.mkdirP("built/uploadrepl")
function encodeURLs(urls: string[]) {
return urls.map(url => encodeURIComponent(url)).join(";")
}
const uplReqs: Map = {}
const uglify = opts.minify ? require("uglify-js") : undefined;
const uploadFileAsync = async (p: string) => {
let rdata: Buffer = null
if (opts.fileContent) {
let s = U.lookup(opts.fileContent, p)
if (s != null)
rdata = Buffer.from(s, "utf8");
}
if (!rdata) {
if (!fs.existsSync(p))
return undefined;
rdata = await readFileAsync(p)
}
let fileName = uploadFileName(p)
let mime = U.getMime(p)
const minified = opts.minify && mime == "application/javascript" && fileName !== "target.js";
pxt.log(` ${p} -> ${fileName} (${mime})` + (minified ? ' minified' : ""));
let isText = /^(text\/.*|application\/.*(javascript|json))$/.test(mime)
let content = ""
let data = rdata;
if (isText) {
content = data.toString("utf8")
if (expandFiles.indexOf(fileName) >= 0) {
if (!opts.localDir) {
let m = pxt.appTarget.appTheme as Map
for (let k of Object.keys(m)) {
if (/CDN$/.test(k))
m[k.slice(0, k.length - 3)] = m[k];
}
}
content = server.expandHtml(content, undefined, cdnCachedAppTheme);
}
if (/^sim/.test(fileName) || /^workerConfig/.test(fileName)) {
// just force blobs for everything in simulator manifest
content = content.replace(/\/(cdn|sim)\//g, "/blb/")
}
if (minified) {
const res = uglify.minify(content);
if (!res.error) {
content = res.code;
}
else {
pxt.log(` Could not minify ${fileName} ${res.error}`)
}
}
if (replFiles.indexOf(fileName) >= 0) {
for (let from of Object.keys(replacements)) {
content = U.replaceAll(content, from, replacements[from])
}
if (opts.localDir) {
data = Buffer.from(content, "utf8")
} else {
// save it for developer inspection
fs.writeFileSync("built/uploadrepl/" + fileName, content)
}
} else if (fileName == "target.json" || fileName == "target.js") {
let isJs = fileName == "target.js"
if (isJs) content = content.slice(targetJsPrefix.length)
let trg: pxt.TargetBundle = JSON.parse(content)
if (opts.localDir) {
for (let e of trg.appTheme.docMenu)
if (e.path[0] == "/") {
e.path = opts.localDir + "docs" + e.path;
}
trg.appTheme.homeUrl = opts.localDir
// patch icons in bundled packages
Object.keys(trg.bundledpkgs).forEach(pkgid => {
const res = trg.bundledpkgs[pkgid];
// path config before storing
const config = JSON.parse(res[pxt.CONFIG_NAME]) as pxt.PackageConfig;
if (/^\//.test(config.icon)) config.icon = opts.localDir + "docs" + config.icon;
res[pxt.CONFIG_NAME] = pxt.Package.stringifyConfig(config);
})
data = Buffer.from((isJs ? targetJsPrefix : '') + nodeutil.stringify(trg), "utf8")
} else {
if (trg.simulator?.boardDefinition?.visual) {
let boardDef = trg.simulator.boardDefinition.visual as pxsim.BoardImageDefinition;
if (boardDef.image) {
boardDef.image = uploadedArtFileCdnUrl(boardDef.image);
if (boardDef.outlineImage) boardDef.outlineImage = uploadedArtFileCdnUrl(boardDef.outlineImage);
}
}
// patch icons in bundled packages
Object.keys(trg.bundledpkgs).forEach(pkgid => {
const res = trg.bundledpkgs[pkgid];
// patch config before storing
const config = JSON.parse(res[pxt.CONFIG_NAME]) as pxt.PackageConfig;
if (config.icon) config.icon = uploadedArtFileCdnUrl(config.icon);
res[pxt.CONFIG_NAME] = pxt.Package.stringifyConfig(config);
})
content = nodeutil.stringify(trg);
if (isJs)
content = targetJsPrefix + content
// save it for developer inspection
fs.writeFileSync("built/uploadrepl/" + fileName, content)
}
}
} else {
content = data.toString("base64")
}
if (opts.localDir) {
U.assert(!!opts.builtPackaged);
let fn = path.join(opts.builtPackaged, opts.localDir, fileName)
nodeutil.mkdirP(path.dirname(fn))
return minified ? writeFileAsync(fn, content) : writeFileAsync(fn, data)
}
let req = {
encoding: isText ? "utf8" : "base64",
content,
hash: "",
filename: fileName,
size: 0
}
let buf = Buffer.from(req.content, req.encoding)
req.size = buf.length
req.hash = gitHash(buf)
uplReqs[fileName] = req
}
// only keep the last version of each uploadFileName()
opts.fileList = U.values(U.toDictionary(opts.fileList, uploadFileName))
// check size
const maxSize = checkFileSize(opts.fileList);
const maxAllowedFileSize = (pxt.appTarget.cloud.maxFileSize || (30000000)); // default to 30Mb
if (maxSize > maxAllowedFileSize)
U.userError(`file too big for upload: ${maxSize} bytes, max is ${maxAllowedFileSize} bytes`);
pxt.log('');
if (opts.localDir)
return U.promisePoolAsync(15, opts.fileList, uploadFileAsync)
.then(() => {
pxt.log("Release files written to " + path.join(opts.builtPackaged, opts.localDir))
})
return U.promisePoolAsync(15, opts.fileList, uploadFileAsync)
.then(() =>
opts.githubOnly
? uploadToGitRepoAsync(opts, uplReqs)
: gitUploadAsync(opts, uplReqs))
}
function readLocalPxTarget() {
if (!fs.existsSync("pxtarget.json")) {
console.error("This command requires pxtarget.json in current directory.")
process.exit(1)
}
nodeutil.setTargetDir(process.cwd())
const pkg = readJson("package.json");
const cfg: pxt.TargetBundle = readJson("pxtarget.json");
cfg.versions = {
target: pkg["version"],
pxt: (pxt.appTarget.versions && pxt.appTarget.versions.pxt) || pkg["dependencies"]["pxt-core"]
};
return cfg
}
function forEachBundledPkgAsync(f: (pkg: pxt.MainPackage, dirname: string) => Promise, includeProjects: boolean = false) {
let prev = process.cwd()
let folders = pxt.appTarget.bundleddirs;
if (includeProjects) {
let projects = nodeutil.allFiles("libs", { maxDepth: 1, includeDirs: true }).filter(f => /prj$/.test(f));
folders = folders.concat(projects);
}
return U.promiseMapAllSeries(folders, (dirname) => {
const host = new Host();
const pkgPath = path.join(nodeutil.targetDir, dirname);
pxt.debug(`building bundled package at ${pkgPath}`)
// if the package is under node_modules/ , slurp any existing files
const m = /node_modules[\\\/][^\\\/]*[\\\/]libs[\\\/](\w+)$/i.exec(pkgPath);
if (m) {
const bdir = m[1];
const overridePath = path.join("libs", bdir);
pxt.debug(`override with files from ${overridePath}`)
if (nodeutil.existsDirSync(overridePath)) {
host.fileOverrides = {};
nodeutil.allFiles(overridePath)
.filter(f => fs.existsSync(f))
.forEach(f => host.fileOverrides[path.relative(overridePath, f)] = fs.readFileSync(f, "utf8"));
pxt.debug(`file overrides: ${Object.keys(host.fileOverrides).join(', ')}`)
} else {
pxt.debug(`override folder ${overridePath} not present`);
}
}
process.chdir(pkgPath);
mainPkg = new pxt.MainPackage(host);
return f(mainPkg, dirname);
})
.finally(() => process.chdir(prev))
.then(() => { });
}
function ghpSetupRepoAsync() {
function getreponame() {
let cfg = fs.readFileSync("gh-pages/.git/config", "utf8")
let m = /^\s*url\s*=\s*.*github.*\/([^\/\s]+)$/mi.exec(cfg)
if (!m) U.userError("cannot determine GitHub repo name")
return m[1].replace(/\.git$/, "")
}
if (fs.existsSync("gh-pages")) {
console.log("Skipping init of gh-pages; you can delete it first to get full re-init")
return Promise.resolve(getreponame())
}
nodeutil.cpR(".git", "gh-pages/.git")
return ghpGitAsync("checkout", "gh-pages")
.then(() => getreponame())
}
function ghpGitAsync(...args: string[]) {
return nodeutil.spawnAsync({
cmd: "git",
cwd: "gh-pages",
args: args
})
}
function ghpInitAsync() {
if (fs.existsSync("gh-pages/.git"))
return Promise.resolve();
nodeutil.cpR(".git", "gh-pages/.git")
return ghpGitAsync("checkout", "gh-pages")
.then(() => Promise.resolve()) // branch already exists
.catch((e: any) => ghpGitAsync("checkout", "--orphan", "gh-pages"))
.then(() => ghpGitAsync("rm", "-rf", "."))
.then(() => {
nodeutil.writeFileSync("gh-pages/index.html", "Under construction.")
nodeutil.writeFileSync("gh-pages/.gitattributes",
`# enforce unix style line endings
*.ts text eol=lf
*.tsx text eol=lf
*.md text eol=lf
*.txt text eol=lf
*.js text eol=lf
*.json text eol=lf
*.xml text eol=lf
*.svg text eol=lf
*.yaml text eol=lf
*.css text eol=lf
*.html text eol=lf
*.py text eol=lf
*.exp text eol=lf
*.manifest text eol=lf
# do not enforce text for everything - it causes issues with random binary files
*.sln text eol=crlf
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
`);
return ghpGitAsync("add", ".")
})
.then(() => ghpGitAsync("commit", "-m", "Initial."))
.then(() => ghpGitAsync("push", "--set-upstream", "origin", "gh-pages"))
}
export function ghpPushAsync(builtPackaged: string, minify = false) {
let repoName = ""
return ghpInitAsync()
.then(() => ghpSetupRepoAsync())
.then(name => internalStaticPkgAsync(builtPackaged, (repoName = name), minify))
.then(() => nodeutil.cpR(path.join(builtPackaged, repoName), "gh-pages"))
.then(() => ghpGitAsync("add", "."))
.then(() => ghpGitAsync("commit", "-m", "Auto-push"))
.then(() => ghpGitAsync("push"))
}
async function maxMTimeAsync(dirs: string[], maxDepth: number) {
let max = 0
await U.promiseMapAll(dirs, async dir => {
const files = nodeutil.allFiles(dir, { allowMissing: true, maxDepth });
await U.promiseMapAll(files, async file => {
const st = await statAsync(file);
max = Math.max(st.mtime.getTime(), max);
});
});
return max;
}
export interface BuildTargetOptions {
localDir?: boolean;
packaged?: boolean;
skipCore?: boolean;
quick?: boolean;
rebundle?: boolean;
}
export function buildTargetAsync(parsed?: commandParser.ParsedCommand): Promise {
parseBuildInfo(parsed);
const opts: BuildTargetOptions = {};
if (parsed && parsed.flags["skipCore"])
opts.skipCore = true;
const clean = parsed && parsed.flags["clean"];
return (clean ? cleanAsync() : Promise.resolve())
.then(() => internalBuildTargetAsync(opts));
}
export async function internalBuildTargetAsync(options: BuildTargetOptions = {}): Promise {
if (pxt.appTarget.id == "core")
return buildTargetCoreAsync(options)
const commonPackageDir = path.resolve("node_modules/pxt-common-packages")
// Make sure to build common sim in case of a local clean. This will do nothing for
// targets without pxt-common-packages installed.
if (!inCommonPkg("built/common-sim.js") || !inCommonPkg("built/common-sim.d.ts")) {
await buildCommonSimAsync();
}
if (nodeutil.existsDirSync(simDir())) {
await extractLocStringsAsync("sim-strings", [simDir()]);
}
copyCommonSim();
await simshimAsync();
await buildFolderAsync('compiler', true, 'compiler');
fillInCompilerExtension(pxt.appTarget);
if (options.rebundle) {
await buildTargetCoreAsync({ quick: true });
}
else {
await buildTargetCoreAsync(options);
}
await buildSimAsync();
await buildFolderAsync('cmds', true);
await buildSemanticUIAsync();
await buildEditorExtensionAsync("editor", "extendEditor");
await buildEditorExtensionAsync("fieldeditors", "extendFieldEditors");
await buildEditorExtensionAsync("scriptPage", "extendScriptPage");
await buildFolderAsync('server', true, 'server');
function inCommonPkg(p: string) {
return fs.existsSync(path.join(commonPackageDir, p));
}
}
function buildEditorExtensionAsync(dirname: string, optionName: string) {
if (pxt.appTarget.appTheme && (pxt.appTarget.appTheme as any)[optionName] &&
fs.existsSync(path.join(dirname, "tsconfig.json"))) {
const tsConfig = JSON.parse(fs.readFileSync(path.join(dirname, "tsconfig.json"), "utf8"));
let p: Promise;
if (tsConfig.compilerOptions.module)
p = buildFolderAndBrowserifyAsync(dirname, true, dirname);
else
p = buildFolderAsync(dirname, true, dirname);
return p.then(() => {
const prepends = nodeutil.allFiles(path.join(dirname, "prepend"), { maxDepth: 1, allowMissing: true })
.filter(f => /\.js$/.test(f));
if (prepends && prepends.length) {
const editorjs = path.join("built", dirname + ".js");
prepends.push(editorjs);
pxt.log(`bundling ${prepends.join(', ')}`);
const bundled = prepends.map(f => fs.readFileSync(f, "utf8")).join("\n");
fs.writeFileSync(editorjs, bundled, "utf8");
}
})
}
return Promise.resolve();
}
function buildFolderAsync(p: string, optional?: boolean, outputName?: string): Promise {
if (!fs.existsSync(path.join(p, "tsconfig.json"))) {
if (!optional) U.userError(`${p}/tsconfig.json not found`);
return Promise.resolve()
}
const tsConfig = JSON.parse(fs.readFileSync(path.join(p, "tsconfig.json"), "utf8"));
let isNodeModule = false;
if (outputName && tsConfig.compilerOptions.outFile !== `../built/${outputName}.js`) {
// Special case to support target sim as an NPM package
if (/^node_modules[\/\\]+pxt-.*?-sim$/.test(p)) {
// Allow the out dir be inside the folder being built, and manually copy the result to ./built afterwards
if (tsConfig.compilerOptions.outFile !== `./built/${outputName}.js`) {
U.userError(`${p}/tsconfig.json expected compilerOptions.outFile:"./built/${outputName}.js", got "${tsConfig.compilerOptions.outFile}"`);
}
isNodeModule = true;
} else {
U.userError(`${p}/tsconfig.json expected compilerOptions.outFile:"../built/${outputName}.js", got "${tsConfig.compilerOptions.outFile}"`);
}
}
if (!fs.existsSync("node_modules/typescript")) {
U.userError("Oops, typescript does not seem to be installed, did you run 'npm install'?");
}
pxt.log(`building ${p}...`)
dirsToWatch.push(p)
return nodeutil.spawnAsync({
cmd: "node",
args: [`../${isNodeModule ? "" : "node_modules/"}typescript/bin/tsc`],
cwd: p
}).then(() => {
if (tsConfig.prepend) {
let files: string[] = tsConfig.prepend
files.push(tsConfig.compilerOptions.outFile)
let s = ""
for (let f of files) {
s += fs.readFileSync(path.resolve(p, f), "utf8") + "\n"
}
fs.writeFileSync(path.resolve(p, tsConfig.compilerOptions.outFile), s)
}
if (isNodeModule) {
const content = fs.readFileSync(path.resolve(p, tsConfig.compilerOptions.outFile), "utf8");
fs.writeFileSync(path.resolve("built", path.basename(tsConfig.compilerOptions.outFile)), content);
}
})
}
function copyCommonSim() {
const p = "node_modules/pxt-common-packages/built";
if (fs.existsSync(p)) {
pxt.log(`copying common-sim...`)
nodeutil.cp(path.join(p, "common-sim.js"), "built");
nodeutil.cp(path.join(p, "common-sim.d.ts"), "built");
}
}
function buildFolderAndBrowserifyAsync(p: string, optional?: boolean, outputName?: string): Promise {
if (!fs.existsSync(path.join(p, "tsconfig.json"))) {
if (!optional) U.userError(`${p}/tsconfig.json not found`);
return Promise.resolve()
}
const tsConfig = JSON.parse(fs.readFileSync(path.join(p, "tsconfig.json"), "utf8"));
if (outputName && tsConfig.compilerOptions.outDir !== `../built/${outputName}`) {
U.userError(`${p}/tsconfig.json expected compilerOptions.outDir:"../built/${outputName}", got "${tsConfig.compilerOptions.outDir}"`);
}
if (!fs.existsSync("node_modules/typescript")) {
U.userError("Oops, typescript does not seem to be installed, did you run 'npm install'?");
}
pxt.log(`building ${p}...`)
dirsToWatch.push(p)
return nodeutil.spawnAsync({
cmd: "node",
args: ["../node_modules/typescript/bin/tsc"],
cwd: p
}).then(() => {
const browserify = require('browserify');
let b = browserify();
nodeutil.allFiles(`built/${outputName}`).forEach((f) => {
if (f.match(/\.js$/)) {
b.add(f);
}
});
let outFile = fs.createWriteStream(`built/${outputName}.js`, { encoding: 'utf8' });
b.bundle().pipe(outFile);
return new Promise((resolve, reject) => {
outFile.on('finish', () => {
resolve();
});
outFile.on('error', (err: any) => {
reject(err);
});
});
})
}
let dirsToWatch: string[] = []
interface CiBuildInfo {
ci: "travis" | "githubactions" | "local"
branch: string;
tag: string;
commit: string;
commitUrl: string;
pullRequest?: boolean;
}
function isTravis() {
return process.env.TRAVIS === "true";
}
function isGithubAction() {
return !!process.env.GITHUB_ACTIONS;
}
function isAzurePipelines() {
return process.env.TF_BUILD === "True";
}
function isLocalBuild() {
return !(isTravis() || isGithubAction() || isAzurePipelines());
}
async function ciBuildInfoAsync(): Promise {
if (isTravis()) return travisInfo();
else if (isGithubAction()) return await githubActionInfoAsync();
else if (isAzurePipelines()) return travisInfo(); // azure pipelines uses same info
else {
// local build
return {
ci: "local",
branch: undefined,
tag: undefined,
commit: undefined,
commitUrl: undefined
}
}
function travisInfo(): CiBuildInfo {
const commit = process.env.TRAVIS_COMMIT;
const pr = process.env.TRAVIS_PULL_REQUEST;
const repoSlug = process.env.TRAVIS_REPO_SLUG;
return {
ci: "travis",
branch: process.env.TRAVIS_BRANCH,
tag: process.env.TRAVIS_TAG,
commit,
commitUrl: !commit ? undefined :
"https://github.com/" + repoSlug + "/commits/" + commit,
pullRequest: pr !== "false"
}
}
async function githubActionInfoAsync(): Promise {
// https://help.github.com/en/actions/automating-your-workflow-with-github-actions/using-environment-variables#default-environment-variables
const repoSlug = process.env.GITHUB_REPOSITORY;
const commit = process.env.GITHUB_SHA;
const ref = process.env.GITHUB_REF;
// branch build refs/heads/...
// tag build res/tags/...
const branch = ref.replace(/^refs\/(heads|tags)\//, '');
const isTagPush = /^refs\/tags\//.test(ref);
const tag = isTagPush ? branch : await nodeutil.getLocalTagPointingAtHeadAsync();
const eventName = process.env.GITHUB_EVENT_NAME;
pxt.log(`event name: ${eventName}`);
// PR: not on master or not a release number
return {
ci: "githubactions",
branch,
tag,
commit,
commitUrl: "https://github.com/" + repoSlug + "/commits/" + commit,
pullRequest: !(branch == "master" || /^v\d+\.\d+\.\d+$/.test(tag))
}
}
}
function setCiBuildInfo(tag: string, branch: string, commit: string, repoSlug: string) {
// travis
process.env["TRAVIS"] = "1";
process.env["TRAVIS_TAG"] = tag;
process.env['TRAVIS_BRANCH'] = branch;
process.env['TRAVIS_COMMIT'] = commit;
process.env['TRAVIS_REPO_SLUG'] = repoSlug;
}
function buildWebManifest(cfg: pxt.TargetBundle) {
let webmanifest: any = {
"lang": "en",
"dir": "ltr",
"name": cfg.name,
"short_name": cfg.nickname || cfg.name,
"background_color": "#FAFAFA",
"icons": [],
"scope": "/",
"start_url": "/",
"display": "fullscreen",
"orientation": "any"
}
if (cfg.appTheme) {
if (cfg.appTheme.accentColor)
webmanifest["theme_color"] = cfg.appTheme.accentColor;
if (cfg.appTheme.backgroundColor)
webmanifest["background_color"] = cfg.appTheme.backgroundColor;
}
[192, 512].forEach(sz => {
const fn = `/static/icons/android-chrome-${sz}x${sz}.png`;
if (fs.existsSync(path.join('docs', fn))) {
webmanifest.icons.push({
"src": uploadedArtFileCdnUrl(fn),
"sizes": `${sz}x${sz}`,
"types": `image/png`
})
}
});
let diskManifest: any = {}
if (fs.existsSync("webmanifest.json"))
diskManifest = nodeutil.readJson("webmanifest.json")
U.jsonCopyFrom(webmanifest, diskManifest);
return webmanifest;
}
function processLf(filename: string, translationStrings: pxt.Map): void {
if (!/\.(ts|tsx|html)$/.test(filename)) return
if (/\.d\.ts$/.test(filename)) return
pxt.debug(`extracting strings from ${filename}`);
fs.readFileSync(filename, { encoding: "utf8" })
.split('\n').forEach((line, idx) => {
function err(msg: string) {
console.error(`${filename}(${idx + 1}): ${msg}`);
}
if (/@ignorelf@/.test(line))
return;
while (true) {
const newLine = line.replace(/\b(?:blf|(?:lf(_va)?))\s*\(\s*(.*)/, (all, a, args) => { // @ignorelf@
const m = /^("([^"]|(\\"))+")\s*[\),]/.exec(args)
if (m) {
try {
const str = JSON.parse(m[1])
translationStrings[str] = str;
} catch (e) {
err("cannot JSON-parse " + m[1])
}
} else {
if (!/util\.ts$/.test(filename))
err("invalid format of lf() argument: " + args) // @ignorelf@
}
return "BLAH " + args
})
if (newLine == line) return;
line = newLine
}
})
}
function getGalleryUrl(props: pxt.GalleryProps | string): string {
return typeof props === "string" ? props : props.url
}
function replaceStaticImagesInJsonBlob(cfg: any, staticAssetHandler: (fileLocation: string) => string): any {
return pxt.replaceStringsInJsonBlob(cfg, /^\.?\/static\/.+\.(png|gif|jpeg|jpg|svg|mp4|ico)$/i, staticAssetHandler);
}
/**
* Collects grid picker catalog titles from bundled packages so they're translated as target strings.
* Each package also gets resource-qualified keys of its own when its strings are generated.
*/
function getBundledGridPickerCatalogStrings(bundledpkgs: pxt.Map>): pxt.Map {
const strings: pxt.Map = {};
for (const files of Object.values(bundledpkgs || {})) {
for (const file of Object.keys(files).filter(name => /\.jres$/i.test(name))) {
const resources = pxt.inflateJRes(JSON.parse(files[file]));
for (const id of Object.keys(resources)) {
const catalog = resources[id].gridPickerCatalog;
if (!catalog) continue;
for (const name of Object.values(pxt.getGridPickerCatalogStrings(id, catalog))) strings[name] = name;
}
}
}
return strings;
}
function saveThemeJson(cfg: pxt.TargetBundle, localDir?: boolean, packaged?: boolean) {
cfg.appTheme.id = cfg.id
cfg.appTheme.title = cfg.title
cfg.appTheme.name = cfg.name
cfg.appTheme.description = cfg.description
if (packaged) {
cfg = replaceStaticImagesInJsonBlob(
cfg,
fn => path.join('./docs', fn).replace(/\\/g, "/")
);
} else if (!localDir) {
cfg = replaceStaticImagesInJsonBlob(
cfg,
fn => uploadedArtFileCdnUrl(fn)
);
}
if (!cfg.appTheme.htmlDocIncludes)
cfg.appTheme.htmlDocIncludes = {}
if (fs.existsSync("built/templates.json")) {
cfg.appTheme.htmlTemplates = readJson("built/templates.json")
}
nodeutil.mkdirP("built");
nodeutil.writeFileSync("built/theme.json", nodeutil.stringify(cfg.appTheme))
}
/**
* Collects every string the target needs translated, from its theme, bundled packages, docs, and
* targetconfig.json, and writes them to built/target-strings.json for localization.
*/
function saveTargetStrings(cfg: pxt.TargetBundle) {
const theme = cfg.appTheme;
let targetStrings: pxt.Map = {};
if (theme.title) targetStrings[theme.title] = theme.title;
if (theme.name) targetStrings[theme.name] = theme.name;
if (theme.description) targetStrings[theme.description] = theme.description;
for (const preset of cfg.simulator?.themePresets ?? []) {
targetStrings[`{id:simulator-theme-name}${preset.name}`] = preset.name;
}
for (const layout of cfg.simulator?.themeLayouts ?? []) {
targetStrings[`{id:simulator-layout-name}${layout.name}`] = layout.name;
for (const field of layout.colorFields ?? []) {
targetStrings[`{id:simulator-theme-field}${field.label}`] = field.label;
}
}
if (theme.homeScreenHero && typeof theme.homeScreenHero != "string") {
const heroBannerCard = theme.homeScreenHero;
if (heroBannerCard.title) targetStrings[heroBannerCard.title] = heroBannerCard.title;
if (heroBannerCard.description) targetStrings[heroBannerCard.description] = heroBannerCard.description;
if (heroBannerCard.buttonLabel) targetStrings[heroBannerCard.buttonLabel] = heroBannerCard.buttonLabel;
}
// add the labels for the target contributed types that appear in the block function create dialog
if (cfg.runtime?.functionsOptions?.extraFunctionEditorTypes?.length) {
cfg.runtime.functionsOptions.extraFunctionEditorTypes.forEach(extraType => {
if (extraType.label) {
targetStrings[`{id:type}${extraType.label}`] = extraType.label;
}
else {
targetStrings[`{id:type}${extraType.typeName}`] = extraType.typeName;
}
if (extraType.defaultName) {
targetStrings[`{id:var}${extraType.defaultName}`] = extraType.defaultName;
}
});
}
if (typeof cfg.appTheme?.assetEditor === "object") {
for (const key of Object.keys(cfg.appTheme.assetEditor)) {
const entry = cfg.appTheme.assetEditor[key];
if (typeof entry === "object" && entry.label) {
targetStrings[`{id:assetType}${entry.label}`] = entry.label;
}
}
}
if (cfg.appTheme?.pxtJsonOptions?.length) {
for (const option of cfg.appTheme.pxtJsonOptions) {
targetStrings[`{id:setting}${option.label}`] = option.label;
}
}
// walk options in pxt.json
// patch icons in bundled packages
Object.keys(cfg.bundledpkgs).forEach(pkgid => {
const res = cfg.bundledpkgs[pkgid];
// path config before storing
const config = JSON.parse(res[pxt.CONFIG_NAME]) as pxt.PackageConfig;
if (config.description) targetStrings[config.description] = config.description;
if (config.yotta && config.yotta.userConfigs) {
config.yotta.userConfigs
.filter(userConfig => userConfig.description)
.forEach(userConfig => targetStrings[userConfig.description] = userConfig.description);
}
})
Object.assign(targetStrings, getBundledGridPickerCatalogStrings(cfg.bundledpkgs));
// extract strings from docs
function walkDocs(docs: pxt.DocMenuEntry[]) {
if (!docs) return;
docs.forEach(doc => {
targetStrings[doc.name] = doc.name;
walkDocs(doc.subitems);
})
}
walkDocs(theme.docMenu);
if (nodeutil.fileExistsSync("targetconfig.json")) {
const targetConfig = nodeutil.readJson("targetconfig.json") as pxt.TargetConfig;
for (const galleryName of Object.keys(targetConfig?.galleries || {})) {
targetStrings[galleryName] = galleryName;
const gallerymd = nodeutil.resolveMd(nodeutil.targetDir, getGalleryUrl(targetConfig.galleries[galleryName]));
for (const cards of pxt.gallery.parseGalleryMardown(gallerymd)) {
for (const card of cards.cards) {
for (const term of (card.tags || []).concat(card.searchTerms || []))
targetStrings[term] = term;
}
}
}
const multiplayerGames = targetConfig?.multiplayer?.games;
for (const game of (multiplayerGames ?? [])) {
if (game.title) targetStrings[`{id:game-title}${game.title}`] = game.title;
if (game.subtitle) targetStrings[`{id:game-subtitle}${game.subtitle}`] = game.subtitle;
}
const kioskGames = targetConfig?.kiosk?.games;
for (const game of (kioskGames ?? [])) {
if (game.name) targetStrings[`{id:game-name}${game.name}`] = game.name;
if (game.description) targetStrings[`{id:game-description}${game.description}`] = game.description;
}
const approvedRepoLib = targetConfig?.packages?.approvedRepoLib;
for (const [extension, repoData] of Object.entries(approvedRepoLib ?? {})) {
for (const tag of (repoData.tags ?? [])) {
targetStrings[`{id:extension-tag}${tag}`] = tag;
}
}
const builtinExtensionLib = targetConfig?.packages?.builtinExtensionsLib;
for (const [extension, repoData] of Object.entries(builtinExtensionLib ?? {})) {
for (const tag of (repoData.tags ?? [])) {
targetStrings[`{id:extension-tag}${tag}`] = tag;
}
}
const hardwareOptions = targetConfig?.hardwareOptions;
for (const opt of (hardwareOptions ?? [])) {
// Not translating hardware name, as that is typically a brand name / etc.
if (opt.description)
targetStrings[`{id:hardware-description}${opt.description}`] = opt.description;
}
}
const themeFiles = getThemeFilePaths();
for(const themePath of themeFiles) {
if (nodeutil.fileExistsSync(themePath)) {
const theme = nodeutil.readJson(themePath);
const name = theme["name"];
if (name) {
targetStrings[`{id:color-theme-name}${name}`] = name;
}
}
}
// extract strings from editor
["editor", "fieldeditors", "cmds", "scriptPage"]
.filter(d => nodeutil.existsDirSync(d))
.forEach(d => nodeutil.allFiles(d)
.forEach(f => processLf(f, targetStrings))
);
let targetStringsSorted: pxt.Map = {};
Object.keys(targetStrings).sort().map(k => targetStringsSorted[k] = targetStrings[k]);
nodeutil.mkdirP("built");
nodeutil.writeFileSync("built/target-strings.json", nodeutil.stringify(targetStringsSorted))
pxt.log(`target-strings.json built`)
}
/** Writes the projects page and its table of contents from the galleries listed in targetconfig.json. */
function saveProjectGalleryDocs() {
if (!nodeutil.fileExistsSync("targetconfig.json")) return;
const targetConfig = nodeutil.readJson("targetconfig.json") as pxt.TargetConfig;
if (targetConfig?.galleries) {
const docsRoot = nodeutil.targetDir;
let gcards: pxt.CodeCard[] = [];
let tocmd: string =
`# Projects
`;
Object.keys(targetConfig.galleries).forEach(k => {
const galleryUrl = getGalleryUrl(targetConfig.galleries[k])
const gallerymd = nodeutil.resolveMd(docsRoot, galleryUrl);
const gallery = pxt.gallery.parseGalleryMardown(gallerymd);
const gurl = `/${galleryUrl.replace(/^\//, '')}`;
tocmd +=
`* [${k}](${gurl})
`;
const gcard: pxt.CodeCard = {
name: k,
url: gurl
};
gcards.push(gcard)
gallery.forEach(cards => cards.cards
.forEach(card => {
if (card.imageUrl && !gcard.imageUrl)
gcard.imageUrl = card.imageUrl;
if (card.largeImageUrl && !gcard.largeImageUrl)
gcard.largeImageUrl = card.largeImageUrl;
if (card.videoUrl && !gcard.videoUrl)
gcard.videoUrl = card.videoUrl;
const url = card.url || card.learnMoreUrl || card.buyUrl || (card.youTubeId && `https://youtu.be/${card.youTubeId}`);
tocmd += ` * [${card.name || card.title}](${url})
`;
}))
});
nodeutil.writeFileSync(path.join(docsRoot, "docs/projects/SUMMARY.md"), tocmd, { encoding: "utf8" });
nodeutil.writeFileSync(path.join(docsRoot, "docs/projects.md"),
`# Projects
\`\`\`codecard
${JSON.stringify(gcards, null, 4)}
\`\`\`
## See Also
${gcards.map(gcard => `[${gcard.name}](${gcard.url})`).join(',\n')}
`, { encoding: "utf8" });
}
}
function lessFilePaths() {
return [
"node_modules/semantic-ui-less",
"node_modules/pxt-core/theme",
"theme/foo/bar",
"theme",
"node_modules/pxt-core/react-common/styles",
"react-common/styles",
"node_modules/@fortawesome",
"node_modules/pxt-core/node_modules/@fortawesome"
];
}
async function buildSemanticUIAsync(parsed?: commandParser.ParsedCommand) {
if (!fs.existsSync(path.join("theme", "style.less")) || !fs.existsSync(path.join("theme", "theme.config"))) {
return;
}
const pkg = readJson("package.json");
const isPxtCore = pkg["name"] === "pxt-core";
nodeutil.mkdirP(path.join("built", "web"));
const lessPath = require.resolve('less');
const lessCPath = path.join(path.dirname(lessPath), '/bin/lessc');
const lessIncludePaths = lessFilePaths().join(":");
// Build semantic css
await nodeutil.spawnAsync({
cmd: "node",
args: [
lessCPath,
"theme/style.less",
"built/web/semantic.css",
"--include-path=" + lessIncludePaths
]
})
let fontAwesomeSource = "node_modules/@fortawesome/fontawesome-free/webfonts/";
if (!fs.existsSync(fontAwesomeSource)) {
fontAwesomeSource = "node_modules/pxt-core/" + fontAwesomeSource;
}
// Inline all of our icon fonts
let semCss = await readFileAsync('built/web/semantic.css', "utf8");
semCss = await linkFontAsync("icons", semCss);
semCss = await linkFontAsync("outline-icons", semCss);
semCss = await linkFontAsync("brand-icons", semCss);
semCss = await linkFontAsync("fa-solid-900", semCss, fontAwesomeSource, "\\.\\.\\/webfonts\\/");
semCss = await linkFontAsync("fa-regular-400", semCss, fontAwesomeSource, "\\.\\.\\/webfonts\\/");
// Append icons.css to semantic.css (custom pxt icons)
const iconsFile = isPxtCore ? 'built/web/icons.css' : 'node_modules/pxt-core/built/web/icons.css';
const iconsCss = await readFileAsync(iconsFile, "utf8");
semCss = semCss + "\n" + iconsCss;
nodeutil.writeFileSync('built/web/semantic.css', semCss);
// Generate blockly css
if (fs.existsSync(path.join("theme", "blockly.less"))) {
await nodeutil.spawnAsync({
cmd: "node",
args: [
lessCPath,
"theme/blockly.less",
"built/web/blockly.css",
"--include-path=" + lessIncludePaths
]
});
}
async function generateReactCommonCss(app: string) {
const appFile = isPxtCore ? `react-common/styles/react-common-${app}-core.less` :
`node_modules/pxt-core/react-common/styles/react-common-${app}.less`;
await nodeutil.spawnAsync({
cmd: "node",
args: [
lessCPath,
appFile,
`built/web/react-common-${app}.css`,
"--include-path=" + lessIncludePaths
]
});
let appCss = await readFileAsync(`built/web/react-common-${app}.css`, "utf8");
appCss = await linkFontAsync("fa-solid-900", appCss, fontAwesomeSource, "\\.\\.\\/webfonts\\/");
appCss = await linkFontAsync("fa-regular-400", appCss, fontAwesomeSource, "\\.\\.\\/webfonts\\/");
await writeFileAsync(`built/web/react-common-${app}.css`, appCss, "utf8");
}
// Generate react-common css for skillmap, authcode, and multiplayer (but not kiosk yet)
await Promise.all(
SUB_WEBAPPS.filter(app => app.buildCss).map(app => generateReactCommonCss(app.name))
);
// Run postcss with autoprefixer and rtlcss
pxt.debug("running postcss");
const postcss = require('postcss');
const browserList = [
"Chrome >= 38",
"Firefox >= 31",
"Edge >= 12",
"ie >= 11",
"Safari >= 9",
"Opera >= 21",
"iOS >= 9",
"ChromeAndroid >= 59",
"FirefoxAndroid >= 55"
];
const cssnano = require("cssnano")({
zindex: false,
autoprefixer: { browsers: browserList, add: true }
});
const rtlcss = require("rtlcss");
const files = [
"semantic.css",
"blockly.css"
];
for (const subapp of SUB_WEBAPPS) {
if (subapp.buildCss) {
files.push(`react-common-${subapp.name}.css`);
}
}
for (const cssFile of files) {
const css = await readFileAsync(`built/web/${cssFile}`, "utf8");
const processed = await postcss([cssnano])
.process(css, { from: `built/web/${cssFile}`, to: `built/web/${cssFile}` });
await writeFileAsync(`built/web/${cssFile}`, processed.css);
const processedRtl = await postcss([rtlcss])
.process(processed.css, { from: `built/web/${cssFile}`, to: `built/web/rtl${cssFile}` });
await writeFileAsync(`built/web/rtl${cssFile}`, processedRtl.css, "utf8");
}
if (!isPxtCore) {
// This is just to support the local skillmap/cra-app serve for development
for (const subapp of SUB_WEBAPPS) {
if (subapp.buildCss) {
nodeutil.cp(`built/web/react-common-${subapp.name}.css`, `node_modules/pxt-core/${subapp.name}/public/blb`);
nodeutil.cp(`built/web/semantic.css`, `node_modules/pxt-core/${subapp.name}/public/blb`);
}
}
}
}
async function linkFontAsync(font: string, semCss: string, sourceDir = "node_modules/semantic-ui-less/themes/default/assets/fonts/", refDir = "fonts\\/") {
const fontFile = await readFileAsync(sourceDir + font + ".woff")
const url = "url(data:application/font-woff;charset=utf-8;base64,"
+ fontFile.toString("base64") + ") format('woff')"
const r = new RegExp(`src:.*url\\((?:"|')${refDir + font}\\.woff.*`, "g")
semCss = semCss.replace('src: url("' + refDir + font + '.eot");', "")
.replace('src: url(' + refDir + font + '.eot);', "")
.replace(r, "src: " + url + ";")
return semCss;
}
function buildWebStringsAsync() {
if (pxt.appTarget.id != "core") return Promise.resolve();
nodeutil.writeFileSync("built/webstrings.json", nodeutil.stringify(webstringsJson()))
return Promise.resolve()
}
function buildReactAppAsync(app: string, parsed: commandParser.ParsedCommand, opts?: {
copyAssets?: boolean,
includePxtSim?: boolean,
// this requires pxt serve to have completed before serving app, as it relies on
// packing of pxtarget in buildTargetCoreAsync (mainly the chunk in the forEachBundledPkgAsync)
expandedPxtTarget?: boolean,
includePdfLib?: boolean,
}) {
opts = opts || {
copyAssets: true
};
// local serve
const appRoot = `node_modules/pxt-core/${app}`;
const docsPath = parsed.flags["docs"];
return rimrafAsync(`${appRoot}/public/blb`, {})
.then(() => rimrafAsync(`${appRoot}/build/assets`, {}))
.then(() => rimrafAsync(`${appRoot}/public/docs`, {}))
.then(() => rimrafAsync(`${appRoot}/public/static`, {}))
.then(() => {
if (!opts.expandedPxtTarget) {
// read pxtarget.json, save into 'pxtTargetBundle' global variable
let cfg = readLocalPxTarget();
updateColorThemes(cfg);
nodeutil.writeFileSync(`${appRoot}/public/blb/target.js`, "// eslint-disable-next-line \n" + targetJsPrefix + JSON.stringify(cfg));
} else {
nodeutil.cp("built/target.js", `${appRoot}/public/blb`);
}
// This will be missing when serving without a cloned / linked repo
if (opts.includePdfLib
&& fs.existsSync("node_modules/pxt-core/webapp/public/pdf-lib/pdf-lib.min.js")) {
nodeutil.cp(
"node_modules/pxt-core/webapp/public/pdf-lib/pdf-lib.min.js",
`${appRoot}/public/blb/pdf-lib`
);
}
nodeutil.cp("targetconfig.json", `${appRoot}/public/blb`);
nodeutil.cp("node_modules/pxt-core/built/pxtlib.js", `${appRoot}/public/blb`);
nodeutil.cp("node_modules/pxt-core/built/web/pxtrcdeps.js", `${appRoot}/public/blb`);
if (opts.includePxtSim) {
nodeutil.cp("node_modules/pxt-core/built/pxtsim.js", `${appRoot}/public/blb`);
nodeutil.cp("node_modules/pxt-core/built/web/worker.js", `${appRoot}/public/blb`);
nodeutil.cp("node_modules/pxt-core/built/web/pxtworker.js", `${appRoot}/public/blb`);
}
nodeutil.cp("built/web/semantic.css", `${appRoot}/public/blb`);
nodeutil.cp("node_modules/pxt-core/built/web/icons.css", `${appRoot}/public/blb`);
nodeutil.cp(`node_modules/pxt-core/built/web/react-common-${app}.css`, `${appRoot}/public/blb`);
if (opts.copyAssets) {
// copy 'assets' over from docs/static
nodeutil.cpR(`docs/static/${app}/assets`, `${appRoot}/public/assets`);
}
if (docsPath) {
// copy docs over from specified path
nodeutil.cpR(`docs/${docsPath}`, `${appRoot}/public/docs/${docsPath}`);
nodeutil.cpR(`docs/static/${docsPath}`, `${appRoot}/public/static/${docsPath}`);
}
return nodeutil.spawnAsync({
cmd: os.platform() === "win32" ? "npm.cmd" : "npm",
args: ["run-script", "start"],
cwd: appRoot,
shell: true
})
});
}
function buildSkillMapAsync(parsed: commandParser.ParsedCommand) {
return buildReactAppAsync(
"skillmap",
parsed,
{
includePdfLib: true,
copyAssets: true
}
);
}
function buildAuthcodeAsync(parsed: commandParser.ParsedCommand) {
return buildReactAppAsync("authcode", parsed, { copyAssets: false });
}
function updateDefaultProjects(cfg: pxt.TargetBundle) {
let defaultProjects = [
pxt.BLOCKS_PROJECT_NAME,
pxt.JAVASCRIPT_PROJECT_NAME
];
nodeutil.allFiles("libs", { maxDepth: 1, includeDirs: true })
.filter((f) => {
return defaultProjects.indexOf(path.basename(f)) !== -1;
})
.forEach((projectPath) => {
let projectId = path.basename(projectPath);
let newProject: pxt.ProjectTemplate = {
id: projectId,
config: {
name: "",
dependencies: {},
files: []
},
files: {}
};
nodeutil.allFiles(projectPath).forEach((f) => {
let relativePath = path.relative(projectPath, f); // nodeutil.allFiles returns libs/blocksprj/path_to_file, this removes libs/blocksprj/
let fileName = path.basename(relativePath);
if (/^((built)|(pxt_modules)|(node_modules))[\/\\]/.test(relativePath) || fileName === "tsconfig.json") {
return;
}
if (fileName === pxt.CONFIG_NAME) {
newProject.config = nodeutil.readPkgConfig(projectPath);
U.iterMap(newProject.config.dependencies, (k, v) => {
if (/^file:/.test(v)) {
newProject.config.dependencies[k] = "*";
}
});
if (newProject.config.icon)
newProject.config.icon = uploadedArtFileCdnUrl(newProject.config.icon);
} else {
newProject.files[relativePath] = fs.readFileSync(f, "utf8").replace(/\r\n/g, "\n");
}
});
(cfg)[projectId] = newProject;
});
if (!cfg.tsprj && cfg.blocksprj) {
let notBlock = (s: string) => !U.endsWith(s, ".blocks")
cfg.tsprj = U.clone(cfg.blocksprj)
cfg.tsprj.id = "tsprj"
cfg.tsprj.config.files = cfg.tsprj.config.files.filter(notBlock)
for (let k of Object.keys(cfg.tsprj.files)) {
if (!notBlock(k)) delete cfg.tsprj.files[k]
}
}
}
function updateTOC(cfg: pxt.TargetBundle) {
if (!cfg.appTheme) return; // no theme to update
// Update Table of Contents from SUMMARY.md file
const summaryMD = nodeutil.resolveMd(nodeutil.targetDir, "SUMMARY");
if (!summaryMD) {
pxt.log('no SUMMARY file found');
} else {
cfg.appTheme.TOC = pxt.docs.buildTOC(summaryMD)
}
}
function getThemeFilePaths() {
const sharedThemeFiles = fs.existsSync("node_modules/pxt-core/theme/color-themes")
? nodeutil
.allFiles("node_modules/pxt-core/theme/color-themes", { maxDepth: 1, includeDirs: false })
.filter((f) => /\.json$/i.test(f))
: [];
const targetThemeFiles = fs.existsSync("theme/color-themes")
? nodeutil
.allFiles("theme/color-themes", { maxDepth: 1, includeDirs: false })
.filter((f) => /\.json$/i.test(f))
: [];
// Target takes precedence, so include those at the end (will overwrite shared themes)
return sharedThemeFiles.concat(targetThemeFiles);
}
function updateColorThemes(cfg: pxt.TargetBundle) {
pxt.log("Loading color themes...");
const themeFiles = getThemeFilePaths();
for (const themeFile of themeFiles) {
const themeFileDir = path.dirname(themeFile);
const fileData = fs.readFileSync(themeFile, "utf8");
const themeData = JSON.parse(fileData);
const theme: pxt.ColorThemeInfo = {
id: themeData.id,
name: themeData.name,
weight: themeData.weight,
defaultSimulatorTheme: themeData.defaultSimulatorTheme,
monacoBaseTheme: themeData.monacoBaseTheme,
colors: themeData.colors
};
for (const overrideFile of themeData.overrideFiles ?? []) {
if (!overrideFile) {
// Skip empty entries
continue;
}
// Strip leading slashes, convert \ to /, and lowercase the path
const combinedPath = path.join(themeFileDir, overrideFile);
let cssText = fs.readFileSync(combinedPath, "utf8");
theme.overrideCss = theme.overrideCss ? `${theme.overrideCss}\n${cssText}` : cssText;
}
if (!cfg.colorThemeMap) {
cfg.colorThemeMap = {};
}
if (cfg.colorThemeMap[theme.id]) {
// Only overwrite specified fields
// This allows target themes to be built off of shared base themes and only specify certain changes.
const existingTheme = cfg.colorThemeMap[theme.id];
cfg.colorThemeMap[theme.id] = {
...existingTheme,
...theme,
colors: {
...existingTheme.colors,
...theme.colors
}
};
} else {
cfg.colorThemeMap[theme.id] = theme;
}
pxt.log(`Loaded theme ${theme.id}`);
}
}
function rebundleAsync() {
return buildTargetCoreAsync({ quick: true })
.then(() => buildSimAsync());
}
function buildSimAsync() {
return buildFolderAsync(simDir(), true, pxt.appTarget.id === "common" ? "common-sim" : "sim");
}
function compressApiInfo(inf: Map) {
function leanSymbol(sym: pxtc.SymbolInfo) {
const isEmpty = (v: any) => !v || Object.keys(v).length == 0
let attrs: pxtc.CommentAttrs = U.clone(sym.attributes || ({} as any))
if (attrs.callingConvention == 0)
delete attrs.callingConvention
if (isEmpty(attrs.paramDefl))
delete attrs.paramDefl
if (isEmpty(attrs.paramHelp))
delete attrs.paramHelp
if (!attrs.jsDoc)
delete attrs.jsDoc
if (attrs.iconURL && attrs.jres) {
delete attrs.iconURL;
}
delete attrs._source
// keep shim=ENUM_GET etc
if (!attrs.shim || attrs.shim.indexOf("::") > 0)
delete attrs.shim
delete attrs._name
if (isEmpty(attrs))
attrs = undefined
const kind = sym.snippet !== undefined ? -sym.kind : sym.kind
const pyQName = sym.pyQName !== sym.qName ? sym.pyQName : undefined
return {
kind: kind == 7 ? undefined : kind,
retType: sym.retType == "void" ? undefined : sym.retType,
attributes: attrs,
extendsTypes: sym.extendsTypes,
parameters: sym.parameters ? sym.parameters.map(p => ({
name: p.name,
description: p.description || undefined,
type: p.type == "number" ? undefined : p.type,
initializer: p.initializer,
default: p.default,
options: isEmpty(p.options) ? undefined : p.options,
isEnum: p.isEnum || undefined,
handlerParameters: p.handlerParameters
})) : undefined,
isInstance: sym.isInstance || undefined,
isReadOnly: sym.isReadOnly || undefined,
pyQName: pyQName
} as pxtc.SymbolInfo;
}
inf = U.clone(inf)
for (const pkgName of Object.keys(inf)) {
const byQName = inf[pkgName].apis.byQName
for (const apiName of Object.keys(byQName)) {
if (/^DAL\./.test(apiName))
delete byQName[apiName]
else
byQName[apiName] = leanSymbol(byQName[apiName])
}
}
return inf
}
async function buildTargetCoreAsync(options: BuildTargetOptions = {}) {
let cfg = readLocalPxTarget()
updateDefaultProjects(cfg);
updateTOC(cfg);
updateColorThemes(cfg);
cfg.bundledpkgs = {}
pxt.setAppTarget(cfg);
pxt.reloadAppTargetVariant();
dirsToWatch = cfg.bundleddirs.slice()
if (pxt.appTarget.id != "core") {
if (fs.existsSync("theme")) {
dirsToWatch.push("theme"); // simulator
dirsToWatch.push(path.join("theme", "site", "globals")); // simulator
}
if (fs.existsSync("editor"))
dirsToWatch.push("editor");
if (fs.existsSync("fieldeditors"))
dirsToWatch.push("fieldeditors");
if (fs.existsSync("scriptPage"))
dirsToWatch.push("scriptPage");
if (fs.existsSync(simDir())) {
dirsToWatch.push(simDir()); // simulator
dirsToWatch = dirsToWatch.concat(
fs.readdirSync(simDir())
.map(p => path.join(simDir(), p))
.filter(p => path.basename(p) !== "built" && fs.statSync(p).isDirectory()));
}
}
const hexCachePath = path.resolve(process.cwd(), "built", "hexcache");
nodeutil.mkdirP(hexCachePath);
pxt.log(`building target.json in ${process.cwd()}...`);
let builtInfo: pxt.Map = {};
let coreDependencies: string[];
const corepkg = "libs/" + pxt.appTarget.corepkg;
// use staticpkgdirs if defined, otherwise fall back to bundledirs
const packageDirs = (pxt.appTarget.staticpkgdirs?.extensions || pxt.appTarget.bundleddirs).map(dir => path.resolve(dir));
const rootDir = process.cwd();
await buildWebStringsAsync();
if (!options.quick) await internalGenDocsAsync(false, true)
await forEachBundledPkgAsync(async (pkg, dirname) => {
pxt.log(`building bundled ${dirname}`);
let isPrj = /prj$/.test(dirname);
const isHw = /hw---/.test(dirname);
const config = nodeutil.readPkgConfig(".")
const isCore = !!config.core;
for (let p of config.additionalFilePaths)
dirsToWatch.push(path.resolve(p));
const publishFiles = await pkg.filesToBePublishedAsync(true);
if (!isPrj) {
cfg.bundledpkgs[path.basename(dirname)] = publishFiles
}
if (isHw || (isCore && pxt.appTarget.simulator && pxt.appTarget.simulator.dynamicBoardDefinition)) {
isPrj = true
}
let res: TargetPackageInfo = null;
if (!options.quick) {
res = await testForBuildTargetAsync(isPrj || (!options.skipCore && isCore), builtInfo[dirname] && builtInfo[dirname].sha);
}
if (!res) return;
const { options: pkgOptions, api, sha: packageSha } = res;
if (pkgOptions && api) {
// JRES is already included in the target bundle
api.jres = undefined;
builtInfo[dirname] = {
apis: api,
sha: packageSha
};
if (dirname === corepkg) {
coreDependencies = mainPkg.sortedDeps().map(p => p.config.name).filter(n => n !== pxt.appTarget.corepkg);
}
}
// For the projects, we need to save the base HEX file to the offline HEX cache
if (isPrj && pxt.appTarget.compile?.hasHex) {
if (!pkgOptions) {
pxt.debug(`Failed to extract native image for project ${dirname}`);
return;
}
const hexFileExtInfo = [pkgOptions.extinfo, ...(pkgOptions.otherMultiVariants?.map(el => el.extinfo) || [])];
for (const extinfo of hexFileExtInfo) {
// Place the base HEX image in the hex cache if necessary
let sha = extinfo.sha;
let hex: string[] = extinfo.hexinfo.hex;
let hexFile = path.join(hexCachePath, sha + ".hex");
if (fs.existsSync(hexFile)) {
pxt.debug(`native image already in offline cache for project ${dirname}: ${hexFile}`);
} else {
nodeutil.writeFileSync(hexFile, hex.join(os.EOL));
pxt.debug(`created native image in offline cache for project ${dirname}: ${hexFile}`);
}
}
if (!options.packaged) return;
if (pxt.appTarget.staticpkgdirs && pxt.appTarget.staticpkgdirs.base.indexOf(dirname) === -1) return;
// We want to cache a hex file for each of the native packages in case they are added to a project.
// This won't cover the whole matrix, but handles the common case of projects that add one extra
// extension in the offline app.
const allDeps = pkg.sortedDeps(true)
.map(dep => path.resolve(path.join(dirname, dep.verArgument())))
.map(dep => path.resolve(dep).replace(/---.*/, "")); // keep path format (/ vs \\) consistent, trim --- suffix to avoid duplicate imports.
const config = nodeutil.readPkgConfig(dirname);
const host = pkg.host() as Host;
const pkgsToBuildWith = packageDirs.filter(dirname => !allDeps.some(el => el.indexOf(dirname.replace(/---.*/, "")) !== -1));
pxt.log(`Dependencies of base pkgs: ${allDeps.map(el => path.basename(el)).join(", ")}`);
for (const extraPackage of pkgsToBuildWith) {
const extraPathBaseName = path.basename(extraPackage);
process.chdir(path.join(rootDir, dirname));
const deps: pxt.Map = {
...config.dependencies,
[extraPathBaseName]: "file:" + path.relative(path.resolve("."), extraPackage)
}
host.fileOverrides["pxt.json"] = JSON.stringify({
...config,
dependencies: deps
})
pxt.log(`Building hex cache for ${extraPathBaseName} with dependencies:`)
console.dir(deps);
mainPkg = new pxt.MainPackage(host);
try {
const extraRes = await testForBuildTargetAsync(true, null);
if (extraRes) {
const hexFileExtInfo = [extraRes.options.extinfo, ...(extraRes.options.otherMultiVariants?.map(el => el.extinfo) || [])];
for (const extinfo of hexFileExtInfo) {
// Place the base HEX image in the hex cache if necessary
let sha = extinfo.sha;
let hex: string[] = extinfo.hexinfo.hex;
let hexFile = path.join(hexCachePath, sha + ".hex");
if (fs.existsSync(hexFile)) {
pxt.debug(`native image already in offline cache for project ${dirname}: ${hexFile}`);
} else {
nodeutil.writeFileSync(hexFile, hex.join(os.EOL));
pxt.log(`created native image in offline cache for project ${dirname}: ${hexFile}`);
}
}
}
}
catch (e) {
// We're not being smart and verifying that the packages are actually compatible, so
// we might get some errors. Ignore them and keep going.
// -- This will likely happen if you have any packages listed that have hw specific versions,
// e.g. serial && serial---linux
pxt.debug(`Unable to cache hex for project ${dirname} with '${extraPackage}'`);
}
}
}
}, true);
// patch icons in bundled packages
Object.keys(cfg.bundledpkgs).forEach(pkgid => {
const res = cfg.bundledpkgs[pkgid];
// path config before storing
const config = JSON.parse(res[pxt.CONFIG_NAME]) as pxt.PackageConfig;
if (!config.icon)
// try known location
['png', 'jpg'].map(ext => `/static/libs/${config.name}.${ext}`)
.filter(ip => fs.existsSync("docs" + ip))
.forEach(ip => config.icon = ip);
res[pxt.CONFIG_NAME] = pxt.Package.stringifyConfig(config);
})
// reload the app target with the bundled packages before caching tutorial used blocks
pxt.setAppTarget(cfg)
pxt.reloadAppTargetVariant()
if (pxt.appTarget.cacheusedblocksdirs && !options.quick) cfg.tutorialInfo = await internalCacheUsedBlocksAsync();
// Trim redundant API info from packages
const coreInfo = builtInfo[corepkg];
if (coreInfo) {
// Don't bother with dependencies of the core package
if (coreDependencies) {
coreDependencies
.map(dep => builtInfo["libs/" + dep])
.filter(bi => !!bi)
.forEach(bi => bi.apis.byQName = {});
}
Object.keys(builtInfo).filter(k => k !== corepkg).map(k => builtInfo[k]).forEach(info => {
deleteRedundantSymbols(coreInfo.apis.byQName, info.apis.byQName)
});
}
const compressedBuiltInfo = compressApiInfo(builtInfo);
cfg.apiInfo = compressedBuiltInfo;
const info = await ciBuildInfoAsync()
cfg.versions = {
branch: info.branch,
tag: info.tag,
commits: info.commitUrl,
target: readJson("package.json")["version"],
pxt: pxtVersion()
}
saveThemeJson(cfg, options.localDir, options.packaged)
saveTargetStrings(cfg)
saveProjectGalleryDocs()
fillInCompilerExtension(cfg);
const webmanifest = buildWebManifest(cfg)
cfg = U.clone(cfg)
cfg.compile.switches = {} // otherwise we leak the switches set with PXT_COMPILE_SWITCHES=
const targetjson = nodeutil.stringify(cfg)
nodeutil.writeFileSync("built/target.json", targetjson)
nodeutil.writeFileSync("built/target.js", targetJsPrefix + targetjson)
pxt.setAppTarget(cfg) // make sure we're using the latest version
let targetlight = U.flatClone(cfg)
delete targetlight.bundleddirs;
delete targetlight.bundledpkgs;
delete targetlight.appTheme;
delete targetlight.apiInfo;
delete targetlight.tutorialInfo;
if (targetlight.compile)
delete targetlight.compile.compilerExtension;
const targetlightjson = nodeutil.stringify(targetlight);
nodeutil.writeFileSync("built/targetlight.json", targetlightjson)
nodeutil.writeFileSync("built/targetlight.js", targetJsPrefix + targetlightjson)
nodeutil.writeFileSync("built/sim.webmanifest", nodeutil.stringify(webmanifest))
console.log("target.json built.");
}
function fillInCompilerExtension(cfg: pxt.TargetBundle) {
const compPath = path.join(nodeutil.targetDir, "built/compiler.js")
if (fs.existsSync(compPath)) {
const src = fs.readFileSync(compPath, "utf8");
// remove top-level namespace declarations, so it evals() correctly
cfg.compile.compilerExtension = src.replace(/^var \w+;$/gm, "");
}
}
function deleteRedundantSymbols(core: pxt.Map, trg: pxt.Map) {
const ignoredKeys = ["fileName", "pkg"]
for (const key of Object.keys(trg)) {
if (flatJSONEquals(core[key], trg[key])) delete trg[key];
}
function flatJSONEquals(a: any, b: any) {
if (a === b) return true;
const tp = typeof a;
if (tp !== typeof b || tp !== "object") return false;
const keysa = Object.keys(a).filter(k => ignoredKeys.indexOf(k) === -1);
const keysb = Object.keys(b).filter(k => ignoredKeys.indexOf(k) === -1);
if (keysa.length !== keysb.length) return false;
for (const key of keysa) {
if (keysb.indexOf(key) === -1) return false;
if (!flatJSONEquals(a[key], b[key])) return false;
}
return true;
}
}
function pxtVersion(): string {
return pxt.appTarget.id == "core" ?
readJson("package.json")["version"] :
readJson("node_modules/pxt-core/package.json")["version"];
}
function buildAndWatchAsync(f: () => Promise, maxDepth: number): Promise {
let currMtime = Date.now()
return f()
.then(dirs => {
if (globalConfig.noAutoBuild) return
pxt.debug('watching ' + dirs.join(', ') + '...');
let loop = () => {
U.delay(1000)
.then(() => maxMTimeAsync(dirs, maxDepth))
.then(num => {
if (num > currMtime) {
currMtime = num
f()
.then(d => {
dirs = d
U.nextTick(loop)
})
} else {
U.nextTick(loop)
}
})
}
U.nextTick(loop)
})
}
function buildFailed(msg: string, e: any) {
console.log("")
console.log("***")
console.log("*** Build failed: " + msg)
console.log(e.stack)
console.log("***")
console.log("")
}
async function buildAndWatchTargetAsync(includeSourceMaps: boolean, rebundle: boolean) {
if (fs.existsSync("pxt.json") &&
!(fs.existsSync(path.join(simDir(), "tsconfig.json")) || nodeutil.existsDirSync(path.join(simDir(), "public")))) {
console.log("No sim/tsconfig.json nor sim/public/; assuming npm installed package")
return Promise.resolve()
}
const hasCommonPackages = fs.existsSync(path.resolve("node_modules/pxt-common-packages"));
let simDirectories: string[] = [];
if (hasCommonPackages) {
const libsdir = path.resolve("node_modules/pxt-common-packages/libs");
simDirectories = fs.readdirSync(libsdir).map(fn => path.join(libsdir, fn, "sim"));
simDirectories = simDirectories.filter(fn => fs.existsSync(fn));
}
const buildTarget = async () => {
let currentlyBuilding = "common sim";
try {
await buildCommonSimAsync();
currentlyBuilding = "target";
await internalBuildTargetAsync({ localDir: true, rebundle });
} catch (e) {
buildFailed(`${currentlyBuilding} build failed: ${e?.message}`, e);
}
let toWatch = dirsToWatch.slice();
if (hasCommonPackages) {
toWatch = toWatch.concat(simDirectories);
}
return toWatch.filter(d => fs.existsSync(d));
}
const lessFiles = lessFilePaths().filter(p => fs.existsSync(p));
// css build already occurs midway through internalBuildTargetAsync, so skip first rerun
let skipFirstCssBuild = true;
const buildCss = async () => {
if (skipFirstCssBuild) {
skipFirstCssBuild = false;
} else {
console.log("rebuilding css");
try {
await buildSemanticUIAsync();
console.log("css build complete");
} catch (e) {
console.error("css build failed", e);
}
}
return lessFiles;
};
// some of the watched targets for buildTarget include nested built files,
// such as libs/game/_locales/*, so can't just grab subdirectories
await buildAndWatchAsync(buildTarget, 1);
await buildAndWatchAsync(buildCss, 6);
}
function buildCommonSimAsync() {
const simPath = path.resolve("node_modules/pxt-common-packages/sim");
if (fs.existsSync(simPath)) {
return buildFolderAsync(simPath)
}
else {
return Promise.resolve();
}
}
function renderDocs(builtPackaged: string, localDir: string) {
const dst = path.resolve(path.join(builtPackaged, localDir))
nodeutil.cpR("node_modules/pxt-core/docfiles", path.join(dst, "/docfiles"))
if (fs.existsSync("docfiles"))
nodeutil.cpR("docfiles", dst + "/docfiles")
const webpath = localDir
let docsTemplate = server.expandDocFileTemplate("docs.html")
docsTemplate = U.replaceAll(docsTemplate, "/cdn/", webpath)
docsTemplate = U.replaceAll(docsTemplate, "/doccdn/", webpath)
docsTemplate = U.replaceAll(docsTemplate, "/docfiles/", webpath + "docfiles/")
docsTemplate = U.replaceAll(docsTemplate, "/--embed", webpath + "embed.js")
const validatedDirs: Map = {}
const docFolders = ["node_modules/pxt-core/common-docs"];
if (fs.existsSync("node_modules/pxt-common-packages/docs")) {
docFolders.push("node_modules/pxt-common-packages/docs");
}
docFolders.push(...nodeutil.getBundledPackagesDocs());
docFolders.push("docs");
for (const docFolder of docFolders) {
for (const f of nodeutil.allFiles(docFolder, { maxDepth: 8 })) {
pxt.log(`rendering ${f}`)
const pathUnderDocs = f.slice(docFolder.length + 1);
let outputFile = path.join(dst, "docs", pathUnderDocs);
const outputDir = path.dirname(outputFile);
if (!validatedDirs[outputDir]) {
nodeutil.mkdirP(outputDir);
validatedDirs[outputDir] = true;
}
let buf = fs.readFileSync(f);
if (/\.(md|html)$/.test(f)) {
const fileData = buf.toString("utf8");
let html = "";
if (U.endsWith(f, ".md")) {
const md = nodeutil.resolveMd(
".",
pathUnderDocs.slice(0, -3),
fileData
);
// patch any /static/... url to /docs/static/...
const patchedMd = md.replace(/\"\/static\//g, `"/docs/static/`);
nodeutil.writeFileSync(outputFile, patchedMd, { encoding: "utf8" });
html = pxt.docs.renderMarkdown({
template: docsTemplate,
markdown: pxt.docs.normalizeStaticMarkdown(patchedMd),
theme: pxt.appTarget.appTheme,
filepath: path.join("docs", pathUnderDocs),
});
// replace .md with .html for rendered page drop
outputFile = outputFile.slice(0, -3) + ".html";
} else {
html = server.expandHtml(fileData);
}
html = html.replace(/(]*)\shref="(\/[^<>"]*)"/g, (f, beg, url) => {
return beg + ` href="${webpath}docs${url}.html"`
});
buf = Buffer.from(html, "utf8");
}
nodeutil.writeFileSync(outputFile, buf)
}
pxt.log(`All docs written from ${docFolder}.`);
}
pxt.log(`All docs written.`);
}
export function serveAsync(parsed: commandParser.ParsedCommand) {
// always use a cloud build
// in most cases, the user machine is not properly setup to
// build a native binary and our CLI just looks broken
// use --localbuild to force localbuild
parseBuildInfo(parsed);
let justServe = false
let packaged = false
let includeSourceMaps = false;
if (parsed.flags["just"]) {
justServe = true
} else if (parsed.flags["pkg"]) {
justServe = true
packaged = true
}
const rebundle = !!parsed.flags["rebundle"];
if (parsed.flags["noBrowser"]) {
globalConfig.noAutoStart = true
}
if (parsed.flags["sourceMaps"]) {
includeSourceMaps = true;
}
if (!globalConfig.localToken) {
globalConfig.localToken = ts.pxtc.Util.guidGen();
saveConfig()
}
let localToken = globalConfig.localToken;
// --local-repo directories resolve against the directory serve was started from,
// which differs from the target root when serve moves into a target found below
const invocationDir = process.cwd();
if (!fs.existsSync("pxtarget.json")) {
//Specifically when the target is being used as a library
let targetDepLoc = nodeutil.targetDir
if (fs.existsSync(path.join(targetDepLoc, "pxtarget.json"))) {
console.log(`Going to ${targetDepLoc}`)
process.chdir(targetDepLoc)
}
else {
let upper = path.join(__dirname, "../../..")
if (fs.existsSync(path.join(upper, "pxtarget.json"))) {
console.log("going to " + upper)
process.chdir(upper)
} else {
U.userError("Cannot find pxtarget.json to serve.")
}
}
}
const targetDir = process.cwd();
const localRepos = localrepos.loadLocalRepos(targetDir, (parsed.flags["localRepo"] as string[]) || [], invocationDir);
return (justServe ? Promise.resolve() : buildAndWatchTargetAsync(includeSourceMaps, rebundle))
.then(() => server.serveAsync({
autoStart: !globalConfig.noAutoStart,
localToken,
packaged,
port: parsed.flags["port"] as number || 0,
wsPort: parsed.flags["wsport"] as number || 0,
hostname: parsed.flags["hostname"] as string || "",
browser: parsed.flags["browser"] as string,
serial: !parsed.flags["noSerial"] && !globalConfig.noSerial,
noauth: parsed.flags["noauth"] as boolean || false,
backport: parsed.flags["backport"] as number || 0,
https: parsed.flags["https"] as boolean || false,
localRepos,
}))
}
const readFileAsync: any = promisify(fs.readFile)
const writeFileAsync: any = promisify(fs.writeFile)
const readDirAsync = promisify(fs.readdir)
const statAsync = promisify(fs.stat)
const rimrafAsync = promisify(rimraf);
let commonfiles: Map = {}
class SnippetHost implements pxt.Host {
//Global cache of module files
files: Map