context_drop 0.1.0 → 0.1.2

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.
@@ -6,82 +6,187 @@ import type {
6
6
 
7
7
  export class ContextDropApiClient {
8
8
  private baseUrl: string;
9
+ private cachedCsrfToken: string | null = null;
10
+ private inFlightConfigPromise: Promise<WidgetConfig> | null = null;
9
11
 
10
12
  constructor(baseUrl: string = "/context_drop") {
11
13
  this.baseUrl = baseUrl.replace(/\/+$/, "") || "/context_drop";
12
14
  }
13
15
 
14
16
  public getCsrfToken(): string | null {
17
+ const metaToken = this.getMetaCsrfToken();
18
+ if (metaToken) {
19
+ return metaToken;
20
+ }
21
+ return this.cachedCsrfToken;
22
+ }
23
+
24
+ public setCsrfToken(token: string | null): void {
25
+ this.cachedCsrfToken = token ? token.trim() : null;
26
+ }
27
+
28
+ private getMetaCsrfToken(): string | null {
15
29
  if (typeof document === "undefined") return null;
16
30
  const meta = document.querySelector('meta[name="csrf-token"]');
17
- return meta ? meta.getAttribute("content") : null;
31
+ const content = meta ? meta.getAttribute("content") : null;
32
+ return content && content.trim().length > 0 ? content.trim() : null;
18
33
  }
19
34
 
20
35
  public async fetchConfig(): Promise<WidgetConfig> {
21
- const response = await fetch(`${this.baseUrl}/config`, {
22
- method: "GET",
23
- credentials: "same-origin",
24
- headers: {
25
- Accept: "application/json"
36
+ if (this.inFlightConfigPromise) {
37
+ return this.inFlightConfigPromise;
38
+ }
39
+
40
+ this.inFlightConfigPromise = (async () => {
41
+ try {
42
+ const response = await fetch(`${this.baseUrl}/config`, {
43
+ method: "GET",
44
+ credentials: "same-origin",
45
+ headers: {
46
+ Accept: "application/json"
47
+ }
48
+ });
49
+
50
+ if (!response.ok) {
51
+ throw new Error(`Failed to fetch ContextDrop config (${response.status})`);
52
+ }
53
+
54
+ const config = (await response.json()) as WidgetConfig;
55
+ if (config && typeof config.csrf_token === "string" && config.csrf_token.trim().length > 0) {
56
+ this.cachedCsrfToken = config.csrf_token.trim();
57
+ if (typeof document !== "undefined") {
58
+ const meta = document.querySelector('meta[name="csrf-token"]');
59
+ if (meta) {
60
+ meta.setAttribute("content", this.cachedCsrfToken);
61
+ }
62
+ }
63
+ }
64
+ return config;
65
+ } finally {
66
+ this.inFlightConfigPromise = null;
26
67
  }
27
- });
68
+ })();
28
69
 
29
- if (!response.ok) {
30
- throw new Error(`Failed to fetch ContextDrop config (${response.status})`);
70
+ return this.inFlightConfigPromise;
71
+ }
72
+
73
+ public async resolveCsrfToken(forceRefresh = false): Promise<string | null> {
74
+ if (!forceRefresh) {
75
+ const metaToken = this.getMetaCsrfToken();
76
+ if (metaToken) {
77
+ return metaToken;
78
+ }
79
+ if (this.cachedCsrfToken) {
80
+ return this.cachedCsrfToken;
81
+ }
82
+ }
83
+
84
+ try {
85
+ const config = await this.fetchConfig();
86
+ if (config && config.csrf_token) {
87
+ return config.csrf_token.trim();
88
+ }
89
+ } catch {
90
+ // Continue and fall back to current token or null
31
91
  }
32
92
 
33
- return (await response.json()) as WidgetConfig;
93
+ return this.cachedCsrfToken || this.getMetaCsrfToken();
34
94
  }
35
95
 
36
- public async uploadAttachment(file: Blob, filename: string): Promise<{ signed_blob_id: string }> {
37
- const formData = new FormData();
38
- formData.append("file", file, filename);
96
+ private isCsrfError(status: number, message: string): boolean {
97
+ if (status !== 422) return false;
98
+ return /csrf|authenticity/i.test(message);
99
+ }
39
100
 
40
- const headers: Record<string, string> = {
41
- Accept: "application/json"
42
- };
43
- const csrf = this.getCsrfToken();
44
- if (csrf) {
45
- headers["X-CSRF-Token"] = csrf;
101
+ private async executeWithCsrfRetry<T>(
102
+ requestFn: (csrfToken: string | null) => Promise<Response>,
103
+ defaultErrorMessage: string
104
+ ): Promise<T> {
105
+ let csrfToken = await this.resolveCsrfToken(false);
106
+ let response = await requestFn(csrfToken);
107
+
108
+ if (response.ok) {
109
+ return (await response.json()) as T;
46
110
  }
47
111
 
48
- const response = await fetch(`${this.baseUrl}/attachments`, {
49
- method: "POST",
50
- credentials: "same-origin",
51
- headers,
52
- body: formData
53
- });
112
+ if (response.status === 422) {
113
+ const rawText = await response.text();
114
+ let parsedError: string | null = null;
115
+ try {
116
+ const json = JSON.parse(rawText) as { error?: string };
117
+ if (json && typeof json.error === "string") {
118
+ parsedError = json.error;
119
+ }
120
+ } catch {
121
+ // Not JSON
122
+ }
123
+
124
+ const errorMessage = parsedError || rawText || "";
125
+ const shouldRetryCsrf =
126
+ this.isCsrfError(response.status, errorMessage) || (!csrfToken && response.status === 422);
127
+
128
+ if (shouldRetryCsrf) {
129
+ csrfToken = await this.resolveCsrfToken(true);
130
+ response = await requestFn(csrfToken);
131
+ if (response.ok) {
132
+ return (await response.json()) as T;
133
+ }
134
+ const retryErrBody = await response.json().catch(() => ({}));
135
+ throw new Error(
136
+ (retryErrBody as { error?: string }).error || `${defaultErrorMessage} (${response.status})`
137
+ );
138
+ }
54
139
 
55
- if (!response.ok) {
56
- const errBody = await response.json().catch(() => ({}));
57
- throw new Error((errBody as { error?: string }).error || `Upload failed (${response.status})`);
140
+ throw new Error(parsedError || errorMessage || `${defaultErrorMessage} (${response.status})`);
58
141
  }
59
142
 
60
- return (await response.json()) as { signed_blob_id: string };
143
+ const errBody = await response.json().catch(() => ({}));
144
+ throw new Error(
145
+ (errBody as { error?: string }).error || `${defaultErrorMessage} (${response.status})`
146
+ );
61
147
  }
62
148
 
63
- public async submitFeedback(payload: FeedbackSubmissionPayload): Promise<FeedbackSubmissionResponse> {
64
- const headers: Record<string, string> = {
65
- "Content-Type": "application/json",
66
- Accept: "application/json"
149
+ public async uploadAttachment(file: Blob, filename: string): Promise<{ signed_blob_id: string }> {
150
+ const makeRequest = async (csrfToken: string | null) => {
151
+ const formData = new FormData();
152
+ formData.append("file", file, filename);
153
+
154
+ const headers: Record<string, string> = {
155
+ Accept: "application/json"
156
+ };
157
+ if (csrfToken) {
158
+ headers["X-CSRF-Token"] = csrfToken;
159
+ }
160
+
161
+ return fetch(`${this.baseUrl}/attachments`, {
162
+ method: "POST",
163
+ credentials: "same-origin",
164
+ headers,
165
+ body: formData
166
+ });
67
167
  };
68
- const csrf = this.getCsrfToken();
69
- if (csrf) {
70
- headers["X-CSRF-Token"] = csrf;
71
- }
72
168
 
73
- const response = await fetch(`${this.baseUrl}/feedback`, {
74
- method: "POST",
75
- credentials: "same-origin",
76
- headers,
77
- body: JSON.stringify({ feedback: payload })
78
- });
169
+ return this.executeWithCsrfRetry(makeRequest, "Upload failed");
170
+ }
79
171
 
80
- if (!response.ok) {
81
- const errBody = await response.json().catch(() => ({}));
82
- throw new Error((errBody as { error?: string }).error || `Submission failed (${response.status})`);
83
- }
172
+ public async submitFeedback(payload: FeedbackSubmissionPayload): Promise<FeedbackSubmissionResponse> {
173
+ const makeRequest = async (csrfToken: string | null) => {
174
+ const headers: Record<string, string> = {
175
+ "Content-Type": "application/json",
176
+ Accept: "application/json"
177
+ };
178
+ if (csrfToken) {
179
+ headers["X-CSRF-Token"] = csrfToken;
180
+ }
181
+
182
+ return fetch(`${this.baseUrl}/feedback`, {
183
+ method: "POST",
184
+ credentials: "same-origin",
185
+ headers,
186
+ body: JSON.stringify({ feedback: payload })
187
+ });
188
+ };
84
189
 
85
- return (await response.json()) as FeedbackSubmissionResponse;
190
+ return this.executeWithCsrfRetry(makeRequest, "Submission failed");
86
191
  }
87
192
  }
@@ -68,6 +68,7 @@ export interface WidgetConfig {
68
68
  enabled: boolean;
69
69
  position: WidgetPosition;
70
70
  placeholder: string;
71
+ csrf_token?: string | null;
71
72
  features: {
72
73
  element_selection: boolean;
73
74
  screenshot_capture: boolean;
@@ -261,6 +261,9 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
261
261
  limits: { ...this.config.limits, ...(parsed.limits || {}) },
262
262
  privacy: { ...this.config.privacy, ...(parsed.privacy || {}) }
263
263
  };
264
+ if (parsed.csrf_token) {
265
+ this.apiClient.setCsrfToken(parsed.csrf_token);
266
+ }
264
267
  } catch {
265
268
  // Ignore malformed JSON attribute
266
269
  }
@@ -296,6 +299,28 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
296
299
  let initialTop = 0;
297
300
  let dragging = false;
298
301
  let moved = false;
302
+ let suppressNextClick = false;
303
+ let suppressClickTimer: ReturnType<typeof setTimeout> | null = null;
304
+
305
+ const clearSuppressClick = (): void => {
306
+ suppressNextClick = false;
307
+ if (suppressClickTimer !== null) {
308
+ clearTimeout(suppressClickTimer);
309
+ suppressClickTimer = null;
310
+ }
311
+ };
312
+
313
+ if (onClickFallback) {
314
+ handleEl.addEventListener("click", (ev: MouseEvent) => {
315
+ if (suppressNextClick) {
316
+ clearSuppressClick();
317
+ ev.preventDefault();
318
+ ev.stopPropagation();
319
+ return;
320
+ }
321
+ onClickFallback();
322
+ });
323
+ }
299
324
 
300
325
  const onPointerMove = (ev: PointerEvent): void => {
301
326
  if (!dragging) return;
@@ -310,30 +335,48 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
310
335
  }
311
336
  };
312
337
 
313
- const onPointerUp = (): void => {
314
- if (!dragging) return;
338
+ const cleanupDrag = (): void => {
315
339
  dragging = false;
316
340
  this.pinDockEl?.classList.remove("is-dragging");
317
341
  window.removeEventListener("pointermove", onPointerMove);
318
342
  window.removeEventListener("pointerup", onPointerUp);
319
- if (!moved && onClickFallback) {
320
- onClickFallback();
343
+ window.removeEventListener("pointercancel", onPointerCancel);
344
+ };
345
+
346
+ const onPointerUp = (): void => {
347
+ if (!dragging) return;
348
+ cleanupDrag();
349
+ if (moved && onClickFallback) {
350
+ suppressNextClick = true;
351
+ if (suppressClickTimer !== null) {
352
+ clearTimeout(suppressClickTimer);
353
+ }
354
+ suppressClickTimer = setTimeout(() => {
355
+ suppressNextClick = false;
356
+ suppressClickTimer = null;
357
+ }, 0);
321
358
  }
322
359
  };
323
360
 
361
+ const onPointerCancel = (): void => {
362
+ if (!dragging) return;
363
+ cleanupDrag();
364
+ clearSuppressClick();
365
+ };
366
+
324
367
  handleEl.addEventListener("pointerdown", (ev: PointerEvent) => {
325
368
  // Only primary mouse button or touch
326
369
  if (ev.button !== 0) return;
327
- const targetEl = ev.target instanceof Element ? ev.target : null;
328
- if (
329
- targetEl &&
330
- handleEl !== this.pinDockEl &&
331
- targetEl.closest("button")
332
- ) {
370
+ const targetEl =
371
+ ev.target && typeof (ev.target as Element).closest === "function"
372
+ ? (ev.target as Element)
373
+ : null;
374
+ const closestBtn = targetEl?.closest("button");
375
+ if (closestBtn && closestBtn !== handleEl && handleEl.contains(closestBtn)) {
333
376
  return;
334
377
  }
335
378
 
336
- if (!this.rootContainer) return;
379
+ if (!this.rootContainer || typeof window === "undefined") return;
337
380
  const rect = this.rootContainer.getBoundingClientRect();
338
381
  startX = ev.clientX;
339
382
  startY = ev.clientY;
@@ -341,9 +384,11 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
341
384
  initialTop = this.freePos ? this.freePos.top : rect.top;
342
385
  dragging = true;
343
386
  moved = false;
387
+ clearSuppressClick();
344
388
 
345
389
  window.addEventListener("pointermove", onPointerMove);
346
390
  window.addEventListener("pointerup", onPointerUp);
391
+ window.addEventListener("pointercancel", onPointerCancel);
347
392
  });
348
393
  }
349
394
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ContextDrop
4
- VERSION = "0.1.0"
4
+ VERSION = '0.1.2'
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: context_drop
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.1.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Kemal Elmizan
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-10 00:00:00.000000000 Z
11
+ date: 2026-11-11 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: actionpack
@@ -176,6 +176,7 @@ files:
176
176
  - app/controllers/context_drop/health_controller.rb
177
177
  - app/controllers/context_drop/mcp_controller.rb
178
178
  - app/helpers/context_drop/widget_helper.rb
179
+ - app/javascript/context_drop/__tests__/api-client.test.ts
179
180
  - app/javascript/context_drop/__tests__/widget.test.ts
180
181
  - app/javascript/context_drop/api-client.ts
181
182
  - app/javascript/context_drop/element-picker.ts