hass-taste-test 0.2.6 → 0.3.0

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/lib/index.js CHANGED
@@ -15,37 +15,58 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
37
  };
28
38
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.multiply = exports.HassCard = exports.HomeAssistant = exports.PlaywrightBrowser = void 0;
39
+ exports.HassCard = exports.HomeAssistant = exports.PlaywrightPage = exports.PlaywrightBrowser = void 0;
40
+ exports.multiply = multiply;
30
41
  const child_process_1 = require("child_process");
31
42
  const path_1 = require("path");
32
43
  const os_1 = require("os");
33
- const node_fetch_1 = __importDefault(require("node-fetch"));
34
44
  const fs = __importStar(require("fs/promises"));
35
45
  const net = __importStar(require("net"));
36
46
  const hass = __importStar(require("home-assistant-js-websocket"));
37
- const socket_1 = require("./socket");
47
+ const socket_ts_1 = require("./socket.js");
38
48
  const proper_lockfile_1 = __importDefault(require("proper-lockfile"));
39
49
  const home_assistant_js_websocket_1 = require("home-assistant-js-websocket");
40
- var playwright_1 = require("./integrations/playwright");
41
- Object.defineProperty(exports, "PlaywrightBrowser", { enumerable: true, get: function () { return playwright_1.PlaywrightBrowser; } });
50
+ var playwright_ts_1 = require("./integrations/playwright.js");
51
+ Object.defineProperty(exports, "PlaywrightBrowser", { enumerable: true, get: function () { return playwright_ts_1.PlaywrightBrowser; } });
52
+ Object.defineProperty(exports, "PlaywrightPage", { enumerable: true, get: function () { return playwright_ts_1.PlaywrightPage; } });
42
53
  /** Sleeps for 100 ms */
43
54
  const sleep = () => new Promise((r) => setTimeout(r, 100));
44
- const exec = (command, args) => new Promise((resolve, reject) => {
45
- const proc = (0, child_process_1.spawn)(command, args, { stdio: 'inherit' });
55
+ /** Runs a command, rejecting if it cannot be started or exits with a non-zero code */
56
+ const exec = (command, args, quiet = false) => new Promise((resolve, reject) => {
57
+ const proc = (0, child_process_1.spawn)(command, args, { stdio: quiet ? 'ignore' : 'inherit' });
46
58
  proc.on('error', (err) => reject(err));
47
- proc.on('close', (code) => resolve(code));
59
+ proc.on('close', (code) => {
60
+ if (code === 0)
61
+ resolve();
62
+ else
63
+ reject(new Error(`${command} ${args.join(' ')} exited with code ${code}`));
64
+ });
48
65
  });
66
+ const exists = (path) => fs.access(path).then(() => true, () => false);
67
+ /** Whether uv (https://docs.astral.sh/uv/) is available on the PATH */
68
+ let uvAvailable;
69
+ const hasUv = () => (uvAvailable ??= exec('uv', ['--version'], true).then(() => true, () => false));
49
70
  class HomeAssistant {
50
71
  venvDir;
51
72
  configDir;
@@ -57,12 +78,10 @@ class HomeAssistant {
57
78
  options;
58
79
  dashboards = 0;
59
80
  entities = {};
60
- started = false;
61
81
  ws;
62
82
  constructor(options) {
63
83
  this.venvDir = (0, path_1.join)((0, os_1.tmpdir)(), 'hasstest-venv');
64
84
  this.options = {
65
- python: 'python3',
66
85
  hassArgs: [],
67
86
  host: '127.0.0.1',
68
87
  port: null,
@@ -77,8 +96,9 @@ class HomeAssistant {
77
96
  path_confFile = () => (0, path_1.join)(this.configDir, 'configuration.yaml');
78
97
  path_componentsDir = () => (0, path_1.join)(this.configDir, 'custom_components');
79
98
  path_wwwDir = () => (0, path_1.join)(this.configDir, 'www');
99
+ path_storageDir = () => (0, path_1.join)(this.configDir, '.storage');
80
100
  path_hass = () => (0, path_1.join)(this.venvDir, 'bin/hass');
81
- path_pip = () => (0, path_1.join)(this.venvDir, 'bin/pip');
101
+ path_python = () => (0, path_1.join)(this.venvDir, 'bin/python');
82
102
  path_cache = () => (0, path_1.join)((0, os_1.tmpdir)(), 'hasstest-cache');
83
103
  /** Create and connect to an isolated Home Assistant instance */
84
104
  static async create(config, options) {
@@ -102,46 +122,96 @@ class HomeAssistant {
102
122
  ]);
103
123
  // Step 2: Create venv and sort out networking under lock
104
124
  const releaseLock = await this.acquireLock();
105
- this.cache = await this.readCache();
106
- await Promise.all([
107
- this.findPort().then(() => this.writeYAMLConfiguration(config)),
108
- this.setupVenv(),
109
- ]);
110
- await fs.writeFile(this.path_cache(), JSON.stringify(this.cache));
111
- await releaseLock();
125
+ try {
126
+ this.cache = await this.readCache();
127
+ await Promise.all([this.findPort(), this.setupVenv()]);
128
+ await fs.writeFile(this.path_cache(), JSON.stringify(this.cache));
129
+ }
130
+ finally {
131
+ await releaseLock();
132
+ }
133
+ await this.writeConfiguration(config);
112
134
  // Step 3: Start Home Assistant and onboard
113
- this.process = (0, child_process_1.spawn)(this.path_hass(), ['-c', this.configDir, '-v', ...this.options.hassArgs], { stdio: 'pipe' });
114
- this.process.stderr.on('data', (d) => {
115
- if (d.includes('Starting Home Assistant'))
116
- this.started = true;
117
- process.stderr.write(d);
118
- });
119
- this.process.on('error', (e) => {
120
- console.error(`----\nHome Assistant is having trouble starting. This is likely due to a problem with your virtual environment; try removing the venv folder at ${this.venvDir} and re-running hass-taste-test\n---`);
121
- throw e;
135
+ this.process = (0, child_process_1.spawn)(this.path_hass(), ['-c', this.configDir, ...this.options.hassArgs], {
136
+ stdio: 'pipe',
122
137
  });
123
- await new Promise(async (resolve, reject) => {
138
+ this.process.stderr.pipe(process.stderr);
139
+ await new Promise((resolve, reject) => {
140
+ let exited = false;
141
+ this.process.on('error', (e) => {
142
+ exited = true;
143
+ console.error(`----\nHome Assistant is having trouble starting. This is likely due to a problem with your virtual environment; try removing the venv folder at ${this.venvDir} and re-running hass-taste-test\n---`);
144
+ reject(e);
145
+ });
124
146
  // Wait for Home Assistant to start, but quit early if the process exits
125
147
  this.process.on('close', (code) => {
126
- if (code != 0)
127
- reject(new Error(`Home Assistant exited with code ${code}`));
148
+ exited = true;
149
+ reject(new Error(`Home Assistant exited with code ${code}`));
128
150
  });
129
- while (!this.started || !(await this.isUp()))
130
- await sleep();
131
- resolve();
151
+ (async () => {
152
+ while (!exited && !(await this.isUp()))
153
+ await sleep();
154
+ resolve();
155
+ })();
132
156
  });
133
157
  await this.onboard();
134
- }
135
- /** Write configuration.yaml */
136
- async writeYAMLConfiguration(additionalConfig) {
137
- const config = [
138
- 'frontend:',
139
- 'http:',
140
- ` server_host: ${this.options.host}`,
141
- ` server_port: ${this.chosenPort}`,
142
- additionalConfig,
143
- ].join('\n');
144
- fs.writeFile(this.path_confFile(), config);
158
+ await this.waitUntilRunning();
159
+ }
160
+ /** Write configuration.yaml, plus HTTP settings in whichever form this Home Assistant expects */
161
+ async writeConfiguration(additionalConfig) {
162
+ // Only the frontend: its dependencies cover everything Hass Taste Test uses (auth, onboarding,
163
+ // config entries, lovelace, repairs, websocket API). default_config would also start ~20 more
164
+ // integrations (bluetooth, zeroconf, cloud, ...) that slow startup and fill the logs.
165
+ const config = ['frontend:'];
166
+ // Keep test output readable: only log errors, unless the caller configures logging themselves
167
+ if (!/^logger:/m.test(additionalConfig))
168
+ config.push('logger:', ' default: error');
169
+ if (await this.usesHttpStorage()) {
170
+ await this.writeHttpStorage();
171
+ }
172
+ else {
173
+ config.push('http:', ` server_host: ${this.options.host}`, ` server_port: ${this.chosenPort}`);
174
+ }
175
+ config.push(additionalConfig);
176
+ await fs.writeFile(this.path_confFile(), config.join('\n'));
177
+ await this.writeOnboardingStorage();
178
+ }
179
+ /**
180
+ * Newer Home Assistant versions keep HTTP settings in `.storage/http` and only import the
181
+ * `http:` YAML block once. That import is applied as an unconfirmed trial configuration,
182
+ * which pops up a confirmation dialog in the frontend and reverts (restarting Home
183
+ * Assistant) after 5 minutes. Detect these versions so we can skip the YAML entirely.
184
+ */
185
+ async usesHttpStorage() {
186
+ const configModule = (0, path_1.join)(await this.sitePackages(), 'homeassistant/components/http/config.py');
187
+ const source = await fs.readFile(configModule, 'utf-8').catch(() => '');
188
+ return source.includes('yaml_migration_done');
189
+ }
190
+ /**
191
+ * Seed the HTTP config store so Home Assistant boots straight into our host and port.
192
+ * This uses the original (version 1) storage format, which Home Assistant migrates on load
193
+ * into a confirmed ("stable") config with all defaults filled in.
194
+ */
195
+ async writeHttpStorage() {
196
+ await fs.mkdir(this.path_storageDir(), { recursive: true });
197
+ await fs.writeFile((0, path_1.join)(this.path_storageDir(), 'http'), JSON.stringify({
198
+ version: 1,
199
+ minor_version: 1,
200
+ key: 'http',
201
+ data: { server_host: [this.options.host], server_port: this.chosenPort },
202
+ }));
203
+ }
204
+ /**
205
+ * Seed the onboarding store so the core config and analytics steps start out done. Finishing
206
+ * the core config step kicks off config flows for shopping_list, met, google_translate, and
207
+ * radio_browser, which are never needed for tests and log errors when Home Assistant is closed
208
+ * before they finish setting up. Storage version 2 predates both steps, so every Home Assistant
209
+ * release since then migrates this file by marking them done, leaving only the user and
210
+ * integration steps (which hand us auth codes) for onboard() to complete.
211
+ */
212
+ async writeOnboardingStorage() {
213
+ await fs.mkdir(this.path_storageDir(), { recursive: true });
214
+ await fs.writeFile((0, path_1.join)(this.path_storageDir(), 'onboarding'), JSON.stringify({ version: 2, minor_version: 1, key: 'onboarding', data: { done: [] } }));
145
215
  }
146
216
  /** Symlink custom component directories to the configuration directory */
147
217
  async linkComponents() {
@@ -162,71 +232,130 @@ class HomeAssistant {
162
232
  }
163
233
  /** Find an open port to launch Home Assistant */
164
234
  async findPort() {
165
- this.chosenPort = this.cache.startPort++;
166
- const server = net.createServer();
167
- server.listen(this.chosenPort, this.options.host);
168
- const success = await new Promise((resolve, reject) => {
169
- server.on('error', (e) => {
170
- if (e.code === 'EADDRINUSE' || e.code === 'EACCESS')
171
- resolve(false);
172
- else
173
- reject(e);
174
- });
175
- server.on('listening', () => {
176
- server.close();
177
- resolve(true);
235
+ for (;;) {
236
+ this.chosenPort = this.cache.startPort++;
237
+ const server = net.createServer();
238
+ const success = await new Promise((resolve, reject) => {
239
+ server.on('error', (e) => {
240
+ if (e.code === 'EADDRINUSE' || e.code === 'EACCES')
241
+ resolve(false);
242
+ else
243
+ reject(e);
244
+ });
245
+ server.on('listening', () => server.close(() => resolve(true)));
246
+ server.listen(this.chosenPort, this.options.host);
178
247
  });
179
- });
180
- if (!success)
181
- await this.findPort();
248
+ if (success)
249
+ return;
250
+ }
251
+ }
252
+ /** Creates a python virtual environment and installs Home Assistant (using uv if available) */
253
+ async chooseInstaller() {
254
+ const requested = process.env.HASS_TASTE_TEST_INSTALLER;
255
+ if (requested === 'pip')
256
+ return 'pip';
257
+ if (requested === 'uv') {
258
+ if (!(await hasUv()))
259
+ throw new Error('The uv installer was requested, but uv is not on the PATH');
260
+ return 'uv';
261
+ }
262
+ if (requested)
263
+ throw new Error(`Unknown installer "${requested}"; expected "uv" or "pip"`);
264
+ if (await hasUv())
265
+ return 'uv';
266
+ console.warn('uv was not found on your PATH; falling back to pip. Install uv (https://docs.astral.sh/uv/) for much faster installs.');
267
+ return 'pip';
182
268
  }
183
- /** Creates a python virtual environment and installs Home Assistant */
184
269
  async setupVenv() {
270
+ const uv = (await this.chooseInstaller()) === 'uv';
271
+ const python = this.cache.requiresPython;
272
+ const clearFlag = (clear) => (clear ? ['--clear'] : []);
273
+ const createVenv = (clear) => uv
274
+ ? exec('uv', ['venv', ...clearFlag(clear), '--python', python, this.venvDir])
275
+ : exec('python3', ['-m', 'venv', ...clearFlag(clear), this.venvDir]);
276
+ const install = () => {
277
+ // Pin the version so an outdated interpreter fails loudly instead of resolving an old release
278
+ const pkg = `homeassistant==${this.cache.latestHass}`;
279
+ return uv
280
+ ? exec('uv', ['pip', 'install', '--python', this.path_python(), pkg])
281
+ : exec(this.path_python(), ['-m', 'pip', 'install', pkg]);
282
+ };
185
283
  // Create virtual environment if it does not already exist
186
- await fs
187
- .access(this.venvDir)
188
- .catch(() => exec(this.options.python, ['-m', 'venv', this.venvDir]));
284
+ if (!(await exists(this.path_python())))
285
+ await createVenv(false);
189
286
  // Check if homeassistant needs an upgrade; saves a bit of time if it doesn't need one
190
- const installed = await this.hassVersion();
191
- if (!installed || installed !== this.cache.latestHass) {
192
- await exec(this.path_pip(), ['install', '--upgrade', 'wheel']);
193
- await exec(this.path_pip(), ['install', '--upgrade', 'homeassistant']);
287
+ if ((await this.hassVersion()) === this.cache.latestHass)
288
+ return;
289
+ try {
290
+ await install();
291
+ }
292
+ catch (e) {
293
+ // Most likely the venv's Python is too old for the latest Home Assistant, or the venv
294
+ // was created by uv (which does not include pip) and pip is now being used. Rebuild it.
295
+ console.warn(`Installing Home Assistant failed (${e}). Recreating ${this.venvDir}`);
296
+ await createVenv(true);
297
+ await install();
194
298
  }
195
299
  }
196
300
  async readCache() {
197
301
  try {
198
302
  const versionFile = await fs.stat(this.path_cache());
199
303
  if (Date.now() - versionFile.mtimeMs < 2000) {
200
- return await JSON.parse(await fs.readFile(this.path_cache(), 'utf-8'));
304
+ const cache = JSON.parse(await fs.readFile(this.path_cache(), 'utf-8'));
305
+ if (cache.requiresPython)
306
+ return cache;
201
307
  }
202
308
  }
203
309
  catch (e) { }
204
310
  return {
205
- latestHass: await this.latestHAVersion(),
311
+ ...(await this.latestHAVersion()),
206
312
  startPort: 8130,
207
313
  };
208
314
  }
209
- /** Fetch the latest hass version from pypi */
315
+ /** Fetch the latest hass version, and the Python versions it supports, from pypi */
210
316
  async latestHAVersion() {
211
- const latest = await (0, node_fetch_1.default)('https://pypi.org/pypi/homeassistant/json').then((r) => r.json());
212
- return latest.info.version;
317
+ const response = await fetch('https://pypi.org/pypi/homeassistant/json');
318
+ if (!response.ok)
319
+ throw new Error(`Could not query PyPI: HTTP ${response.status}`);
320
+ const latest = (await response.json());
321
+ return {
322
+ latestHass: latest.info.version,
323
+ requiresPython: latest.info.requires_python || '3',
324
+ };
325
+ }
326
+ /** Path to the venv's site-packages directory */
327
+ async sitePackages() {
328
+ const libFolders = await fs.readdir((0, path_1.join)(this.venvDir, 'lib')).catch(() => []);
329
+ const python = libFolders.find((f) => f.startsWith('python'));
330
+ if (!python)
331
+ throw new Error(`Could not find a Python installation in ${this.venvDir}`);
332
+ return (0, path_1.join)(this.venvDir, 'lib', python, 'site-packages');
213
333
  }
214
334
  /** Finds the version of Home Assistant installed, if any */
215
335
  async hassVersion() {
216
- const libFolders = await fs.readdir((0, path_1.join)(this.venvDir, 'lib'));
217
- const libs = await Promise.all(libFolders.map((f) => fs.readdir((0, path_1.join)(this.venvDir, 'lib', f, 'site-packages'))));
218
- const homeAssistant = libs
219
- .flat()
336
+ // An interrupted install can leave package metadata behind without the entry point
337
+ if (!(await exists(this.path_hass())))
338
+ return null;
339
+ const files = await this.sitePackages()
340
+ .then((dir) => fs.readdir(dir))
341
+ .catch(() => []);
342
+ const homeAssistant = files
220
343
  .map((f) => f.match(/^homeassistant-(.*)\.dist-info/))
221
344
  .find((f) => f !== null);
222
345
  return homeAssistant ? homeAssistant[1] : null;
223
346
  }
224
- /** Checks if Home Assistant is listening on its TCP port */
225
- isUp = () => new Promise((resolve) => {
226
- net.createConnection(this.chosenPort, this.options.host)
227
- .on('connect', () => resolve(true))
228
- .on('error', () => resolve(false));
229
- });
347
+ /** Checks if Home Assistant is serving the onboarding API, which onboard() starts with */
348
+ isUp = () => fetch(this.url + '/api/onboarding')
349
+ .then((response) => response.ok)
350
+ .catch(() => false);
351
+ /**
352
+ * Wait for Home Assistant to finish starting. Until then it has not installed its signal
353
+ * handlers, so close() would interrupt startup and log a KeyboardInterrupt traceback.
354
+ */
355
+ async waitUntilRunning() {
356
+ while ((await hass.getConfig(this.ws)).state !== 'RUNNING')
357
+ await sleep();
358
+ }
230
359
  /** Complete onboarding and fetch short-lived access token */
231
360
  async onboard() {
232
361
  let login;
@@ -238,7 +367,7 @@ class HomeAssistant {
238
367
  username: this.options.username,
239
368
  password: this.options.password,
240
369
  });
241
- if (login.auth_code)
370
+ if (login?.auth_code)
242
371
  break;
243
372
  else
244
373
  await sleep();
@@ -248,13 +377,11 @@ class HomeAssistant {
248
377
  await sleep();
249
378
  }
250
379
  }
251
- if (!login.auth_code)
252
- throw new Error('No auth code found');
380
+ if (!login?.auth_code)
381
+ throw new Error('Onboarding failed: no auth code found');
253
382
  this.accessCode = login.auth_code;
254
383
  await this.launchWebsocket(this.accessCode);
255
- // Step through the onboarding pages
256
- await this.post('/api/onboarding/core_config', undefined, true);
257
- await this.post('/api/onboarding/analytics', {}, true);
384
+ // Core config and analytics were already marked done (see writeOnboardingStorage)
258
385
  const response = await this.post('/api/onboarding/integration', { redirect_uri: this.url + '/?auth_callback=1' }, true);
259
386
  this.accessCode = response.auth_code;
260
387
  }
@@ -274,13 +401,13 @@ class HomeAssistant {
274
401
  return `${this.url}/${path}?auth_callback=1&code=${encodeURIComponent(code)}&state=${encodeURIComponent(state)}`;
275
402
  }
276
403
  async post(url, body, authorize = false) {
277
- const response = await (0, node_fetch_1.default)(this.url + url, {
404
+ const response = await fetch(this.url + url, {
278
405
  method: 'post',
279
406
  headers: {
280
407
  'Content-Type': 'application/json',
281
408
  ...(authorize ? { Authorization: 'Bearer ' + this.accessToken } : undefined),
282
409
  },
283
- body: body ? JSON.stringify({ client_id: this.clientId, ...body }) : undefined,
410
+ body: JSON.stringify({ client_id: this.clientId, ...body }),
284
411
  });
285
412
  return (await response.json());
286
413
  }
@@ -308,7 +435,7 @@ class HomeAssistant {
308
435
  params.append('client_id', this.clientId);
309
436
  params.append('code', code);
310
437
  params.append('grant_type', 'authorization_code');
311
- const response = await (0, node_fetch_1.default)(this.url + '/auth/token', {
438
+ const response = await fetch(this.url + '/auth/token', {
312
439
  method: 'post',
313
440
  body: params,
314
441
  });
@@ -323,9 +450,9 @@ class HomeAssistant {
323
450
  });
324
451
  this.ws = await hass.createConnection({
325
452
  auth,
326
- createSocket: async () => (0, socket_1.createSocket)(auth, false),
453
+ createSocket: async () => (0, socket_ts_1.createSocket)(auth, false),
327
454
  });
328
- (0, home_assistant_js_websocket_1.subscribeEntities)(this.ws, (e) => (this.entities = { ...this.entities, ...e }));
455
+ (0, home_assistant_js_websocket_1.subscribeEntityStates)(this.ws, (e) => (this.entities = { ...this.entities, ...e }));
329
456
  }
330
457
  async addIntegration(name) {
331
458
  const response = await this.post('/api/config/config_entries/flow', {
@@ -384,7 +511,7 @@ class HomeAssistant {
384
511
  }
385
512
  async Dashboard(config, options) {
386
513
  if (!this.options.browser)
387
- throw new Error('Cannot launch a dashboard without a browser integration. Make sure to specify options.integration');
514
+ throw new Error('Cannot launch a dashboard without a browser integration. Make sure to specify options.browser');
388
515
  const dashboard = await this.createDashboard({ title: options?.title });
389
516
  await this.setDashboardView(dashboard, config);
390
517
  const code = await this.fetchLoginCode();
@@ -400,18 +527,22 @@ class HomeAssistant {
400
527
  await this.options.browser.close();
401
528
  if (this.ws)
402
529
  this.ws.close();
403
- if (this.process) {
530
+ const running = this.process?.pid !== undefined &&
531
+ this.process.exitCode === null &&
532
+ this.process.signalCode === null;
533
+ if (running) {
534
+ const exited = new Promise((resolve) => this.process.once('exit', resolve));
404
535
  this.process.kill('SIGINT');
405
- await new Promise((resolve) => this.process.on('exit', resolve));
536
+ await exited;
406
537
  }
407
538
  if (this.configDir)
408
- await fs.rm(this.configDir, { recursive: true });
539
+ await fs.rm(this.configDir, { recursive: true, force: true });
409
540
  }
410
541
  HassDashboard = class {
542
+ cards = [];
411
543
  parent;
412
544
  path;
413
545
  page;
414
- cards = [];
415
546
  constructor(parent, path, config, page) {
416
547
  this.parent = parent;
417
548
  this.path = path;
@@ -431,9 +562,9 @@ class HomeAssistant {
431
562
  }
432
563
  exports.HomeAssistant = HomeAssistant;
433
564
  class HassCard {
565
+ selectors;
434
566
  n;
435
567
  page;
436
- selectors;
437
568
  constructor(n, page, selectors) {
438
569
  this.n = n;
439
570
  this.page = page;
@@ -470,4 +601,3 @@ function multiply(n, configFn) {
470
601
  }
471
602
  return config;
472
603
  }
473
- exports.multiply = multiply;
@@ -1,29 +1,4 @@
1
- interface IgnoreAttributesForTags {
2
- /** tags on which to ignore the given attributes */
3
- tags: string[];
4
- /** attributes to ignore for the given tags */
5
- attributes: string[];
6
- }
7
- interface DiffOptions {
8
- /** array of attributes to ignore, when given a string that attribute will be ignored on all tags
9
- * when given an object of type `IgnoreAttributesForTags`, you can specify on which tags to ignore which attributes */
10
- ignoreAttributes: (string | IgnoreAttributesForTags)[];
11
- /** array of tags to ignore, these tags are stripped from the output */
12
- ignoreTags: string[];
13
- /** array of tags whose children to ignore, the children of these tags are stripped from the output */
14
- ignoreChildren: string[];
15
- /** like ignoreChildren, but applies to shadow DOM rather than direct descendants */
16
- ignoreShadowChildren: string[];
17
- /** array of attributes which should be removed when empty.
18
- * Be careful not to add any boolean attributes here (e.g. `hidden`) unless you know what you're doing */
19
- stripEmptyAttributes: string[];
20
- /** whether to strip attributes from Lit & Polymer with undefined values */
21
- stripUndefinedAttributes: boolean;
22
- }
23
- declare const DEFAULT_IGNORE_TAGS: string[];
24
- declare const DEFAULT_IGNORE_SHADOW_CHILDREN: string[];
25
- declare const DEFAULT_EMPTY_ATTRS: string[];
26
- declare const VOID_ELEMENTS: string[];
1
+ import type { DiffOptions } from '../types.ts';
27
2
  /**
28
3
  * Restructures given HTML string, returning it in a format which can be used for comparison:
29
4
  * - whitespace and newlines are normalized
@@ -46,4 +21,4 @@ declare const VOID_ELEMENTS: string[];
46
21
  * @param {DiffOptions} [options]
47
22
  * @returns {string} html restructured in a diffable format
48
23
  */
49
- declare function getDiffableHTML(container: Node, options?: DiffOptions): string;
24
+ export declare function getDiffableHTML(container: Node, options?: Partial<DiffOptions>): string;
@@ -3,33 +3,8 @@
3
3
  // Changes are licensed under the repository license (see LICENSE.md)
4
4
  //
5
5
  // The code has been modified to traverse shadow DOM & find Lit and Polymer attributes
6
- const DEFAULT_IGNORE_TAGS = ['script', 'style'];
7
- const DEFAULT_IGNORE_SHADOW_CHILDREN = [
8
- 'ha-icon',
9
- 'ha-state-icon',
10
- 'ha-slider',
11
- 'mwc-button',
12
- 'paper-input', // Polymer elements
13
- ];
14
- const DEFAULT_EMPTY_ATTRS = ['class', 'id'];
15
- const VOID_ELEMENTS = [
16
- 'area',
17
- 'base',
18
- 'br',
19
- 'col',
20
- 'embed',
21
- 'hr',
22
- 'img',
23
- 'input',
24
- 'keygen',
25
- 'link',
26
- 'menuitem',
27
- 'meta',
28
- 'param',
29
- 'source',
30
- 'track',
31
- 'wbr',
32
- ];
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.getDiffableHTML = getDiffableHTML;
33
8
  /**
34
9
  * Restructures given HTML string, returning it in a format which can be used for comparison:
35
10
  * - whitespace and newlines are normalized
@@ -53,6 +28,34 @@ const VOID_ELEMENTS = [
53
28
  * @returns {string} html restructured in a diffable format
54
29
  */
55
30
  function getDiffableHTML(container, options) {
31
+ // Constants live inside the function because it is serialized and run in the browser
32
+ const DEFAULT_IGNORE_TAGS = ['script', 'style'];
33
+ const DEFAULT_IGNORE_SHADOW_CHILDREN = [
34
+ 'ha-icon',
35
+ 'ha-state-icon',
36
+ 'ha-slider', // Home Assistant elements
37
+ 'mwc-button', // Material web components
38
+ 'paper-input', // Polymer elements
39
+ ];
40
+ const DEFAULT_EMPTY_ATTRS = ['class', 'id'];
41
+ const VOID_ELEMENTS = [
42
+ 'area',
43
+ 'base',
44
+ 'br',
45
+ 'col',
46
+ 'embed',
47
+ 'hr',
48
+ 'img',
49
+ 'input',
50
+ 'keygen',
51
+ 'link',
52
+ 'menuitem',
53
+ 'meta',
54
+ 'param',
55
+ 'source',
56
+ 'track',
57
+ 'wbr',
58
+ ];
56
59
  const ignoreAttributes = options?.ignoreAttributes
57
60
  ? options.ignoreAttributes.filter((e) => typeof e === 'string')
58
61
  : [];
@@ -1,6 +1,5 @@
1
- /// <reference types="node" />
2
- import { Browser, ElementHandle, Page, LaunchOptions, BrowserContext } from 'playwright';
3
- import { BrowserIntegration, BrowserPage, DashboardOptions, DiffOptions } from '../types';
1
+ import type { Browser, ElementHandle, Page, LaunchOptions, BrowserContext } from 'playwright';
2
+ import type { BrowserIntegration, BrowserPage, DashboardOptions, DiffOptions } from '../types.ts';
4
3
  export type PlaywrightElement = ElementHandle<Node>;
5
4
  export declare class PlaywrightBrowser implements BrowserIntegration<PlaywrightElement> {
6
5
  private static browsers;
@@ -15,10 +14,10 @@ export declare class PlaywrightBrowser implements BrowserIntegration<PlaywrightE
15
14
  export declare class PlaywrightPage implements BrowserPage<PlaywrightElement> {
16
15
  private page;
17
16
  constructor(page: Page);
18
- getNthCard(n: number): Promise<ElementHandle<SVGElement | HTMLElement>>;
19
- shadowHTML(element: PlaywrightElement, options?: DiffOptions): Promise<string>;
20
- screenshot(element: PlaywrightElement): Promise<Buffer>;
21
- find(element: PlaywrightElement, selector: string): Promise<ElementHandle<SVGElement | HTMLElement> | null>;
17
+ getNthCard(n: number): Promise<ElementHandle<HTMLElement | SVGElement>>;
18
+ shadowHTML(element: PlaywrightElement, options?: Partial<DiffOptions>): Promise<string>;
19
+ screenshot(element: PlaywrightElement): Promise<Buffer<ArrayBufferLike>>;
20
+ find(element: PlaywrightElement, selector: string): Promise<ElementHandle<HTMLElement | SVGElement> | null>;
22
21
  textContent(element: PlaywrightElement): Promise<string>;
23
22
  get playwright(): Page;
24
23
  }