create-heresay 0.2.21 → 0.2.22

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-heresay",
3
- "version": "0.2.21",
3
+ "version": "0.2.22",
4
4
  "description": "Set up your own Heresay: in-app feedback that every report gets a hearing. Creates a Firebase project in your Google account and deploys the dashboard, API and SDK to it.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/release/VERSION CHANGED
@@ -1 +1 @@
1
- 0.2.21
1
+ 0.2.22
@@ -52,6 +52,14 @@ export function parseContext(v) {
52
52
  framework: isFramework(c.framework) ? c.framework : null,
53
53
  page_title: f('page_title'), page_url: pageUrl(c.page_url),
54
54
  viewport: typeof c.viewport === 'string' && /^\d{1,5}x\d{1,5}$/.test(c.viewport) ? c.viewport : null,
55
+ locale: typeof c.locale === 'string' && /^[A-Za-z]{2,3}([_-][A-Za-z0-9]{2,8}){0,3}$/.test(c.locale) ? c.locale : null,
56
+ timezone: typeof c.timezone === 'string' && /^[A-Za-z0-9_+\-/]{1,64}$/.test(c.timezone) ? c.timezone : null,
57
+ theme: c.theme === 'light' || c.theme === 'dark' ? c.theme : null,
58
+ device: str(c.device, 80), network: str(c.network, 80),
59
+ screen: typeof c.screen === 'string' && /^\d{1,5}x\d{1,5}(@[\d.]{1,4}x)?$/.test(c.screen) ? c.screen : null,
60
+ session_s: typeof c.session_s === 'number' && Number.isFinite(c.session_s) && c.session_s >= 0
61
+ ? Math.min(Math.round(c.session_s), 30 * 86_400) : null,
62
+ settings: str(c.settings, 120),
55
63
  };
56
64
  }
57
65
  /** http(s) only, and the query string dropped here too: it is where apps put tokens. */
@@ -96,8 +104,13 @@ export function agentPrompt(project, t) {
96
104
  const ctx = [
97
105
  ['Screen / route', c.route], ['Page', c.page_title], ['URL', c.page_url],
98
106
  ['App version', c.app_version], ['Platform', c.platform], ['OS', c.os], ['Browser', c.browser],
99
- ['Viewport', c.viewport],
107
+ ['Device', c.device], ['Viewport', c.viewport], ['Screen', c.screen], ['Theme', c.theme],
108
+ ['Language', c.locale], ['Time zone', c.timezone], ['Network', c.network], ['Settings', c.settings],
109
+ ['In the app for', c.session_s != null ? duration(c.session_s) : null],
100
110
  ].filter(([, v]) => v).map(([k, v]) => `- ${k}: ${v}`).join('\n');
111
+ // The last thing that went wrong, so it isn't lost in a long trail.
112
+ const worst = [...(t.trail ?? [])].reverse().find((e) => e.kind === 'error')
113
+ ?? [...(t.trail ?? [])].reverse().find((e) => e.kind === 'request' || e.kind === 'warn');
101
114
  const fence = '"""';
102
115
  return [
103
116
  `A user of ${project.name} reported something and the developer accepted it. Fix it.`,
@@ -110,12 +123,21 @@ export function agentPrompt(project, t) {
110
123
  fence,
111
124
  t.text.replaceAll(fence, "''"),
112
125
  ...(t.reporter_note ? ['', `About their setup: ${t.reporter_note.replaceAll(fence, "''")}`] : []),
126
+ ...(worst ? ['', `Last thing that went wrong, ${duration(worst.ago)} before they sent it: ${worst.text.replaceAll(fence, "''")}`] : []),
113
127
  ...(t.trail?.length ? ['', 'What happened in the app before they sent it, recorded by the SDK on their device (oldest first):',
114
128
  ...trailLines(t.trail).map((l) => l.replaceAll(fence, "''"))] : []),
115
129
  fence,
116
130
  ...(t.note ? ['', `Developer's note: ${t.note}`] : []),
117
131
  ].join('\n');
118
132
  }
133
+ /** 75 → '1 min 15 s', 7300 → '2 h 1 min'. */
134
+ export function duration(s) {
135
+ if (s < 60)
136
+ return `${s} s`;
137
+ if (s < 3600)
138
+ return `${Math.floor(s / 60)} min${s % 60 ? ` ${s % 60} s` : ''}`;
139
+ return `${Math.floor(s / 3600)} h${Math.floor(s % 3600 / 60) ? ` ${Math.floor(s % 3600 / 60)} min` : ''}`;
140
+ }
119
141
  export async function handle(req, deps) {
120
142
  try {
121
143
  return await route(req, deps);
@@ -7,7 +7,7 @@
7
7
  * before reporting. So it is cleaned here whatever the SDK did, and an agent gets it fenced.
8
8
  */
9
9
  export const TRAIL_KINDS = ['page', 'click', 'request', 'error', 'warn', 'state'];
10
- export const TRAIL_LIMITS = { events: 30, textMax: 200, detailMax: 600, totalMax: 8000, agoMax: 3600, nMax: 999 };
10
+ export const TRAIL_LIMITS = { events: 50, textMax: 200, detailMax: 600, totalMax: 12000, agoMax: 3600, nMax: 999 };
11
11
  /**
12
12
  * Blanks what tends to be personal or secret, in case the SDK missed it or something other than
13
13
  * the SDK sent this. Emails, bearer tokens, JWTs, long opaque strings, long numbers, query strings.
@@ -1,3 +1,3 @@
1
1
  /** The Heresay release. Bumped by the release script; the CLI and /v1/health report it. */
2
- export const VERSION = '0.2.21';
2
+ export const VERSION = '0.2.22';
3
3
  //# sourceMappingURL=version.js.map
@@ -1374,6 +1374,14 @@
1374
1374
  .filter(Boolean).join(' · ');
1375
1375
  }
1376
1376
 
1377
+ /** The device around the app: what layout, language and timing bugs depend on. */
1378
+ function deviceLine(c) {
1379
+ var s = c.session_s;
1380
+ var inApp = s == null ? null : 'in the app ' + (s < 60 ? s + ' s' : s < 3600 ? Math.floor(s / 60) + ' min' : Math.floor(s / 3600) + ' h ' + Math.floor(s % 3600 / 60) + ' min');
1381
+ return [c.device, c.screen, c.theme && c.theme + ' mode', c.locale, c.timezone, c.network, c.settings, inApp]
1382
+ .filter(Boolean).join(' · ');
1383
+ }
1384
+
1377
1385
  var TRAIL_LABEL = { page: 'Page', click: 'Click', request: 'Request', error: 'Error', warn: 'Warning', state: 'Device' };
1378
1386
 
1379
1387
  /**
@@ -1548,6 +1556,7 @@
1548
1556
  ]),
1549
1557
  el('p', { class: 'text', text: r.text }),
1550
1558
  el('div', { class: 'ctx', text: ctxLine(r.context) }),
1559
+ deviceLine(r.context) ? el('div', { class: 'ctx', text: deviceLine(r.context) }) : null,
1551
1560
  r.context.page_url ? el('div', { class: 'ctx' }, [el('a', { href: r.context.page_url, target: '_blank', rel: 'noopener noreferrer', text: r.context.page_url })]) : null,
1552
1561
  reporterLine(r.context, r.reporter),
1553
1562
  trailView(r.trail),
@@ -73,9 +73,14 @@ default says what matters.
73
73
  **The trail**
74
74
 
75
75
  With each report, the widget attaches what happened in the app in the last few minutes:
76
- pages visited, what was clicked (by its label), requests that failed, errors and console
77
- warnings. The reporter sees it in the form and can switch it off or leave parts out. Never what
78
- anyone typed, request bodies, headers or query strings. On by default; change it only when asked.
76
+ pages visited (with their titles), what was clicked (by its label, and the dialog, form or menu
77
+ it was in), forms sent and fields the browser refused (by label and why), requests that failed
78
+ or took 3 s or more (with how long), errors, console warnings, alerts the app showed, freezes of
79
+ a second or more, and leaving the tab and coming back. Each report also carries the device
80
+ around the app: phone or desktop, touch or mouse, screen, light or dark, language, time zone,
81
+ connection, and settings such as reduced motion. The reporter sees all of it in the form and can
82
+ switch the trail off or leave parts out. Never what anyone typed, request bodies, headers or
83
+ query strings. On by default; change it only when asked.
79
84
 
80
85
  | Attribute | Values |
81
86
  | --- | --- |
@@ -89,8 +89,8 @@
89
89
  what: 'What is it?', whatHappened: 'What happened?', ph: 'What happened, or what would you change?',
90
90
  send: 'Send', sending: 'Sending…',
91
91
  pickType: 'Pick what kind of report this is.', sayWhat: 'Say what happened.', cantSend: 'Could not send. Try again.',
92
- attachedPrefs: 'This page, the app version and your preferences are attached.',
93
- attached: 'This page and the app version are attached.',
92
+ attachedPrefs: 'This page, the app version, device details and your preferences are attached.',
93
+ attached: 'This page, the app version and device details are attached.',
94
94
  types: {
95
95
  broken: ['Broken', 'Something does not work'],
96
96
  confusing: ['Confusing', 'I could not tell how to do something'],
@@ -114,8 +114,8 @@
114
114
  got: 'Got it', tryIt: 'Try it',
115
115
  attachTrail: 'Attach what happened',
116
116
  trailHint: 'Recent pages, clicks and errors in this app. Never what you typed.',
117
- seeTrail: 'See it',
118
- trail: { page: ['page', 'pages'], click: ['click', 'clicks'], request: ['failed request', 'failed requests'], error: ['error', 'errors'], warn: ['warning', 'warnings'], state: ['connection change', 'connection changes'] },
117
+ seeTrail: 'See it', alsoSent: 'Also sent: ',
118
+ trail: { page: ['page', 'pages'], click: ['click', 'clicks'], request: ['failed request', 'failed requests'], error: ['error', 'errors'], warn: ['warning', 'warnings'], state: ['device event', 'device events'] },
119
119
  nudgeAria: 'Offer to report a problem', nudgeTitle: 'Something not working?', nudgeBody: 'Tell the team what happened. A real person reads it.', nudgeYes: 'Tell the team', nudgeNo: 'Not now',
120
120
  sentTo: 'Sent to this app’s team', powered: 'Powered by Heresay',
121
121
  },
@@ -127,8 +127,8 @@
127
127
  what: 'De quoi s’agit-il ?', whatHappened: 'Que s’est-il passé ?', ph: 'Que s’est-il passé, ou que changeriez-vous ?',
128
128
  send: 'Envoyer', sending: 'Envoi…',
129
129
  pickType: 'Choisissez le type de signalement.', sayWhat: 'Dites ce qui s’est passé.', cantSend: 'Envoi impossible. Réessayez.',
130
- attachedPrefs: 'Cette page, la version de l’app et vos préférences sont jointes.',
131
- attached: 'Cette page et la version de l’app sont jointes.',
130
+ attachedPrefs: 'Cette page, la version de l’app, les détails de l’appareil et vos préférences sont joints.',
131
+ attached: 'Cette page, la version de l’app et les détails de l’appareil sont joints.',
132
132
  types: {
133
133
  broken: ['Cassé', 'Quelque chose ne marche pas'],
134
134
  confusing: ['Déroutant', 'Je ne voyais pas comment faire'],
@@ -152,8 +152,8 @@
152
152
  got: 'Compris', tryIt: 'Essayer',
153
153
  attachTrail: 'Joindre ce qui s’est passé',
154
154
  trailHint: 'Pages, clics et erreurs récents dans cette app. Jamais ce que vous avez saisi.',
155
- seeTrail: 'Voir',
156
- trail: { page: ['page', 'pages'], click: ['clic', 'clics'], request: ['requête échouée', 'requêtes échouées'], error: ['erreur', 'erreurs'], warn: ['avertissement', 'avertissements'], state: ['changement de connexion', 'changements de connexion'] },
155
+ seeTrail: 'Voir', alsoSent: 'Aussi envoyé : ',
156
+ trail: { page: ['page', 'pages'], click: ['clic', 'clics'], request: ['requête échouée', 'requêtes échouées'], error: ['erreur', 'erreurs'], warn: ['avertissement', 'avertissements'], state: ['événement de l’appareil', 'événements de l’appareil'] },
157
157
  nudgeAria: 'Proposition de signaler un problème', nudgeTitle: 'Quelque chose ne marche pas ?', nudgeBody: 'Dites à l’équipe ce qui s’est passé. Une vraie personne le lit.', nudgeYes: 'Signaler', nudgeNo: 'Pas maintenant',
158
158
  sentTo: 'Envoyé à l’équipe de cette app', powered: 'Propulsé par Heresay',
159
159
  },
@@ -165,8 +165,8 @@
165
165
  what: 'இது என்ன வகை?', whatHappened: 'என்ன நடந்தது?', ph: 'என்ன நடந்தது, அல்லது எதை மாற்ற விரும்புகிறீர்கள்?',
166
166
  send: 'அனுப்பு', sending: 'அனுப்புகிறது…',
167
167
  pickType: 'இது எந்த வகைப் புகார் என்பதைத் தேர்ந்தெடுக்கவும்.', sayWhat: 'என்ன நடந்தது என்று சொல்லுங்கள்.', cantSend: 'அனுப்ப முடியவில்லை. மீண்டும் முயலவும்.',
168
- attachedPrefs: 'இந்தப் பக்கம், ஆப் பதிப்பு மற்றும் உங்கள் விருப்பங்கள் இணைக்கப்படும்.',
169
- attached: 'இந்தப் பக்கமும் ஆப் பதிப்பும் இணைக்கப்படும்.',
168
+ attachedPrefs: 'இந்தப் பக்கம், ஆப் பதிப்பு, சாதன விவரங்கள் மற்றும் உங்கள் விருப்பங்கள் இணைக்கப்படும்.',
169
+ attached: 'இந்தப் பக்கம், ஆப் பதிப்பு மற்றும் சாதன விவரங்கள் இணைக்கப்படும்.',
170
170
  types: {
171
171
  broken: ['வேலை செய்யவில்லை', 'ஏதோ ஒன்று சரியாக இயங்கவில்லை'],
172
172
  confusing: ['குழப்பமாக உள்ளது', 'எப்படிச் செய்வது என்று புரியவில்லை'],
@@ -190,8 +190,8 @@
190
190
  got: 'சரி', tryIt: 'முயன்று பாருங்கள்',
191
191
  attachTrail: 'என்ன நடந்தது என்பதையும் இணை',
192
192
  trailHint: 'இந்த ஆப்பில் சமீபத்திய பக்கங்கள், கிளிக்குகள், பிழைகள். நீங்கள் தட்டச்சு செய்தது ஒருபோதும் இல்லை.',
193
- seeTrail: 'பார்',
194
- trail: { page: ['பக்கம்', 'பக்கங்கள்'], click: ['கிளிக்', 'கிளிக்குகள்'], request: ['தோல்வியடைந்த கோரிக்கை', 'தோல்வியடைந்த கோரிக்கைகள்'], error: ['பிழை', 'பிழைகள்'], warn: ['எச்சரிக்கை', 'எச்சரிக்கைகள்'], state: ['இணைப்பு மாற்றம்', 'இணைப்பு மாற்றங்கள்'] },
193
+ seeTrail: 'பார்', alsoSent: 'இவையும் அனுப்பப்படும்: ',
194
+ trail: { page: ['பக்கம்', 'பக்கங்கள்'], click: ['கிளிக்', 'கிளிக்குகள்'], request: ['தோல்வியடைந்த கோரிக்கை', 'தோல்வியடைந்த கோரிக்கைகள்'], error: ['பிழை', 'பிழைகள்'], warn: ['எச்சரிக்கை', 'எச்சரிக்கைகள்'], state: ['சாதன நிகழ்வு', 'சாதன நிகழ்வுகள்'] },
195
195
  nudgeAria: 'சிக்கலைத் தெரிவிக்க ஒரு அழைப்பு', nudgeTitle: 'ஏதாவது வேலை செய்யவில்லையா?', nudgeBody: 'என்ன நடந்தது என்று குழுவிடம் சொல்லுங்கள். ஒருவர் அதைப் படிப்பார்.', nudgeYes: 'குழுவிடம் சொல்', nudgeNo: 'இப்போது வேண்டாம்',
196
196
  sentTo: 'இந்த ஆப்பின் குழுவுக்கு அனுப்பப்படும்', powered: 'Heresay மூலம் இயங்குகிறது',
197
197
  },
@@ -203,8 +203,8 @@
203
203
  what: 'यह क्या है?', whatHappened: 'क्या हुआ?', ph: 'क्या हुआ, या आप क्या बदलना चाहेंगे?',
204
204
  send: 'भेजें', sending: 'भेजा जा रहा है…',
205
205
  pickType: 'चुनें कि यह किस तरह की रिपोर्ट है।', sayWhat: 'बताइए क्या हुआ।', cantSend: 'भेजा नहीं जा सका। फिर से कोशिश करें।',
206
- attachedPrefs: 'यह पेज, ऐप का वर्शन और आपकी प्राथमिकताएँ साथ भेजी जाती हैं।',
207
- attached: 'यह पेज और ऐप का वर्शन साथ भेजे जाते हैं।',
206
+ attachedPrefs: 'यह पेज, ऐप का वर्शन, डिवाइस की जानकारी और आपकी प्राथमिकताएँ साथ भेजी जाती हैं।',
207
+ attached: 'यह पेज, ऐप का वर्शन और डिवाइस की जानकारी साथ भेजी जाती है।',
208
208
  types: {
209
209
  broken: ['टूटा हुआ', 'कुछ काम नहीं कर रहा'],
210
210
  confusing: ['उलझन भरा', 'समझ नहीं आया कि कैसे करें'],
@@ -228,8 +228,8 @@
228
228
  got: 'ठीक है', tryIt: 'आज़माएँ',
229
229
  attachTrail: 'क्या हुआ, वह भी भेजें',
230
230
  trailHint: 'इस ऐप में हाल के पेज, क्लिक और त्रुटियाँ। आपने जो टाइप किया, वह कभी नहीं।',
231
- seeTrail: 'देखें',
232
- trail: { page: ['पेज', 'पेज'], click: ['क्लिक', 'क्लिक'], request: ['विफल अनुरोध', 'विफल अनुरोध'], error: ['त्रुटि', 'त्रुटियाँ'], warn: ['चेतावनी', 'चेतावनियाँ'], state: ['कनेक्शन बदलाव', 'कनेक्शन बदलाव'] },
231
+ seeTrail: 'देखें', alsoSent: 'यह भी भेजा जाता है: ',
232
+ trail: { page: ['पेज', 'पेज'], click: ['क्लिक', 'क्लिक'], request: ['विफल अनुरोध', 'विफल अनुरोध'], error: ['त्रुटि', 'त्रुटियाँ'], warn: ['चेतावनी', 'चेतावनियाँ'], state: ['डिवाइस घटना', 'डिवाइस घटनाएँ'] },
233
233
  nudgeAria: 'समस्या बताने का सुझाव', nudgeTitle: 'कुछ काम नहीं कर रहा?', nudgeBody: 'टीम को बताइए क्या हुआ। इसे कोई इंसान पढ़ता है।', nudgeYes: 'टीम को बताएँ', nudgeNo: 'अभी नहीं',
234
234
  sentTo: 'इस ऐप की टीम को भेजा जाता है', powered: 'Heresay द्वारा संचालित',
235
235
  },
@@ -413,14 +413,44 @@
413
413
  page_title: (document.title || '').trim() || null,
414
414
  page_url: pageUrl(),
415
415
  viewport: Math.round(window.innerWidth) + 'x' + Math.round(window.innerHeight),
416
+ locale: navigator.language || null,
417
+ timezone: (function () { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || null; } catch (e) { return null; } })(),
418
+ theme: media('(prefers-color-scheme: dark)') ? 'dark' : 'light',
419
+ device: deviceKind(),
420
+ network: network(),
421
+ screen: screen && screen.width ? screen.width + 'x' + screen.height + '@' + (Math.round((window.devicePixelRatio || 1) * 100) / 100) + 'x' : null,
422
+ session_s: Math.round(((window.performance && performance.now()) || 0) / 1000),
423
+ settings: [media('(prefers-reduced-motion: reduce)') && 'reduced motion', media('(prefers-contrast: more)') && 'more contrast',
424
+ media('(forced-colors: active)') && 'forced colours', zoom()].filter(Boolean).join(', ') || null,
416
425
  };
417
426
  }
418
427
 
428
+ function media(q) { try { return window.matchMedia(q).matches; } catch (e) { return false; } }
429
+ /** 'phone, touch', 'tablet, touch', 'desktop, mouse': what the layout had to work on. */
430
+ function deviceKind() {
431
+ var ua = navigator.userAgent;
432
+ var kind = /iPad|Tablet|Android(?!.*Mobi)/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1) ? 'tablet'
433
+ : /Mobi|iPhone|Android/.test(ua) ? 'phone' : 'desktop';
434
+ return kind + ', ' + (media('(pointer: coarse)') ? 'touch' : 'mouse');
435
+ }
436
+ /** How the connection looked to the browser: '4g', '3g, data saver', 'offline'. Not every browser says. */
437
+ function network() {
438
+ if (navigator.onLine === false) return 'offline';
439
+ var c = navigator.connection;
440
+ if (!c || !c.effectiveType) return null;
441
+ return c.effectiveType + (c.saveData ? ', data saver' : '');
442
+ }
443
+ /** Page zoom, when the browser shows it: a zoomed page reflows like a narrow one. */
444
+ function zoom() {
445
+ var z = window.visualViewport && window.visualViewport.scale;
446
+ return z && Math.abs(z - 1) > 0.05 ? 'zoomed ' + Math.round(z * 100) + '%' : null;
447
+ }
448
+
419
449
  // ---- the trail -------------------------------------------------------------------------
420
450
 
421
451
  /**
422
452
  * What happened in the app before a report: pages, clicks, requests that failed, errors. Kept
423
- * in memory on this device only (the newest 30, for 5 minutes) and sent only with a report,
453
+ * in memory on this device only (the newest 50, for 5 minutes) and sent only with a report,
424
454
  * only if the reporter leaves "Attach what happened" on. Never what anyone typed, never request
425
455
  * or response bodies or headers, never query strings. Nothing is recorded inside the widget.
426
456
  */
@@ -434,7 +464,7 @@
434
464
  if (on.page || on.request || on.error) on.state = true;
435
465
  return on;
436
466
  })();
437
- var TRAIL_MAX = 30, TRAIL_AGE = 5 * 60000;
467
+ var TRAIL_MAX = 50, TRAIL_AGE = 5 * 60000;
438
468
  // data-nudge, read here because the request watchers below serve both. See "offering help".
439
469
  var NUDGE_SIGNALS = ['clicks', 'errors', 'requests'];
440
470
  var NUDGE = (function () {
@@ -463,17 +493,20 @@
463
493
  }
464
494
 
465
495
  var noting = false;
466
- function note(kind, text, detail) {
467
- if (!TRAIL[kind] || noting) return;
496
+ /** `part` is the data-trail part that allows it, when that isn't the kind's own. */
497
+ function note(kind, text, detail, part) {
498
+ if (!(part ? TRAIL[part] : TRAIL[kind]) || noting) return;
468
499
  noting = true;
469
500
  try {
470
501
  text = scrub(text, 200);
471
502
  if (!text) return;
472
503
  var now = Date.now(), last = trail[trail.length - 1];
473
- if (last && last.kind === kind && last.text === text) { last.n++; last.at = now; return; }
474
- trail.push({ kind: kind, at: now, text: text, detail: detail ? scrub(detail, 600) : null, n: 1 });
504
+ if (last && last.kind === kind && last.text === text) { last.n++; last.at = now; return last; }
505
+ var e = { kind: kind, at: now, text: text, detail: detail ? scrub(detail, 600) : null, n: 1 };
506
+ trail.push(e);
475
507
  if (trail.length > TRAIL_MAX) trail.shift();
476
- } catch (e) { /* never break the app over a record */ } finally { noting = false; }
508
+ return e;
509
+ } catch (x) { /* never break the app over a record */ } finally { noting = false; }
477
510
  }
478
511
  function recentTrail() {
479
512
  var cut = Date.now() - TRAIL_AGE;
@@ -518,12 +551,22 @@
518
551
 
519
552
  // Pages: any router changes the address through history, so watch that.
520
553
  var lastWhere = null;
521
- function onPage() {
554
+ function titled(w) {
555
+ var t = (document.title || '').replace(/\s+/g, ' ').trim();
556
+ return w + (t ? ' "' + (t.length > 60 ? t.slice(0, 59) + '…' : t) + '"' : '');
557
+ }
558
+ function onPage(first) {
522
559
  var w = location.pathname + location.hash;
523
- if (w !== lastWhere) { lastWhere = w; note('page', w); }
560
+ if (w === lastWhere) return;
561
+ lastWhere = w;
562
+ if (first === true) { note('page', titled(w)); return; }
563
+ // Single-page apps set the title just after the address: the entry goes in now, in order,
564
+ // and gets the title a moment later.
565
+ var e = note('page', w);
566
+ if (e) setTimeout(function () { var t = scrub(titled(w), 200); if (t) e.text = t; }, 150);
524
567
  }
525
568
  if (TRAIL.page) {
526
- onPage();
569
+ onPage(true);
527
570
  ['pushState', 'replaceState'].forEach(function (m) {
528
571
  var orig = history[m];
529
572
  if (typeof orig !== 'function') return;
@@ -539,7 +582,8 @@
539
582
 
540
583
  // Clicks: what was clicked, by its label. Never a field's value.
541
584
  var CLICKABLE = 'a,button,input,select,textarea,label,summary,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=switch],[role=option]';
542
- function clicked(t) {
585
+ /** `bare` leaves out where it is. */
586
+ function clicked(t, bare) {
543
587
  var hit = t.closest && t.closest(CLICKABLE), n = hit || t;
544
588
  if (!n.tagName) return null;
545
589
  var tag = n.tagName.toLowerCase(), type = (n.getAttribute('type') || '').toLowerCase();
@@ -555,7 +599,24 @@
555
599
  || n.getAttribute('title') || n.getAttribute('alt') || '';
556
600
  name = name.replace(/\s+/g, ' ').trim();
557
601
  if (name.length > 40) name = name.slice(0, 39) + '…';
558
- return what + (name ? ' "' + name + '"' : '');
602
+ return what + (name ? ' "' + name + '"' : '') + (bare ? '' : where(n));
603
+ }
604
+
605
+ /** The dialog, form, menu or region a control is in, by its name: ' in dialog "Edit profile"'. */
606
+ var AREAS = 'dialog,[role=dialog],[role=alertdialog],[role=menu],[role=tabpanel],form,nav,[role=navigation],[role=search],aside,section[aria-label],section[aria-labelledby],[role=region]';
607
+ function where(n) {
608
+ var a = n.parentElement && n.parentElement.closest(AREAS);
609
+ if (!a || a.closest('[data-heresay-private]')) return '';
610
+ var tag = a.tagName.toLowerCase(), role = a.getAttribute('role');
611
+ var kind = role === 'alertdialog' ? 'dialog' : role === 'navigation' || tag === 'nav' ? 'navigation'
612
+ : role === 'tabpanel' ? 'tab' : role === 'search' ? 'search' : role || (tag === 'aside' ? 'sidebar' : tag === 'section' ? 'section' : tag);
613
+ var by = a.getAttribute('aria-labelledby');
614
+ var label = a.getAttribute('aria-label')
615
+ || (by && by.split(/\s+/).map(function (id) { var x = document.getElementById(id); return x ? x.textContent : ''; }).join(' '))
616
+ || ((a.querySelector('h1,h2,h3,legend') || {}).textContent) || '';
617
+ label = label.replace(/\s+/g, ' ').trim();
618
+ if (label.length > 30) label = label.slice(0, 29) + '…';
619
+ return ' in ' + kind + (label ? ' "' + label + '"' : '');
559
620
  }
560
621
  if (TRAIL.click) {
561
622
  document.addEventListener('click', function (e) {
@@ -564,7 +625,34 @@
564
625
  }, true);
565
626
  }
566
627
 
567
- // Requests: only the ones that failed, by method, path and status.
628
+ // Forms: sent, and the fields the browser refused, by their label and why. Never their value.
629
+ var WHY = { valueMissing: 'is required', typeMismatch: 'is not in the right format', patternMismatch: 'does not match the format asked for',
630
+ tooShort: 'is too short', tooLong: 'is too long', rangeUnderflow: 'is too low', rangeOverflow: 'is too high',
631
+ stepMismatch: 'is not an allowed value', badInput: 'could not be read' };
632
+ if (TRAIL.click) {
633
+ document.addEventListener('submit', function (e) {
634
+ var f = e.target;
635
+ if (!f || !f.tagName || host.contains(f)) return;
636
+ var name = f.closest('[data-heresay-private]') ? '' : (f.getAttribute('aria-label') || f.getAttribute('name') || ((f.querySelector('h1,h2,h3,legend') || {}).textContent) || '');
637
+ name = name.replace(/\s+/g, ' ').trim().slice(0, 40);
638
+ note('click', 'form' + (name ? ' "' + name + '"' : '') + ' sent');
639
+ }, true);
640
+ document.addEventListener('invalid', function (e) {
641
+ var t = e.target;
642
+ if (!t || !t.validity || host.contains(t)) return;
643
+ var why = Object.keys(WHY).filter(function (k) { return t.validity[k]; })[0];
644
+ note('warn', clicked(t, true) + ' ' + (WHY[why] || 'was refused'), null, 'click');
645
+ }, true);
646
+ }
647
+
648
+ // Requests: the ones that failed, and the ones so slow someone would notice, by method, path,
649
+ // status and how long they took.
650
+ /** ' in 2.4 s', past a second; quicker than that, the time says nothing. */
651
+ function took(t0) { var ms = Date.now() - t0; return ms >= 1000 ? ' in ' + (Math.round(ms / 100) / 10) + ' s' : ''; }
652
+ /** A request that worked but took 3 s or more: a warning, since nothing failed. */
653
+ function slow(method, url, status, t0) {
654
+ if (Date.now() - t0 >= 3000) note('warn', 'Slow request: ' + method + ' ' + shortUrl(url) + ' → ' + status + took(t0), null, 'request');
655
+ }
568
656
  if ((TRAIL.request || NUDGE.requests) && window.fetch) {
569
657
  var ofetch = window.fetch;
570
658
  window.fetch = function (input, init) {
@@ -573,11 +661,13 @@
573
661
  var url = typeof input === 'string' ? input : input && (input.url || String(input));
574
662
  if (url && !ours(url)) {
575
663
  var method = String(init && init.method || input && input.method || 'GET').toUpperCase();
664
+ var t0 = Date.now();
576
665
  p.then(function (res) {
577
- if (!res.ok && res.type !== 'opaque') { note('request', method + ' ' + shortUrl(url) + ' → ' + res.status); requestFailed(res.status); }
666
+ if (!res.ok && res.type !== 'opaque') { note('request', method + ' ' + shortUrl(url) + ' → ' + res.status + took(t0)); requestFailed(res.status); }
667
+ else slow(method, url, res.status, t0);
578
668
  }, function (err) {
579
669
  if (err && err.name === 'AbortError') return;
580
- note('request', method + ' ' + shortUrl(url) + ' → failed (' + (navigator.onLine === false ? 'offline' : 'network error') + ')');
670
+ note('request', method + ' ' + shortUrl(url) + ' → failed (' + (navigator.onLine === false ? 'offline' : 'network error') + ')' + took(t0));
581
671
  requestFailed(0);
582
672
  });
583
673
  }
@@ -595,11 +685,12 @@
595
685
  var x = this, r = x.__heresay;
596
686
  try {
597
687
  if (r && !ours(r.u)) {
598
- var aborted = false;
688
+ var aborted = false, t0 = Date.now();
599
689
  x.addEventListener('abort', function () { aborted = true; });
600
690
  x.addEventListener('loadend', function () {
601
- if (x.status >= 400) { note('request', r.m + ' ' + shortUrl(r.u) + ' → ' + x.status); requestFailed(x.status); }
602
- else if (x.status === 0 && !aborted) { note('request', r.m + ' ' + shortUrl(r.u) + ' → failed (network error)'); requestFailed(0); }
691
+ if (x.status >= 400) { note('request', r.m + ' ' + shortUrl(r.u) + ' → ' + x.status + took(t0)); requestFailed(x.status); }
692
+ else if (x.status === 0 && !aborted) { note('request', r.m + ' ' + shortUrl(r.u) + ' → failed (network error)' + took(t0)); requestFailed(0); }
693
+ else if (x.status) slow(r.m, r.u, x.status, t0);
603
694
  });
604
695
  }
605
696
  } catch (e) { /* ignore */ }
@@ -639,9 +730,49 @@
639
730
  };
640
731
  });
641
732
  }
733
+ if (TRAIL.error) {
734
+ // Something the page's own security policy blocked: often why a script or an embed is missing.
735
+ document.addEventListener('securitypolicyviolation', function (e) {
736
+ note('error', 'Blocked by the Content Security Policy (' + (e.effectiveDirective || e.violatedDirective) + '): ' +
737
+ (/^https?:/.test(e.blockedURI) ? shortUrl(e.blockedURI) : e.blockedURI || 'inline'));
738
+ });
739
+ // The page stopped answering: a long task of a second or more.
740
+ try {
741
+ new PerformanceObserver(function (l) {
742
+ l.getEntries().forEach(function (t) {
743
+ if (t.duration >= 1000) note('warn', 'The page froze for ' + (Math.round(t.duration / 100) / 10) + ' s');
744
+ });
745
+ }).observe({ type: 'longtask', buffered: true });
746
+ } catch (e) { /* not in this browser */ }
747
+ // What the app told the person: alerts, as screen readers announce them. Checked at most every
748
+ // 300 ms, only when the page changes.
749
+ var shown = typeof WeakMap === 'function' ? new WeakMap() : null, alertTimer = null;
750
+ var checkAlerts = function () {
751
+ alertTimer = null;
752
+ document.querySelectorAll('[role=alert],[role=alertdialog],[aria-live=assertive]').forEach(function (a) {
753
+ if (host.contains(a) || a.closest('[data-heresay-private]')) return;
754
+ var t = (a.getAttribute('aria-label') || a.textContent || '').replace(/\s+/g, ' ').trim();
755
+ if (shown.get(a) === t) return;
756
+ shown.set(a, t);
757
+ if (t) note('warn', 'The app showed: "' + (t.length > 120 ? t.slice(0, 119) + '…' : t) + '"');
758
+ });
759
+ };
760
+ if (shown && window.MutationObserver) {
761
+ new MutationObserver(function () { if (!alertTimer) alertTimer = setTimeout(checkAlerts, 300); })
762
+ .observe(document.documentElement, { childList: true, subtree: true, characterData: true });
763
+ }
764
+ }
642
765
  if (TRAIL.state) {
643
766
  window.addEventListener('offline', function () { note('state', 'Went offline'); });
644
767
  window.addEventListener('online', function () { note('state', 'Back online'); });
768
+ // Leaving the tab and coming back: a session can expire, a socket drop, while they are away.
769
+ var hiddenAt = 0;
770
+ document.addEventListener('visibilitychange', function () {
771
+ if (document.visibilityState === 'hidden') { hiddenAt = Date.now(); return; }
772
+ var s = hiddenAt ? Math.round((Date.now() - hiddenAt) / 1000) : 0;
773
+ hiddenAt = 0;
774
+ if (s >= 5) note('state', 'Came back to the tab after ' + (s >= 60 ? Math.floor(s / 60) + ':' + ('0' + s % 60).slice(-2) + ' min' : s + ' s'));
775
+ });
645
776
  }
646
777
 
647
778
  // ---- offering help ---------------------------------------------------------------------
@@ -1161,7 +1292,10 @@
1161
1292
  }));
1162
1293
  box.appendChild(el('label', { class: 'switch' }, [on, el('span', { text: S.attachTrail })]));
1163
1294
  box.appendChild(el('div', { class: 'chips' }, chips));
1164
- box.appendChild(el('details', {}, [el('summary', { text: S.seeTrail }), el('p', { class: 'small', text: S.trailHint }), list]));
1295
+ var c = context();
1296
+ var device = [c.device, c.screen, c.theme, c.locale, c.timezone, c.network, c.settings].filter(Boolean).join(' · ');
1297
+ box.appendChild(el('details', {}, [el('summary', { text: S.seeTrail }), el('p', { class: 'small', text: S.trailHint }), list,
1298
+ device ? el('p', { class: 'small', text: S.alsoSent + device }) : null]));
1165
1299
  return box;
1166
1300
  }
1167
1301