makethisbetter 1.5.4 → 1.7.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.
Files changed (107) hide show
  1. package/README.md +10 -10
  2. package/dist/annotate/draw-note-bar.d.ts +29 -0
  3. package/dist/annotate/draw-note-bar.d.ts.map +1 -0
  4. package/dist/annotate/draw-note-bar.test.d.ts +2 -0
  5. package/dist/annotate/draw-note-bar.test.d.ts.map +1 -0
  6. package/dist/annotate/draw.d.ts +15 -9
  7. package/dist/annotate/draw.d.ts.map +1 -1
  8. package/dist/annotate/highlighter.d.ts +2 -0
  9. package/dist/annotate/highlighter.d.ts.map +1 -1
  10. package/dist/annotate/session.d.ts +16 -2
  11. package/dist/annotate/session.d.ts.map +1 -1
  12. package/dist/api/client.d.ts +8 -5
  13. package/dist/api/client.d.ts.map +1 -1
  14. package/dist/context/breadcrumbs.d.ts +26 -0
  15. package/dist/context/breadcrumbs.d.ts.map +1 -0
  16. package/dist/context/breadcrumbs.test.d.ts +2 -0
  17. package/dist/context/breadcrumbs.test.d.ts.map +1 -0
  18. package/dist/context/dom-utils.d.ts +3 -0
  19. package/dist/context/dom-utils.d.ts.map +1 -0
  20. package/dist/context/frustration.d.ts +0 -1
  21. package/dist/context/frustration.d.ts.map +1 -1
  22. package/dist/i18n/de.d.ts +24 -0
  23. package/dist/i18n/de.d.ts.map +1 -1
  24. package/dist/i18n/en.d.ts +24 -0
  25. package/dist/i18n/en.d.ts.map +1 -1
  26. package/dist/i18n/es.d.ts +24 -0
  27. package/dist/i18n/es.d.ts.map +1 -1
  28. package/dist/i18n/fr.d.ts +24 -0
  29. package/dist/i18n/fr.d.ts.map +1 -1
  30. package/dist/i18n/ja.d.ts +24 -0
  31. package/dist/i18n/ja.d.ts.map +1 -1
  32. package/dist/i18n/ko.d.ts +24 -0
  33. package/dist/i18n/ko.d.ts.map +1 -1
  34. package/dist/i18n/zh-CN.d.ts +24 -0
  35. package/dist/i18n/zh-CN.d.ts.map +1 -1
  36. package/dist/makethisbetter.cjs +50 -25
  37. package/dist/makethisbetter.cjs.map +1 -1
  38. package/dist/makethisbetter.esm.js +1132 -590
  39. package/dist/makethisbetter.esm.js.map +1 -1
  40. package/dist/makethisbetter.js +49 -24
  41. package/dist/makethisbetter.js.map +1 -1
  42. package/dist/popup/clarify.d.ts +28 -7
  43. package/dist/popup/clarify.d.ts.map +1 -1
  44. package/dist/popup/comment.d.ts +1 -0
  45. package/dist/popup/comment.d.ts.map +1 -1
  46. package/dist/record/replay.d.ts +7 -0
  47. package/dist/record/replay.d.ts.map +1 -0
  48. package/dist/screenshot/capture.d.ts +1 -0
  49. package/dist/screenshot/capture.d.ts.map +1 -1
  50. package/dist/styles.d.ts +1 -0
  51. package/dist/styles.d.ts.map +1 -1
  52. package/dist/types.d.ts +13 -0
  53. package/dist/types.d.ts.map +1 -1
  54. package/dist/widget/controller.d.ts +18 -0
  55. package/dist/widget/controller.d.ts.map +1 -1
  56. package/dist/widget/dim-overlay.d.ts +8 -0
  57. package/dist/widget/dim-overlay.d.ts.map +1 -0
  58. package/dist/widget/dim-overlay.test.d.ts +2 -0
  59. package/dist/widget/dim-overlay.test.d.ts.map +1 -0
  60. package/dist/widget/payload.d.ts +2 -2
  61. package/dist/widget/payload.d.ts.map +1 -1
  62. package/dist/widget/tab.d.ts +3 -0
  63. package/dist/widget/tab.d.ts.map +1 -1
  64. package/package.json +1 -1
  65. package/src/annotate/draw-note-bar.test.ts +90 -0
  66. package/src/annotate/draw-note-bar.ts +105 -0
  67. package/src/annotate/draw.test.ts +74 -84
  68. package/src/annotate/draw.ts +108 -65
  69. package/src/annotate/highlighter.test.ts +24 -1
  70. package/src/annotate/highlighter.ts +16 -2
  71. package/src/annotate/session.test.ts +112 -96
  72. package/src/annotate/session.ts +54 -10
  73. package/src/api/client.test.ts +69 -30
  74. package/src/api/client.ts +68 -20
  75. package/src/context/breadcrumbs.test.ts +154 -0
  76. package/src/context/breadcrumbs.ts +157 -0
  77. package/src/context/dom-utils.ts +16 -0
  78. package/src/context/frustration.ts +4 -8
  79. package/src/i18n/de.ts +34 -11
  80. package/src/i18n/en.ts +33 -10
  81. package/src/i18n/es.ts +34 -11
  82. package/src/i18n/fr.ts +33 -10
  83. package/src/i18n/index.test.ts +12 -0
  84. package/src/i18n/ja.ts +32 -9
  85. package/src/i18n/ko.ts +34 -11
  86. package/src/i18n/zh-CN.ts +35 -12
  87. package/src/popup/clarify.test.ts +132 -40
  88. package/src/popup/clarify.ts +154 -42
  89. package/src/popup/comment.test.ts +57 -0
  90. package/src/popup/comment.ts +15 -9
  91. package/src/record/replay.ts +115 -0
  92. package/src/record/session.test.ts +8 -1
  93. package/src/record/session.ts +1 -1
  94. package/src/screenshot/capture.test.ts +51 -23
  95. package/src/screenshot/capture.ts +101 -55
  96. package/src/styles/widget.css +347 -1
  97. package/src/styles.ts +2 -0
  98. package/src/types.ts +15 -0
  99. package/src/widget/controller.test.ts +476 -65
  100. package/src/widget/controller.ts +222 -40
  101. package/src/widget/dim-overlay.test.ts +27 -0
  102. package/src/widget/dim-overlay.ts +20 -0
  103. package/src/widget/payload.test.ts +26 -1
  104. package/src/widget/payload.ts +3 -1
  105. package/src/widget/pet.test.ts +2 -2
  106. package/src/widget/tab.test.ts +15 -0
  107. package/src/widget/tab.ts +11 -3
@@ -20,33 +20,33 @@ describe('ApiClient', () => {
20
20
  })
21
21
 
22
22
  it('sends POST to correct URL with project key header', async () => {
23
- const jsonBody = JSON.stringify({ id: 'fb_1', status: 'open' })
23
+ const jsonBody = JSON.stringify({ submission_session: { id: 'submission_1', token: 'secret' } })
24
24
  const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
25
25
  new Response(jsonBody, { status: 201 }),
26
26
  )
27
27
 
28
- const client = new ApiClient('proj_test123', 'https://api.example.com')
29
- await client.submitFeedback(mockPayload, null)
28
+ const client = new ApiClient('acme123', 'https://api.example.com')
29
+ await client.createSubmissionSession(mockPayload, null)
30
30
 
31
31
  expect(fetchSpy).toHaveBeenCalledWith(
32
- 'https://api.example.com/widget/feedbacks',
32
+ 'https://api.example.com/widget/feedback_submission_sessions',
33
33
  expect.objectContaining({
34
34
  method: 'POST',
35
- headers: expect.objectContaining({ 'X-Project-Key': 'proj_test123' }),
35
+ headers: expect.objectContaining({ 'X-Project-Key': 'acme123' }),
36
36
  }),
37
37
  )
38
38
  })
39
39
 
40
40
  it('includes description in FormData', async () => {
41
41
  let capturedBody: FormData | null = null
42
- const jsonBody = JSON.stringify({ id: 'fb_1', status: 'open' })
42
+ const jsonBody = JSON.stringify({ submission_session: { id: 'submission_1', token: 'secret' } })
43
43
  vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url: RequestInfo | URL, init?: RequestInit) => {
44
44
  capturedBody = init?.body instanceof FormData ? init.body : null
45
45
  return new Response(jsonBody, { status: 201 })
46
46
  })
47
47
 
48
48
  const client = new ApiClient('key', 'https://api.example.com')
49
- await client.submitFeedback(mockPayload, null)
49
+ await client.createSubmissionSession(mockPayload, null)
50
50
 
51
51
  expect(capturedBody).not.toBeNull()
52
52
  const formData = capturedBody as unknown as FormData
@@ -55,7 +55,7 @@ describe('ApiClient', () => {
55
55
 
56
56
  it('uploads screenshot when present', async () => {
57
57
  let capturedBody: FormData | null = null
58
- const jsonBody = JSON.stringify({ id: 'fb_1', status: 'open' })
58
+ const jsonBody = JSON.stringify({ submission_session: { id: 'submission_1', token: 'secret' } })
59
59
  vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url: RequestInfo | URL, init?: RequestInit) => {
60
60
  capturedBody = init?.body instanceof FormData ? init.body : null
61
61
  return new Response(jsonBody, { status: 201 })
@@ -63,20 +63,20 @@ describe('ApiClient', () => {
63
63
 
64
64
  const screenshot = new Blob(['png'], { type: 'image/png' })
65
65
  const client = new ApiClient('key', 'https://api.example.com')
66
- await client.submitFeedback(mockPayload, screenshot)
66
+ await client.createSubmissionSession(mockPayload, screenshot)
67
67
 
68
68
  const formData = capturedBody as unknown as FormData
69
69
  expect(formData.get('feedback[screenshot]')).toBeInstanceOf(File)
70
70
  })
71
71
 
72
72
  it('includes X-User-Token header when userToken is set', async () => {
73
- const jsonBody = JSON.stringify({ id: 'fb_1', status: 'open' })
73
+ const jsonBody = JSON.stringify({ submission_session: { id: 'submission_1', token: 'secret' } })
74
74
  const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
75
75
  new Response(jsonBody, { status: 201 }),
76
76
  )
77
77
 
78
78
  const client = new ApiClient('key', 'https://api.example.com', 1000, 'jwt_static_token')
79
- await client.submitFeedback(mockPayload, null)
79
+ await client.createSubmissionSession(mockPayload, null)
80
80
 
81
81
  expect(fetchSpy).toHaveBeenCalledWith(
82
82
  expect.any(String),
@@ -90,14 +90,14 @@ describe('ApiClient', () => {
90
90
  })
91
91
 
92
92
  it('calls userTokenFn to get fresh token before each request', async () => {
93
- const jsonBody = JSON.stringify({ id: 'fb_1', status: 'open' })
93
+ const jsonBody = JSON.stringify({ submission_session: { id: 'submission_1', token: 'secret' } })
94
94
  const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
95
95
  new Response(jsonBody, { status: 201 }),
96
96
  )
97
97
 
98
98
  const tokenFn = vi.fn(async () => 'jwt_dynamic_token')
99
99
  const client = new ApiClient('key', 'https://api.example.com', 1000, undefined, tokenFn)
100
- await client.submitFeedback(mockPayload, null)
100
+ await client.createSubmissionSession(mockPayload, null)
101
101
 
102
102
  expect(tokenFn).toHaveBeenCalledOnce()
103
103
  expect(fetchSpy).toHaveBeenCalledWith(
@@ -111,14 +111,14 @@ describe('ApiClient', () => {
111
111
  })
112
112
 
113
113
  it('prefers userTokenFn over static userToken', async () => {
114
- const jsonBody = JSON.stringify({ id: 'fb_1', status: 'open' })
114
+ const jsonBody = JSON.stringify({ submission_session: { id: 'submission_1', token: 'secret' } })
115
115
  const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
116
116
  new Response(jsonBody, { status: 201 }),
117
117
  )
118
118
 
119
119
  const tokenFn = vi.fn(async () => 'from_fn')
120
120
  const client = new ApiClient('key', 'https://api.example.com', 1000, 'from_static', tokenFn)
121
- await client.submitFeedback(mockPayload, null)
121
+ await client.createSubmissionSession(mockPayload, null)
122
122
 
123
123
  expect(fetchSpy).toHaveBeenCalledWith(
124
124
  expect.any(String),
@@ -131,19 +131,20 @@ describe('ApiClient', () => {
131
131
  })
132
132
 
133
133
  it('includes X-User-Token in startClarification', async () => {
134
- const jsonBody = JSON.stringify({ status: 'pending', messages: [], done: false })
134
+ const jsonBody = JSON.stringify({ clarification: { status: 'pending', messages: [], done: false } })
135
135
  const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
136
136
  new Response(jsonBody, { status: 200 }),
137
137
  )
138
138
 
139
139
  const client = new ApiClient('key', 'https://api.example.com', 1000, 'jwt_token')
140
- await client.startClarification('fb_1', 'hello')
140
+ await client.startClarification('submission_1', 'secret', 'hello')
141
141
 
142
142
  expect(fetchSpy).toHaveBeenCalledWith(
143
143
  expect.any(String),
144
144
  expect.objectContaining({
145
145
  headers: expect.objectContaining({
146
146
  'X-Project-Key': 'key',
147
+ 'X-Submission-Token': 'secret',
147
148
  'X-User-Token': 'jwt_token',
148
149
  'Content-Type': 'application/json',
149
150
  }),
@@ -152,14 +153,14 @@ describe('ApiClient', () => {
152
153
  })
153
154
 
154
155
  it('includes X-User-Token in getClarification', async () => {
155
- const jsonBody = JSON.stringify({ status: 'done', messages: [], done: true })
156
+ const jsonBody = JSON.stringify({ clarification: { status: 'done', messages: [], done: true } })
156
157
  const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
157
158
  new Response(jsonBody, { status: 200 }),
158
159
  )
159
160
 
160
161
  const tokenFn = vi.fn(async () => 'jwt_dynamic')
161
162
  const client = new ApiClient('key', 'https://api.example.com', 1000, undefined, tokenFn)
162
- await client.getClarification('fb_1')
163
+ await client.getClarification('submission_1', 'secret')
163
164
 
164
165
  expect(tokenFn).toHaveBeenCalledOnce()
165
166
  expect(fetchSpy).toHaveBeenCalledWith(
@@ -167,6 +168,7 @@ describe('ApiClient', () => {
167
168
  expect.objectContaining({
168
169
  headers: expect.objectContaining({
169
170
  'X-Project-Key': 'key',
171
+ 'X-Submission-Token': 'secret',
170
172
  'X-User-Token': 'jwt_dynamic',
171
173
  }),
172
174
  }),
@@ -177,25 +179,29 @@ describe('ApiClient', () => {
177
179
  vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('Network error'))
178
180
 
179
181
  const client = new ApiClient('key', 'https://api.example.com', 0)
180
- await expect(client.submitFeedback(mockPayload, null)).rejects.toThrow()
182
+ await expect(client.createSubmissionSession(mockPayload, null)).rejects.toThrow()
181
183
  })
182
184
 
183
- it('sends an idempotency key and reuses it across retries', async () => {
185
+ it('reuses the idempotency key and submission token across retries', async () => {
184
186
  const calls: RequestInit[] = []
185
187
  const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
186
188
  calls.push(init!)
187
189
  if (calls.length === 1) return new Response('oops', { status: 500 })
188
- return new Response(JSON.stringify({ id: 'fb_1' }), { status: 201 })
190
+ return new Response(JSON.stringify({ submission_session: { id: 'submission_1', token: 'secret' } }), { status: 201 })
189
191
  })
190
192
 
191
- const client = new ApiClient('proj_test123', 'https://api.example.com', 0)
192
- await client.submitFeedback(mockPayload, null)
193
+ const client = new ApiClient('acme123', 'https://api.example.com', 0)
194
+ await client.createSubmissionSession(mockPayload, null)
193
195
 
194
196
  expect(fetchSpy).toHaveBeenCalledTimes(2)
195
197
  const key1 = (calls[0].headers as Record<string, string>)['X-Idempotency-Key']
196
198
  const key2 = (calls[1].headers as Record<string, string>)['X-Idempotency-Key']
199
+ const token1 = (calls[0].headers as Record<string, string>)['X-Submission-Token']
200
+ const token2 = (calls[1].headers as Record<string, string>)['X-Submission-Token']
197
201
  expect(key1).toBeTruthy()
198
202
  expect(key2).toBe(key1)
203
+ expect(token1.length).toBeGreaterThanOrEqual(32)
204
+ expect(token2).toBe(token1)
199
205
  })
200
206
 
201
207
  it('streams clarify deltas and resolves the done result', async () => {
@@ -210,7 +216,7 @@ describe('ApiClient', () => {
210
216
 
211
217
  const client = new ApiClient('key', 'https://api.example.com')
212
218
  const deltas: string[] = []
213
- const result = await client.streamClarification('fb_1', 'hello', (t) => deltas.push(t))
219
+ const result = await client.streamClarification('submission_1', 'secret', (t) => deltas.push(t))
214
220
 
215
221
  expect(deltas).toEqual(['Hi ', 'there'])
216
222
  expect(result.done).toBe(true)
@@ -226,21 +232,54 @@ describe('ApiClient', () => {
226
232
  )
227
233
 
228
234
  const client = new ApiClient('key', 'https://api.example.com')
229
- await expect(client.streamClarification('fb_1', undefined, () => {})).rejects.toThrow()
235
+ await expect(client.streamClarification('submission_1', 'secret', () => {})).rejects.toThrow()
230
236
  })
231
237
 
232
238
  it('uses a fresh idempotency key for each separate submission', async () => {
233
239
  const keys: string[] = []
234
240
  vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
235
241
  keys.push((init!.headers as Record<string, string>)['X-Idempotency-Key'])
236
- return new Response(JSON.stringify({ id: 'fb_1' }), { status: 201 })
242
+ return new Response(JSON.stringify({ submission_session: { id: 'submission_1', token: 'secret' } }), { status: 201 })
237
243
  })
238
244
 
239
- const client = new ApiClient('proj_test123', 'https://api.example.com')
240
- await client.submitFeedback(mockPayload, null)
241
- await client.submitFeedback(mockPayload, null)
245
+ const client = new ApiClient('acme123', 'https://api.example.com')
246
+ await client.createSubmissionSession(mockPayload, null)
247
+ await client.createSubmissionSession(mockPayload, null)
242
248
 
243
249
  expect(keys[0]).toBeTruthy()
244
250
  expect(keys[0]).not.toBe(keys[1])
245
251
  })
252
+
253
+ it('finalizes a submission session only with its token', async () => {
254
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
255
+ new Response(JSON.stringify({ feedback: { id: 'FB-1', status: 'received', project_id: 'acme' } }), { status: 201 }),
256
+ )
257
+
258
+ const client = new ApiClient('key', 'https://api.example.com')
259
+ const feedback = await client.finalizeSubmissionSession('submission_1', 'secret')
260
+
261
+ expect(feedback.id).toBe('FB-1')
262
+ expect(fetchSpy).toHaveBeenCalledWith(
263
+ 'https://api.example.com/widget/feedback_submission_sessions/submission_1/feedback',
264
+ expect.objectContaining({
265
+ method: 'POST',
266
+ headers: expect.objectContaining({ 'X-Submission-Token': 'secret' }),
267
+ }),
268
+ )
269
+ })
270
+
271
+ it('abandons a submission session on Exit', async () => {
272
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 204 }))
273
+
274
+ const client = new ApiClient('key', 'https://api.example.com')
275
+ await client.abandonSubmissionSession('submission_1', 'secret')
276
+
277
+ expect(fetchSpy).toHaveBeenCalledWith(
278
+ 'https://api.example.com/widget/feedback_submission_sessions/submission_1',
279
+ expect.objectContaining({
280
+ method: 'DELETE',
281
+ headers: expect.objectContaining({ 'X-Submission-Token': 'secret' }),
282
+ }),
283
+ )
284
+ })
246
285
  })
package/src/api/client.ts CHANGED
@@ -1,4 +1,10 @@
1
- import type { FeedbackPayload, FeedbackResponse, ClarifyResponse, ClarifyMessage } from '../types'
1
+ import type {
2
+ FeedbackPayload,
3
+ FeedbackResponse,
4
+ SubmissionSessionResponse,
5
+ ClarifyResponse,
6
+ ClarifyMessage,
7
+ } from '../types'
2
8
 
3
9
  export interface ClarifyStreamResult {
4
10
  messages: ClarifyMessage[]
@@ -35,7 +41,14 @@ export class ApiClient {
35
41
  return headers
36
42
  }
37
43
 
38
- async submitFeedback(payload: FeedbackPayload, screenshot: Blob | null): Promise<FeedbackResponse> {
44
+ private async submissionHeaders(token: string, contentType?: string): Promise<Record<string, string>> {
45
+ const headers = await this.authHeaders(contentType)
46
+ headers['X-Submission-Token'] = token
47
+ return headers
48
+ }
49
+
50
+ async createSubmissionSession(payload: FeedbackPayload, screenshot: Blob | null): Promise<SubmissionSessionResponse> {
51
+ const submissionToken = generateSubmissionToken()
39
52
  const form = new FormData()
40
53
  form.append('feedback[description]', payload.description)
41
54
  form.append('feedback[page_url]', payload.page_url)
@@ -56,10 +69,14 @@ export class ApiClient {
56
69
  if (payload.user_email) form.append('feedback[user_email]', payload.user_email)
57
70
  if (payload.user_name) form.append('feedback[user_name]', payload.user_name)
58
71
 
72
+ if (payload.breadcrumbs && payload.breadcrumbs.length > 0) {
73
+ form.append('feedback[breadcrumbs]', JSON.stringify(payload.breadcrumbs))
74
+ }
75
+
59
76
  if (payload.recording_events && payload.recording_events.length > 0) {
60
77
  const json = JSON.stringify(payload.recording_events)
61
78
  const blob = new Blob([json], { type: 'application/json' })
62
- form.append('feedback[recording]', blob, 'recording.json')
79
+ form.append('feedback[recording]', blob, 'interaction-replay.json')
63
80
  form.append('feedback[recording_duration]', String(payload.recording_duration ?? 0))
64
81
  }
65
82
 
@@ -69,16 +86,20 @@ export class ApiClient {
69
86
  }
70
87
 
71
88
  const headers = await this.authHeaders()
89
+ headers['X-Submission-Token'] = submissionToken
72
90
  // One key per submission, reused across retries: if the first POST
73
91
  // reached the server but the response was lost, the retry must not
74
92
  // create a second feedback.
75
93
  headers['X-Idempotency-Key'] = generateIdempotencyKey()
76
- const res = await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks`, {
94
+ const res = await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions`, {
77
95
  method: 'POST',
78
96
  headers,
79
97
  body: form,
80
98
  })
81
- return res.json() as Promise<FeedbackResponse>
99
+ const body = await res.json() as {
100
+ submission_session: Omit<SubmissionSessionResponse, 'token'> & { token?: string }
101
+ }
102
+ return { ...body.submission_session, token: submissionToken }
82
103
  }
83
104
 
84
105
  async createIdentityToken(reporterExternalId: string): Promise<{ identity_token: string; board_url: string } | null> {
@@ -110,44 +131,44 @@ export class ApiClient {
110
131
  }
111
132
  }
112
133
 
113
- async startClarification(feedbackId: string, message?: string): Promise<ClarifyResponse> {
134
+ async startClarification(submissionSessionId: string, token: string, message?: string): Promise<ClarifyResponse> {
114
135
  const body: Record<string, string> = {}
115
136
  if (message) body.message = message
116
- const headers = await this.authHeaders('application/json')
117
- const res = await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${feedbackId}/clarify`, {
137
+ const headers = await this.submissionHeaders(token, 'application/json')
138
+ const res = await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${submissionSessionId}/clarification`, {
118
139
  method: 'POST',
119
140
  headers,
120
141
  body: JSON.stringify(body),
121
142
  })
122
- return res.json() as Promise<ClarifyResponse>
143
+ const response = await res.json() as { clarification: ClarifyResponse }
144
+ return response.clarification
123
145
  }
124
146
 
125
- async getClarification(feedbackId: string): Promise<ClarifyResponse> {
126
- const headers = await this.authHeaders()
127
- const res = await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${feedbackId}/clarify`, {
147
+ async getClarification(submissionSessionId: string, token: string): Promise<ClarifyResponse> {
148
+ const headers = await this.submissionHeaders(token)
149
+ const res = await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${submissionSessionId}/clarification`, {
128
150
  method: 'GET',
129
151
  headers,
130
152
  })
131
- return res.json() as Promise<ClarifyResponse>
153
+ const response = await res.json() as { clarification: ClarifyResponse }
154
+ return response.clarification
132
155
  }
133
156
 
134
157
  // Streams a clarification turn over SSE. Calls onDelta for each token and
135
158
  // resolves with the committed result. Throws if the server doesn't stream
136
159
  // (e.g. old backend returns JSON) so the caller can fall back to polling.
137
160
  async streamClarification(
138
- feedbackId: string,
139
- message: string | undefined,
161
+ submissionSessionId: string,
162
+ token: string,
140
163
  onDelta: (text: string) => void,
141
164
  ): Promise<ClarifyStreamResult> {
142
- const body: Record<string, string> = {}
143
- if (message) body.message = message
144
- const headers = await this.authHeaders('application/json')
165
+ const headers = await this.submissionHeaders(token, 'application/json')
145
166
  headers['Accept'] = 'text/event-stream'
146
167
 
147
- const res = await fetch(`${this.apiUrl}/widget/feedbacks/${feedbackId}/clarify`, {
168
+ const res = await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${submissionSessionId}/clarification`, {
148
169
  method: 'POST',
149
170
  headers,
150
- body: JSON.stringify(body),
171
+ body: JSON.stringify({}),
151
172
  })
152
173
 
153
174
  const contentType = res.headers.get('Content-Type') ?? ''
@@ -158,6 +179,24 @@ export class ApiClient {
158
179
  return consumeSse(res.body, onDelta)
159
180
  }
160
181
 
182
+ async finalizeSubmissionSession(submissionSessionId: string, token: string): Promise<FeedbackResponse> {
183
+ const headers = await this.submissionHeaders(token)
184
+ const res = await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${submissionSessionId}/feedback`, {
185
+ method: 'POST',
186
+ headers,
187
+ })
188
+ const response = await res.json() as { feedback: FeedbackResponse }
189
+ return response.feedback
190
+ }
191
+
192
+ async abandonSubmissionSession(submissionSessionId: string, token: string): Promise<void> {
193
+ const headers = await this.submissionHeaders(token)
194
+ await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${submissionSessionId}`, {
195
+ method: 'DELETE',
196
+ headers,
197
+ })
198
+ }
199
+
161
200
  private async fetchWithRetry(url: string, init: RequestInit, retries = 1): Promise<Response> {
162
201
  let res: Response
163
202
  try {
@@ -230,3 +269,12 @@ function generateIdempotencyKey(): string {
230
269
  }
231
270
  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`
232
271
  }
272
+
273
+ function generateSubmissionToken(): string {
274
+ if (typeof crypto === 'undefined' || typeof crypto.getRandomValues !== 'function') {
275
+ throw new Error('Secure random generation is unavailable')
276
+ }
277
+
278
+ const bytes = crypto.getRandomValues(new Uint8Array(32))
279
+ return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
280
+ }
@@ -0,0 +1,154 @@
1
+ import { describe, it, expect, afterEach } from 'vitest'
2
+ import { BreadcrumbCollector } from './breadcrumbs'
3
+
4
+ function clickOn(el: Element): void {
5
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }))
6
+ }
7
+
8
+ describe('BreadcrumbCollector', () => {
9
+ let collector: BreadcrumbCollector
10
+
11
+ afterEach(() => {
12
+ collector?.stop()
13
+ document.body.innerHTML = ''
14
+ })
15
+
16
+ it('starts empty', () => {
17
+ collector = new BreadcrumbCollector()
18
+ collector.start()
19
+ expect(collector.getBreadcrumbs()).toHaveLength(0)
20
+ })
21
+
22
+ it('keeps only the last 20 breadcrumbs', () => {
23
+ collector = new BreadcrumbCollector()
24
+ collector.start()
25
+
26
+ const button = document.createElement('button')
27
+ document.body.appendChild(button)
28
+ for (let i = 0; i < 25; i++) {
29
+ clickOn(button)
30
+ }
31
+
32
+ expect(collector.getBreadcrumbs()).toHaveLength(20)
33
+ })
34
+
35
+ it('captures clicks with selector and name', () => {
36
+ collector = new BreadcrumbCollector()
37
+ collector.start()
38
+
39
+ const button = document.createElement('button')
40
+ button.id = 'save-btn'
41
+ button.textContent = 'Save'
42
+ document.body.appendChild(button)
43
+ clickOn(button)
44
+
45
+ const crumbs = collector.getBreadcrumbs()
46
+ expect(crumbs).toHaveLength(1)
47
+ expect(crumbs[0].type).toBe('ui')
48
+ expect(crumbs[0].category).toBe('ui.click')
49
+ expect(crumbs[0].message).toBe('Save')
50
+ expect(crumbs[0].data?.selector).toBe('#save-btn')
51
+ })
52
+
53
+ it('ignores clicks inside the widget host', () => {
54
+ collector = new BreadcrumbCollector()
55
+ collector.start()
56
+
57
+ const host = document.createElement('div')
58
+ host.id = 'mtb-widget-host'
59
+ const button = document.createElement('button')
60
+ host.appendChild(button)
61
+ document.body.appendChild(host)
62
+ clickOn(button)
63
+
64
+ expect(collector.getBreadcrumbs()).toHaveLength(0)
65
+ })
66
+
67
+ it('captures input changes without values', () => {
68
+ collector = new BreadcrumbCollector()
69
+ collector.start()
70
+
71
+ const input = document.createElement('input')
72
+ input.name = 'email'
73
+ input.value = 'secret@example.com'
74
+ document.body.appendChild(input)
75
+ input.dispatchEvent(new Event('change', { bubbles: true }))
76
+
77
+ const crumbs = collector.getBreadcrumbs()
78
+ expect(crumbs).toHaveLength(1)
79
+ expect(crumbs[0].category).toBe('ui.input')
80
+ expect(crumbs[0].data?.field).toBe('email')
81
+ expect(JSON.stringify(crumbs[0])).not.toContain('secret@example.com')
82
+ })
83
+
84
+ it('captures pushState navigation with from/to URLs', () => {
85
+ collector = new BreadcrumbCollector()
86
+ collector.start()
87
+
88
+ const from = location.href
89
+ history.pushState({}, '', '/checkout')
90
+
91
+ const crumbs = collector.getBreadcrumbs()
92
+ expect(crumbs).toHaveLength(1)
93
+ expect(crumbs[0].type).toBe('navigation')
94
+ expect(crumbs[0].category).toBe('navigation')
95
+ expect(crumbs[0].data?.from).toBe(from)
96
+ expect(crumbs[0].data?.to).toBe(location.href)
97
+ expect(crumbs[0].data?.to).toContain('/checkout')
98
+ })
99
+
100
+ it('captures console errors from the error source', () => {
101
+ collector = new BreadcrumbCollector()
102
+ collector.start()
103
+
104
+ window.onerror?.('TypeError: boom', 'app.js', 1, 1, undefined)
105
+
106
+ const crumbs = collector.getBreadcrumbs()
107
+ expect(crumbs).toHaveLength(1)
108
+ expect(crumbs[0].type).toBe('console')
109
+ expect(crumbs[0].category).toBe('console.error')
110
+ expect(crumbs[0].message).toBe('TypeError: boom')
111
+ })
112
+
113
+ it('getBreadcrumbs returns a copy', () => {
114
+ collector = new BreadcrumbCollector()
115
+ collector.start()
116
+
117
+ const button = document.createElement('button')
118
+ document.body.appendChild(button)
119
+ clickOn(button)
120
+
121
+ const copy = collector.getBreadcrumbs()
122
+ copy.pop()
123
+
124
+ expect(collector.getBreadcrumbs()).toHaveLength(1)
125
+ })
126
+
127
+ it('stops capturing after stop()', () => {
128
+ collector = new BreadcrumbCollector()
129
+ collector.start()
130
+ collector.stop()
131
+
132
+ const button = document.createElement('button')
133
+ document.body.appendChild(button)
134
+ clickOn(button)
135
+ window.onerror?.('after stop', 'app.js', 1, 1, undefined)
136
+ history.pushState({}, '', '/after-stop')
137
+
138
+ expect(collector.getBreadcrumbs()).toHaveLength(0)
139
+ })
140
+
141
+ it('keeps breadcrumbs in insertion order', () => {
142
+ collector = new BreadcrumbCollector()
143
+ collector.start()
144
+
145
+ const button = document.createElement('button')
146
+ document.body.appendChild(button)
147
+ clickOn(button)
148
+ history.pushState({}, '', '/ordered')
149
+ window.onerror?.('ordered error', 'app.js', 1, 1, undefined)
150
+
151
+ const categories = collector.getBreadcrumbs().map(c => c.category)
152
+ expect(categories).toEqual(['ui.click', 'navigation', 'console.error'])
153
+ })
154
+ })