#!/bin/sh
# The tests in the tree need the VS Code test harness, which is not part of this
# source package, so what is checked here is the installed tree itself: the
# entry points package.json points at, the modules that do not touch the DOM, and
# the async iterable the tree shaker has to keep for the editor's hover to work.
set -eu

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

test -f "$ROOT/esm/vs/editor/editor.main.js"
test -f "$ROOT/esm/vs/editor/editor.api.js"
test -f "$ROOT/esm/vs/editor/editor.worker.js"

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

const root = process.env.ROOT;
const load = (p) => import(`${root}/esm/${p}`);

const pkg = JSON.parse(readFileSync(`${root}/package.json`, 'utf8'));
assert.equal(pkg.name, 'monaco-editor-core');
for (const field of ['module', 'typings']) {
	assert.ok(existsSync(`${root}/${pkg[field]}`), `${field} points at ${pkg[field]}`);
}

const { URI } = await load('vs/base/common/uri.js');
const uri = URI.parse('file:///usr/share/doc/monaco-editor-core/copyright');
assert.equal(uri.scheme, 'file');
assert.equal(uri.path, '/usr/share/doc/monaco-editor-core/copyright');

const { format } = await load('vs/base/common/strings.js');
assert.equal(format('{0} {1}', 'monaco', 'editor'), 'monaco editor');

const { LinkedMap } = await load('vs/base/common/map.js');
const map = new LinkedMap();
map.set('a', 1);
map.set('b', 2);
assert.deepEqual([...map.keys()], ['a', 'b']);
assert.equal(map.get('b'), 2);
map.delete('a');
assert.deepEqual([...map.keys()], ['b']);

const { Iterable } = await load('vs/base/common/iterator.js');
assert.equal(Iterable.first([7, 8, 9]), 7);

const { AsyncIterableObject } = await load('vs/base/common/async.js');
const seen = [];
for await (const value of AsyncIterableObject.fromArray([1, 2, 3])) {
	seen.push(value);
}
assert.deepEqual(seen, [1, 2, 3]);

const doubled = [];
for await (const value of AsyncIterableObject.fromArray([1, 2, 3]).map((n) => n * 2)) {
	doubled.push(value);
}
assert.deepEqual(doubled, [2, 4, 6]);
EOF

# Nothing of the build host may have survived into the installed tree.
if grep -rlI --include='*.js' -e '/home/' -e '/build/monaco' "$ROOT/esm"; then
	echo "the build path leaked into the tree above" >&2
	exit 1
fi
