hass-taste-test 0.2.7 → 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,47 +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
- 'default_config:',
139
- 'frontend:',
140
- 'http:',
141
- ` server_host: ${this.options.host}`,
142
- ` server_port: ${this.chosenPort}`,
143
- additionalConfig,
144
- ].join('\n');
145
- 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: [] } }));
146
215
  }
147
216
  /** Symlink custom component directories to the configuration directory */
148
217
  async linkComponents() {
@@ -163,71 +232,130 @@ class HomeAssistant {
163
232
  }
164
233
  /** Find an open port to launch Home Assistant */
165
234
  async findPort() {
166
- this.chosenPort = this.cache.startPort++;
167
- const server = net.createServer();
168
- server.listen(this.chosenPort, this.options.host);
169
- const success = await new Promise((resolve, reject) => {
170
- server.on('error', (e) => {
171
- if (e.code === 'EADDRINUSE' || e.code === 'EACCESS')
172
- resolve(false);
173
- else
174
- reject(e);
175
- });
176
- server.on('listening', () => {
177
- server.close();
178
- 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);
179
247
  });
180
- });
181
- if (!success)
182
- 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';
183
268
  }
184
- /** Creates a python virtual environment and installs Home Assistant */
185
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
+ };
186
283
  // Create virtual environment if it does not already exist
187
- await fs
188
- .access(this.venvDir)
189
- .catch(() => exec(this.options.python, ['-m', 'venv', this.venvDir]));
284
+ if (!(await exists(this.path_python())))
285
+ await createVenv(false);
190
286
  // Check if homeassistant needs an upgrade; saves a bit of time if it doesn't need one
191
- const installed = await this.hassVersion();
192
- if (!installed || installed !== this.cache.latestHass) {
193
- await exec(this.path_pip(), ['install', '--upgrade', 'wheel']);
194
- 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();
195
298
  }
196
299
  }
197
300
  async readCache() {
198
301
  try {
199
302
  const versionFile = await fs.stat(this.path_cache());
200
303
  if (Date.now() - versionFile.mtimeMs < 2000) {
201
- 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;
202
307
  }
203
308
  }
204
309
  catch (e) { }
205
310
  return {
206
- latestHass: await this.latestHAVersion(),
311
+ ...(await this.latestHAVersion()),
207
312
  startPort: 8130,
208
313
  };
209
314
  }
210
- /** Fetch the latest hass version from pypi */
315
+ /** Fetch the latest hass version, and the Python versions it supports, from pypi */
211
316
  async latestHAVersion() {
212
- const latest = await (0, node_fetch_1.default)('https://pypi.org/pypi/homeassistant/json').then((r) => r.json());
213
- 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');
214
333
  }
215
334
  /** Finds the version of Home Assistant installed, if any */
216
335
  async hassVersion() {
217
- const libFolders = await fs.readdir((0, path_1.join)(this.venvDir, 'lib'));
218
- const libs = await Promise.all(libFolders.map((f) => fs.readdir((0, path_1.join)(this.venvDir, 'lib', f, 'site-packages'))));
219
- const homeAssistant = libs
220
- .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
221
343
  .map((f) => f.match(/^homeassistant-(.*)\.dist-info/))
222
344
  .find((f) => f !== null);
223
345
  return homeAssistant ? homeAssistant[1] : null;
224
346
  }
225
- /** Checks if Home Assistant is listening on its TCP port */
226
- isUp = () => new Promise((resolve) => {
227
- net.createConnection(this.chosenPort, this.options.host)
228
- .on('connect', () => resolve(true))
229
- .on('error', () => resolve(false));
230
- });
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
+ }
231
359
  /** Complete onboarding and fetch short-lived access token */
232
360
  async onboard() {
233
361
  let login;
@@ -239,7 +367,7 @@ class HomeAssistant {
239
367
  username: this.options.username,
240
368
  password: this.options.password,
241
369
  });
242
- if (login.auth_code)
370
+ if (login?.auth_code)
243
371
  break;
244
372
  else
245
373
  await sleep();
@@ -249,13 +377,11 @@ class HomeAssistant {
249
377
  await sleep();
250
378
  }
251
379
  }
252
- if (!login.auth_code)
253
- throw new Error('No auth code found');
380
+ if (!login?.auth_code)
381
+ throw new Error('Onboarding failed: no auth code found');
254
382
  this.accessCode = login.auth_code;
255
383
  await this.launchWebsocket(this.accessCode);
256
- // Step through the onboarding pages
257
- await this.post('/api/onboarding/core_config', {}, true);
258
- await this.post('/api/onboarding/analytics', {}, true);
384
+ // Core config and analytics were already marked done (see writeOnboardingStorage)
259
385
  const response = await this.post('/api/onboarding/integration', { redirect_uri: this.url + '/?auth_callback=1' }, true);
260
386
  this.accessCode = response.auth_code;
261
387
  }
@@ -275,7 +401,7 @@ class HomeAssistant {
275
401
  return `${this.url}/${path}?auth_callback=1&code=${encodeURIComponent(code)}&state=${encodeURIComponent(state)}`;
276
402
  }
277
403
  async post(url, body, authorize = false) {
278
- const response = await (0, node_fetch_1.default)(this.url + url, {
404
+ const response = await fetch(this.url + url, {
279
405
  method: 'post',
280
406
  headers: {
281
407
  'Content-Type': 'application/json',
@@ -309,7 +435,7 @@ class HomeAssistant {
309
435
  params.append('client_id', this.clientId);
310
436
  params.append('code', code);
311
437
  params.append('grant_type', 'authorization_code');
312
- const response = await (0, node_fetch_1.default)(this.url + '/auth/token', {
438
+ const response = await fetch(this.url + '/auth/token', {
313
439
  method: 'post',
314
440
  body: params,
315
441
  });
@@ -324,9 +450,9 @@ class HomeAssistant {
324
450
  });
325
451
  this.ws = await hass.createConnection({
326
452
  auth,
327
- createSocket: async () => (0, socket_1.createSocket)(auth, false),
453
+ createSocket: async () => (0, socket_ts_1.createSocket)(auth, false),
328
454
  });
329
- (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 }));
330
456
  }
331
457
  async addIntegration(name) {
332
458
  const response = await this.post('/api/config/config_entries/flow', {
@@ -385,7 +511,7 @@ class HomeAssistant {
385
511
  }
386
512
  async Dashboard(config, options) {
387
513
  if (!this.options.browser)
388
- 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');
389
515
  const dashboard = await this.createDashboard({ title: options?.title });
390
516
  await this.setDashboardView(dashboard, config);
391
517
  const code = await this.fetchLoginCode();
@@ -401,18 +527,22 @@ class HomeAssistant {
401
527
  await this.options.browser.close();
402
528
  if (this.ws)
403
529
  this.ws.close();
404
- 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));
405
535
  this.process.kill('SIGINT');
406
- await new Promise((resolve) => this.process.on('exit', resolve));
536
+ await exited;
407
537
  }
408
538
  if (this.configDir)
409
- await fs.rm(this.configDir, { recursive: true });
539
+ await fs.rm(this.configDir, { recursive: true, force: true });
410
540
  }
411
541
  HassDashboard = class {
542
+ cards = [];
412
543
  parent;
413
544
  path;
414
545
  page;
415
- cards = [];
416
546
  constructor(parent, path, config, page) {
417
547
  this.parent = parent;
418
548
  this.path = path;
@@ -432,9 +562,9 @@ class HomeAssistant {
432
562
  }
433
563
  exports.HomeAssistant = HomeAssistant;
434
564
  class HassCard {
565
+ selectors;
435
566
  n;
436
567
  page;
437
- selectors;
438
568
  constructor(n, page, selectors) {
439
569
  this.n = n;
440
570
  this.page = page;
@@ -471,4 +601,3 @@ function multiply(n, configFn) {
471
601
  }
472
602
  return config;
473
603
  }
474
- 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
  }