#!/bin/sh
# The tree is what upstream publishes as an npm package: ES modules for a
# browser.  Its own tests cannot run here -- test/unit wants a DOM and
# test/smoke a browser -- so what is checked is the installed tree itself: the
# entry points package.json points at, the metadata the build generates from it,
# one language bundle, and the four workers.
set -eu

SHARE=${MONACO_SHARE:-/usr/share/nodejs}
ROOT=$SHARE/monaco-editor

ROOT=$ROOT node --no-warnings --input-type=module <<'EOF'
import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { createRequire } from 'node:module';

const root = process.env.ROOT;
const pkg = JSON.parse(readFileSync(`${root}/package.json`, 'utf8'));

assert.equal(pkg.name, 'monaco-editor');
assert.match(pkg.version, /^0\.47\./);
assert.ok(pkg.monacoCommitId, 'package.json carries no commit id');
for (const field of ['module', 'typings']) {
	assert.ok(existsSync(`${root}/${pkg[field]}`), `${field} points at ${pkg[field]}`);
}

// esm/metadata.js is CommonJS, the way upstream ships it
const require = createRequire(import.meta.url);
const { features, languages } = require(`${root}/esm/metadata.js`);
assert.equal(features.length, 58);
assert.equal(languages.length, 81);
assert.deepEqual(
	languages.filter((language) => language.worker).map((language) => language.label),
	['css', 'html', 'json', 'typescript']
);
for (const language of languages) {
	if (!language.worker) continue;
	const entry = `${root}/esm/${language.worker.entry}.js`;
	assert.ok(existsSync(entry), `missing ${language.worker.entry}`);
}

// a language bundle: plain data, no DOM, so it can be loaded here
const abap = await import(`${root}/esm/vs/basic-languages/abap/abap.js`);
assert.equal(abap.conf.comments.lineComment, '*');
assert.ok(Array.isArray(abap.language.tokenizer.root));
EOF

# Nothing of the build host may have survived into the installed tree: the
# repack suffix and the directory a build runs in would both show up in a path
# that was baked into the output.
if grep -rlIF --include='*.js' -e '+ds/' -e '/build/reproducible-path' "$ROOT/esm"; then
	echo "the build path leaked into the tree above" >&2
	exit 1
fi
