@warp-drive/holodeck 0.0.1-beta.0 → 0.0.3-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/index.js CHANGED
@@ -1,396 +1,7 @@
1
1
  /* global Bun */
2
- import chalk from 'chalk';
3
- import { Hono } from 'hono';
4
- import { serve } from '@hono/node-server';
5
- import { createSecureServer } from 'node:http2';
6
- import { logger } from 'hono/logger';
7
- import { HTTPException } from 'hono/http-exception';
8
- import { cors } from 'hono/cors';
9
- import crypto from 'node:crypto';
10
- import fs from 'node:fs';
11
- import zlib from 'node:zlib';
12
- import { homedir } from 'os';
13
2
  import path from 'path';
14
-
15
3
  const isBun = typeof Bun !== 'undefined';
16
- const DEBUG =
17
- process.env.DEBUG?.includes('wd:holodeck') || process.env.DEBUG === '*' || process.env.DEBUG?.includes('wd:*');
18
-
19
- async function getCertInfo() {
20
- let CERT_PATH = process.env.HOLODECK_SSL_CERT_PATH;
21
- let KEY_PATH = process.env.HOLODECK_SSL_KEY_PATH;
22
-
23
- if (!CERT_PATH) {
24
- CERT_PATH = path.join(homedir(), 'holodeck-localhost.pem');
25
- process.env.HOLODECK_SSL_CERT_PATH = CERT_PATH;
26
-
27
- console.log(
28
- `HOLODECK_SSL_CERT_PATH was not found in the current environment. Setting it to default value of ${CERT_PATH}`
29
- );
30
- }
31
-
32
- if (!KEY_PATH) {
33
- KEY_PATH = path.join(homedir(), 'holodeck-localhost-key.pem');
34
- process.env.HOLODECK_SSL_KEY_PATH = KEY_PATH;
35
-
36
- console.log(
37
- `HOLODECK_SSL_KEY_PATH was not found in the current environment. Setting it to default value of ${KEY_PATH}`
38
- );
39
- }
40
-
41
- if (isBun) {
42
- const CERT = Bun.file(CERT_PATH);
43
- const KEY = Bun.file(KEY_PATH);
44
-
45
- if (!(await CERT.exists()) || !(await KEY.exists())) {
46
- throw new Error(
47
- 'SSL certificate or key not found, you may need to run `pnpm dlx @warp-drive/holodeck ensure-cert`'
48
- );
49
- }
50
-
51
- return {
52
- CERT_PATH,
53
- KEY_PATH,
54
- CERT: await CERT.text(),
55
- KEY: await KEY.text(),
56
- };
57
- } else {
58
- if (!fs.existsSync(CERT_PATH) || !fs.existsSync(KEY_PATH)) {
59
- throw new Error(
60
- 'SSL certificate or key not found, you may need to run `pnpm dlx @warp-drive/holodeck ensure-cert`'
61
- );
62
- }
63
-
64
- return {
65
- CERT_PATH,
66
- KEY_PATH,
67
- CERT: fs.readFileSync(CERT_PATH, 'utf8'),
68
- KEY: fs.readFileSync(KEY_PATH, 'utf8'),
69
- };
70
- }
71
- }
72
-
73
- const DEFAULT_PORT = 1135;
74
- const BROTLI_OPTIONS = {
75
- params: {
76
- [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
77
- // brotli currently defaults to 11 but lets be explicit
78
- [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
79
- },
80
- };
81
- function compress(code) {
82
- return zlib.brotliCompressSync(code, BROTLI_OPTIONS);
83
- }
84
-
85
- /**
86
- * removes the protocol, host, and port from a url
87
- */
88
- function getNiceUrl(url) {
89
- const urlObj = new URL(url);
90
- urlObj.searchParams.delete('__xTestId');
91
- urlObj.searchParams.delete('__xTestRequestNumber');
92
- return (urlObj.pathname + urlObj.searchParams.toString()).slice(1);
93
- }
94
-
95
- /*
96
- {
97
- projectRoot: string;
98
- testId: string;
99
- url: string;
100
- method: string;
101
- body: string;
102
- testRequestNumber: number
103
- }
104
- */
105
- function generateFilepath(options) {
106
- const { body } = options;
107
- const bodyHash = body ? crypto.createHash('md5').update(JSON.stringify(body)).digest('hex') : null;
108
- const cacheDir = generateFileDir(options);
109
- return `${cacheDir}/${bodyHash ? `${bodyHash}-` : 'res'}`;
110
- }
111
- function generateFileDir(options) {
112
- const { projectRoot, testId, url, method, testRequestNumber } = options;
113
- return `${projectRoot}/.mock-cache/${testId}/${method}-${testRequestNumber}-${url}`;
114
- }
115
-
116
- async function replayRequest(context, cacheKey) {
117
- let metaJson;
118
- try {
119
- if (isBun) {
120
- metaJson = await Bun.file(`${cacheKey}.meta.json`).json();
121
- } else {
122
- metaJson = JSON.parse(fs.readFileSync(`${cacheKey}.meta.json`, 'utf8'));
123
- }
124
- } catch (e) {
125
- context.header('Content-Type', 'application/vnd.api+json');
126
- context.status(400);
127
- return context.body(
128
- JSON.stringify({
129
- errors: [
130
- {
131
- status: '400',
132
- code: 'MOCK_NOT_FOUND',
133
- title: 'Mock not found',
134
- detail: `No meta was found for ${context.req.method} ${context.req.url}. You may need to record a mock for this request.`,
135
- },
136
- ],
137
- })
138
- );
139
- }
140
-
141
- const bodyPath = `${cacheKey}.body.br`;
142
- const bodyInit =
143
- metaJson.status !== 204 && metaJson.status < 500
144
- ? isBun
145
- ? Bun.file(bodyPath)
146
- : fs.createReadStream(bodyPath)
147
- : '';
148
-
149
- const headers = new Headers(metaJson.headers || {});
150
- // @ts-expect-error - createReadStream is supported in node
151
- const response = new Response(bodyInit, {
152
- status: metaJson.status,
153
- statusText: metaJson.statusText,
154
- headers,
155
- });
156
-
157
- if (metaJson.status > 400) {
158
- throw new HTTPException(metaJson.status, { res: response, message: metaJson.statusText });
159
- }
160
-
161
- return response;
162
- }
163
-
164
- function createTestHandler(projectRoot) {
165
- const TestHandler = async (context) => {
166
- try {
167
- const { req } = context;
168
-
169
- const testId = req.query('__xTestId');
170
- const testRequestNumber = req.query('__xTestRequestNumber');
171
- const niceUrl = getNiceUrl(req.url);
172
-
173
- if (!testId) {
174
- context.header('Content-Type', 'application/vnd.api+json');
175
- context.status(400);
176
- return context.body(
177
- JSON.stringify({
178
- errors: [
179
- {
180
- status: '400',
181
- code: 'MISSING_X_TEST_ID_HEADER',
182
- title: 'Request to the http mock server is missing the `X-Test-Id` header',
183
- detail:
184
- "The `X-Test-Id` header is used to identify the test that is making the request to the mock server. This is used to ensure that the mock server is only used for the test that is currently running. If using @ember-data/request add import { MockServerHandler } from '@warp-drive/holodeck'; to your request handlers.",
185
- source: { header: 'X-Test-Id' },
186
- },
187
- ],
188
- })
189
- );
190
- }
191
-
192
- if (!testRequestNumber) {
193
- context.header('Content-Type', 'application/vnd.api+json');
194
- context.status(400);
195
- return context.body(
196
- JSON.stringify({
197
- errors: [
198
- {
199
- status: '400',
200
- code: 'MISSING_X_TEST_REQUEST_NUMBER_HEADER',
201
- title: 'Request to the http mock server is missing the `X-Test-Request-Number` header',
202
- detail:
203
- "The `X-Test-Request-Number` header is used to identify the request number for the current test. This is used to ensure that the mock server response is deterministic for the test that is currently running. If using @ember-data/request add import { MockServerHandler } from '@warp-drive/holodeck'; to your request handlers.",
204
- source: { header: 'X-Test-Request-Number' },
205
- },
206
- ],
207
- })
208
- );
209
- }
210
-
211
- if (req.method === 'POST' || niceUrl === '__record') {
212
- const payload = await req.json();
213
- const { url, headers, method, status, statusText, body, response } = payload;
214
- const cacheKey = generateFilepath({
215
- projectRoot,
216
- testId,
217
- url,
218
- method,
219
- body: body ? JSON.stringify(body) : null,
220
- testRequestNumber,
221
- });
222
- const compressedResponse = compress(JSON.stringify(response));
223
- // allow Content-Type to be overridden
224
- headers['Content-Type'] = headers['Content-Type'] || 'application/vnd.api+json';
225
- // We always compress and chunk the response
226
- headers['Content-Encoding'] = 'br';
227
- // we don't cache since tests will often reuse similar urls for different payload
228
- headers['Cache-Control'] = 'no-store';
229
- // streaming requires Content-Length
230
- headers['Content-Length'] = compressedResponse.length;
231
-
232
- const cacheDir = generateFileDir({
233
- projectRoot,
234
- testId,
235
- url,
236
- method,
237
- testRequestNumber,
238
- });
239
-
240
- fs.mkdirSync(cacheDir, { recursive: true });
241
-
242
- if (isBun) {
243
- const newMetaFile = Bun.file(`${cacheKey}.meta.json`);
244
- await newMetaFile.write(JSON.stringify({ url, status, statusText, headers, method, requestBody: body }));
245
- const newBodyFile = Bun.file(`${cacheKey}.body.br`);
246
- await newBodyFile.write(compressedResponse);
247
- } else {
248
- fs.writeFileSync(
249
- `${cacheKey}.meta.json`,
250
- JSON.stringify({ url, status, statusText, headers, method, requestBody: body })
251
- );
252
- fs.writeFileSync(`${cacheKey}.body.br`, compressedResponse);
253
- }
254
-
255
- context.status(204);
256
- return context.body(null);
257
- } else {
258
- const body = req.body;
259
- const cacheKey = generateFilepath({
260
- projectRoot,
261
- testId,
262
- url: niceUrl,
263
- method: req.method,
264
- body: body ? JSON.stringify(body) : null,
265
- testRequestNumber,
266
- });
267
- return replayRequest(context, cacheKey);
268
- }
269
- } catch (e) {
270
- if (e instanceof HTTPException) {
271
- throw e;
272
- }
273
- context.header('Content-Type', 'application/vnd.api+json');
274
- context.status(500);
275
- return context.body(
276
- JSON.stringify({
277
- errors: [
278
- {
279
- status: '500',
280
- code: 'MOCK_SERVER_ERROR',
281
- title: 'Mock Server Error during Request',
282
- detail: e.message,
283
- },
284
- ],
285
- })
286
- );
287
- }
288
- };
289
-
290
- return TestHandler;
291
- }
292
-
293
- export function startNodeServer() {
294
- const args = process.argv.slice();
295
-
296
- if (!isBun && args.length) {
297
- const options = JSON.parse(args[2]);
298
- _createServer(options);
299
- }
300
- }
301
-
302
- export function startWorker() {
303
- // listen for launch message
304
- globalThis.onmessage = async (event) => {
305
- const { options } = event.data;
306
-
307
- const { server } = await _createServer(options);
308
-
309
- // listen for messages
310
- globalThis.onmessage = (event) => {
311
- const message = event.data;
312
- if (message === 'end') {
313
- server.close();
314
- globalThis.close();
315
- }
316
- };
317
- };
318
- }
319
-
320
- /*
321
- { port?: number, projectRoot: string }
322
- */
323
- export async function createServer(options, useBun = false) {
324
- if (!useBun) {
325
- const CURRENT_FILE = new URL(import.meta.url).pathname;
326
- const START_FILE = path.join(CURRENT_FILE, '../start-node.js');
327
- const server = Bun.spawn(['node', '--experimental-default-type=module', START_FILE, JSON.stringify(options)], {
328
- env: process.env,
329
- cwd: process.cwd(),
330
- stdin: 'inherit',
331
- stdout: 'inherit',
332
- stderr: 'inherit',
333
- });
334
-
335
- return {
336
- terminate() {
337
- server.kill();
338
- // server.unref();
339
- },
340
- };
341
- }
342
-
343
- const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
344
-
345
- worker.postMessage({
346
- type: 'launch',
347
- options,
348
- });
349
-
350
- return worker;
351
- }
352
-
353
- async function _createServer(options) {
354
- const { CERT, KEY } = await getCertInfo();
355
- const app = new Hono();
356
- if (DEBUG) {
357
- app.use('*', logger());
358
- }
359
- app.use(
360
- '*',
361
- cors({
362
- origin: (origin) =>
363
- origin.startsWith('http://localhost:') || origin.startsWith('https://localhost:') ? origin : '*',
364
- allowHeaders: ['Accept', 'Content-Type'],
365
- allowMethods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'POST', 'DELETE', 'PATCH'],
366
- exposeHeaders: ['Content-Length', 'Content-Type'],
367
- maxAge: 60_000,
368
- credentials: false,
369
- })
370
- );
371
- app.all('*', createTestHandler(options.projectRoot));
372
-
373
- const server = serve({
374
- overrideGlobalObjects: !isBun,
375
- fetch: app.fetch,
376
- serverOptions: {
377
- key: KEY,
378
- cert: CERT,
379
- },
380
- createServer: createSecureServer,
381
- port: options.port ?? DEFAULT_PORT,
382
- hostname: options.hostname ?? 'localhost',
383
- });
384
-
385
- console.log(
386
- `\tMock server running at ${chalk.yellow('https://') + chalk.magenta((options.hostname ?? 'localhost') + ':') + chalk.yellow(options.port ?? DEFAULT_PORT)}`
387
- );
388
-
389
- return { app, server };
390
- }
391
-
392
- /** @type {Map<string, Awaited<ReturnType<typeof createServer>>>} */
393
- const servers = new Map();
4
+ let closeHandler = () => {};
394
5
 
395
6
  export default {
396
7
  async launchProgram(config = {}) {
@@ -399,41 +10,33 @@ export default {
399
10
  (pkg) => pkg.name
400
11
  );
401
12
  const options = { name, projectRoot, ...config };
402
- console.log(
403
- chalk.grey(
404
- `\n\t@${chalk.greenBright('warp-drive')}/${chalk.magentaBright(
405
- 'holodeck'
406
- )} 🌅\n\t=================================\n`
407
- ) +
408
- chalk.grey(
409
- `\n\tHolodeck Access Granted\n\t\tprogram: ${chalk.magenta(name)}\n\t\tsettings: ${chalk.green(JSON.stringify(config).split('\n').join(' '))}\n\t\tdirectory: ${chalk.cyan(projectRoot)}\n\t\tengine: ${chalk.cyan(
410
- isBun ? 'bun@' + Bun.version : 'node'
411
- )}`
412
- )
413
- );
414
- console.log(chalk.grey(`\n\tStarting Holodeck Subroutines (mode:${chalk.cyan(isBun ? 'bun' : 'node')})`));
415
13
 
416
- if (servers.has(projectRoot)) {
417
- throw new Error(`Holodeck is already running for project '${name}' at '${projectRoot}'`);
14
+ if (!isBun) {
15
+ // @ts-expect-error
16
+ options.useWorker = config.useWorker ?? true;
17
+ const nodeImpl = await import('./node.js');
18
+ const program = await nodeImpl.launchProgram(options);
19
+ closeHandler = program.endProgram;
20
+ return program.config;
418
21
  }
419
22
 
420
- // toggle to true if Bun fixes CORS support for HTTP/2
421
- const project = await createServer(options, false);
422
- servers.set(projectRoot, project);
423
- },
424
- async endProgram() {
425
- console.log(chalk.grey(`\n\tEnding Holodeck Subroutines (mode:${chalk.cyan(isBun ? 'bun' : 'node')})`));
426
- const projectRoot = process.cwd();
427
-
428
- if (!servers.has(projectRoot)) {
429
- const name = require(path.join(projectRoot, 'package.json')).name;
430
- console.log(chalk.red(`\n\nHolodeck was not running for project '${name}' at '${projectRoot}'\n\n`));
431
- return;
23
+ // if we are bun but should use node
24
+ if (!config.useBun) {
25
+ const compatImpl = await import('./compat-shim.js');
26
+ const program = await compatImpl.launchProgram(options);
27
+ closeHandler = program.endProgram;
28
+ return program.config;
432
29
  }
433
30
 
434
- const project = servers.get(projectRoot);
435
- servers.delete(projectRoot);
436
- project.terminate();
437
- console.log(chalk.grey(`\n\tHolodeck program ended`));
31
+ // use bun
32
+ // @ts-expect-error
33
+ options.useWorker = config.useWorker ?? true;
34
+ const nodeImpl = await import('./bun.js');
35
+ const program = await nodeImpl.launchProgram(options);
36
+ closeHandler = program.endProgram;
37
+ return program.config;
38
+ },
39
+ async endProgram() {
40
+ closeHandler();
438
41
  },
439
42
  };
@@ -0,0 +1,12 @@
1
+ import { launchProgram } from './node.js';
2
+
3
+ function startNodeServer() {
4
+ const args = process.argv.slice();
5
+
6
+ if (args.length) {
7
+ const options = JSON.parse(args[2]);
8
+ launchProgram(options);
9
+ }
10
+ }
11
+
12
+ startNodeServer();
@@ -0,0 +1,3 @@
1
+ import { startWorker } from './node.js';
2
+
3
+ startWorker();