summaryrefslogtreecommitdiff
path: root/packages/integrations/deno/test/helpers.ts
blob: ac451d96315b01039c1003d079de6d1b39a46e93 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { fromFileUrl } from 'https://deno.land/std@0.110.0/path/mod.ts';
import { assert } from 'https://deno.land/std@0.158.0/testing/asserts.ts';
import { readableStreamFromReader } from 'https://deno.land/std@0.142.0/streams/conversion.ts';

const dir = new URL('./', import.meta.url);
const defaultURL = new URL('http://localhost:8085/');

export const defaultTestPermissions: Deno.PermissionOptions = {
	read: true,
	net: true,
	run: true,
	env: true,
};

declare type ExitCallback = () => void;

export async function runBuild(fixturePath: string) {
	const proc = Deno.run({
		cmd: ['node', '../../../../../astro/astro.js', 'build', '--silent'],
		cwd: fromFileUrl(new URL(fixturePath, dir)),
	});
	try {
		const status = await proc.status();
		assert(status.success);
	} finally {
		proc.close();
	}
}

export async function startModFromImport(baseUrl: URL): Promise<ExitCallback> {
	const entryUrl = new URL('./dist/server/entry.mjs', baseUrl);
	const mod = await import(entryUrl.toString());

	if (!mod.running()) {
		mod.start();
	}

	return () => mod.stop();
}

export async function startModFromSubprocess(baseUrl: URL): Promise<ExitCallback> {
	const entryUrl = new URL('./dist/server/entry.mjs', baseUrl);
	const proc = Deno.run({
		cmd: ['deno', 'run', '--allow-env', '--allow-net', fromFileUrl(entryUrl)],
		cwd: fromFileUrl(baseUrl),
		stderr: 'piped',
	});

	const stderr = readableStreamFromReader(proc.stderr);
	const dec = new TextDecoder();
	for await (const bytes of stderr) {
		const msg = dec.decode(bytes);
		if (msg.includes(`Server running`)) {
			break;
		}
	}

	return () => proc.close();
}

export async function runBuildAndStartApp(fixturePath: string) {
	const url = new URL(fixturePath, dir);

	await runBuild(fixturePath);
	const stop = await startModFromImport(url);

	return { url: defaultURL, stop };
}

export async function runBuildAndStartAppFromSubprocess(fixturePath: string) {
	const url = new URL(fixturePath, dir);

	await runBuild(fixturePath);
	const stop = await startModFromSubprocess(url);

	return { url: defaultURL, stop };
}