File size: 2,211 Bytes
4ee7c6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const {test} = require('node:test');
const assert = require('node:assert/strict');
const vm = require('node:vm');
const fs = require('node:fs');
const code = fs.readFileSync(require('node:path').join(__dirname, '../usage.js'), 'utf8');
function setup(fail = false, origin = 'https://kalanosdev-lerobot-grader.hf.space') {
  const events = [], handlers = {}, clipboard = [];
  const context = {
    window: {}, location: {origin}, URL,
    document: {body: {}, getElementById: () => null, addEventListener: (name, fn) => {handlers[name] = fn;}},
    MutationObserver: class { observe() {} },
    navigator: {clipboard: {writeText: async text => {if (fail) throw Error('denied'); clipboard.push(text);}}},
    fetch: async (url, options) => {events.push(JSON.parse(options.body));},
  };
  vm.runInNewContext(code, context);
  return {events, handlers, clipboard, api: context.window.kalanosUsage};
}
test('counts successful copies without transmitting clipboard content', async () => {
  const state = setup();
  const status = {};
  await state.api.copy('private card contents', null, status);
  assert.deepEqual(state.clipboard, ['private card contents']);
  assert.deepEqual(state.events, [{event: 'hf_space_viewed'}, {event: 'hf_card_copied'}]);
  assert.equal(status.textContent, 'Copied');
});
test('failed clipboard writes do not count as copied', async () => {
  const state = setup(true), status = {};
  await state.api.copy('card', null, status);
  assert.deepEqual(state.events, [{event: 'hf_space_viewed'}]);
  assert.match(status.textContent, /manually/);
});
test('local previews still copy but send no analytics', async () => {
  const state = setup(false, 'http://127.0.0.1:7860');
  await state.api.copy('card');
  assert.deepEqual(state.events, []);
  assert.deepEqual(state.clipboard, ['card']);
});
test('only HF card expansions count as previews', () => {
  const state = setup();
  state.handlers.toggle({target: {matches: () => true, open: false}});
  state.handlers.toggle({target: {matches: () => false, open: true}});
  state.handlers.toggle({target: {matches: () => true, open: true}});
  assert.deepEqual(state.events, [{event: 'hf_space_viewed'}, {event: 'hf_card_previewed'}]);
});