context-drop 0.2.0 → 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.
@@ -1,5 +1,5 @@
1
1
  import crypto from "node:crypto";
2
- import { toFeedbackSummary } from "./memory.js";
2
+ import { hasAuthenticatedSubmitter, toFeedbackSummary } from "./memory.js";
3
3
  function resolvePgSecret(explicit) {
4
4
  const raw = explicit ||
5
5
  process.env.CONTEXT_DROP_SECRET ||
@@ -92,8 +92,13 @@ export function createPostgresStorageAdapter(options) {
92
92
  submitter JSONB NOT NULL DEFAULT '{}'::jsonb,
93
93
  metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
94
94
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
95
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
95
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
96
+ deleted_at TIMESTAMPTZ
96
97
  );
98
+ `);
99
+ await pool.query(`
100
+ ALTER TABLE context_drop_feedbacks
101
+ ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
97
102
  `);
98
103
  await pool.query(`
99
104
  CREATE INDEX IF NOT EXISTS idx_context_drop_feedbacks_env_status
@@ -191,10 +196,14 @@ export function createPostgresStorageAdapter(options) {
191
196
  element_references: elements,
192
197
  attachments,
193
198
  created_at: toIsoString(row["created_at"]),
194
- updated_at: toIsoString(row["updated_at"])
199
+ updated_at: toIsoString(row["updated_at"]),
200
+ deleted_at: row["deleted_at"] ? toIsoString(row["deleted_at"]) : null
195
201
  };
196
202
  }
197
203
  return {
204
+ getOwnershipSecret() {
205
+ return secretKey;
206
+ },
198
207
  async savePendingBlob(blob) {
199
208
  await ensureMigrated();
200
209
  const rawId = crypto.randomUUID();
@@ -338,6 +347,9 @@ export function createPostgresStorageAdapter(options) {
338
347
  const offset = Math.max(0, filter.offset ?? 0);
339
348
  const clauses = [];
340
349
  const values = [];
350
+ if (!filter.include_deleted) {
351
+ clauses.push("f.deleted_at IS NULL");
352
+ }
341
353
  if (filter.environment && filter.environment.trim().length > 0) {
342
354
  values.push(filter.environment.trim().toLowerCase());
343
355
  clauses.push(`LOWER(f.environment) = $${values.length}`);
@@ -372,6 +384,47 @@ export function createPostgresStorageAdapter(options) {
372
384
  records: hydrated.map(toFeedbackSummary)
373
385
  };
374
386
  },
387
+ async listOwnFeedbacks(query) {
388
+ await ensureMigrated();
389
+ const limit = Math.max(1, Math.min(50, query.limit ?? 20));
390
+ const ownershipClauses = [];
391
+ const values = [];
392
+ if (hasAuthenticatedSubmitter(query.submitter)) {
393
+ values.push(String(query.submitter?.type || "User").trim());
394
+ const typeParam = `$${values.length}`;
395
+ values.push(String(query.submitter?.id).trim());
396
+ const idParam = `$${values.length}`;
397
+ ownershipClauses.push(`(COALESCE(NULLIF(f.submitter->>'type', ''), 'User') = ${typeParam} AND f.submitter->>'id' = ${idParam})`);
398
+ }
399
+ if (query.session_id && query.session_id.trim().length > 0) {
400
+ values.push(query.session_id.trim());
401
+ const sidParam = `$${values.length}`;
402
+ ownershipClauses.push(`((f.submitter->>'id' IS NULL OR f.submitter->>'id' = '') AND f.session_id = ${sidParam})`);
403
+ }
404
+ const numericTokenIds = (query.token_ids ?? [])
405
+ .map((t) => Number(t))
406
+ .filter((n) => Number.isInteger(n) && n > 0);
407
+ if (numericTokenIds.length > 0) {
408
+ values.push(numericTokenIds);
409
+ const idsParam = `$${values.length}`;
410
+ ownershipClauses.push(`((f.submitter->>'id' IS NULL OR f.submitter->>'id' = '') AND f.id = ANY(${idsParam}::bigint[]))`);
411
+ }
412
+ if (ownershipClauses.length === 0) {
413
+ return { total: 0, records: [] };
414
+ }
415
+ const whereSql = `WHERE f.deleted_at IS NULL AND (${ownershipClauses.join(" OR ")})`;
416
+ const countRes = await pool.query(`SELECT COUNT(*)::int AS total FROM context_drop_feedbacks f ${whereSql}`, values);
417
+ const total = Number(countRes.rows[0]?.["total"] ?? 0);
418
+ const pageValues = [...values, limit];
419
+ const rowsRes = await pool.query(`SELECT f.* FROM context_drop_feedbacks f ${whereSql}
420
+ ORDER BY f.created_at DESC, f.id DESC
421
+ LIMIT $${pageValues.length}`, pageValues);
422
+ const hydrated = await Promise.all(rowsRes.rows.map(hydrateFeedbackRow));
423
+ return {
424
+ total,
425
+ records: hydrated
426
+ };
427
+ },
375
428
  async getFeedback(id) {
376
429
  await ensureMigrated();
377
430
  const res = await pool.query("SELECT * FROM context_drop_feedbacks WHERE id = $1", [
@@ -382,6 +435,136 @@ export function createPostgresStorageAdapter(options) {
382
435
  return null;
383
436
  return hydrateFeedbackRow(row);
384
437
  },
438
+ async updateFeedback(id, input) {
439
+ await ensureMigrated();
440
+ const fbId = Number(id);
441
+ const existing = await this.getFeedback(fbId);
442
+ if (!existing || existing.deleted_at)
443
+ return null;
444
+ const nextMessage = input.message !== undefined ? input.message : existing.message;
445
+ const nextMetadata = input.metadata !== undefined ? input.metadata : existing.metadata;
446
+ await pool.query(`UPDATE context_drop_feedbacks
447
+ SET message = $1, metadata = $2::jsonb, updated_at = NOW()
448
+ WHERE id = $3`, [nextMessage, JSON.stringify(nextMetadata || {}), fbId]);
449
+ const elIdByRef = new Map();
450
+ if (input.element_references !== undefined) {
451
+ await pool.query("DELETE FROM context_drop_element_references WHERE feedback_id = $1", [fbId]);
452
+ for (let idx = 0; idx < input.element_references.length; idx++) {
453
+ const el = input.element_references[idx];
454
+ const elRes = await pool.query(`INSERT INTO context_drop_element_references
455
+ (feedback_id, client_ref, tag_name, selector, dom_path, text_content,
456
+ attributes_snapshot, bounding_rect, viewport, metadata, captured_at)
457
+ VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb, $11::timestamptz)
458
+ RETURNING id`, [
459
+ fbId,
460
+ el.client_ref,
461
+ el.tag_name,
462
+ el.selector,
463
+ el.dom_path,
464
+ el.text_content,
465
+ JSON.stringify(el.attributes_snapshot || {}),
466
+ JSON.stringify(el.bounding_rect || {}),
467
+ JSON.stringify(el.viewport || {}),
468
+ JSON.stringify(el.metadata || {}),
469
+ el.captured_at
470
+ ]);
471
+ elIdByRef.set(el.client_ref || String(idx), Number(elRes.rows[0]["id"]));
472
+ }
473
+ }
474
+ else {
475
+ existing.element_references.forEach((el, idx) => {
476
+ elIdByRef.set(el.client_ref || String(idx), Number(el.id));
477
+ });
478
+ }
479
+ if (input.attachments !== undefined) {
480
+ const retainedIds = new Set();
481
+ const prevById = new Map();
482
+ for (const a of existing.attachments) {
483
+ prevById.set(String(a.id), a);
484
+ }
485
+ for (const spec of input.attachments) {
486
+ if (spec.kind === "retain") {
487
+ const prev = prevById.get(String(spec.existing_id));
488
+ if (!prev)
489
+ continue;
490
+ retainedIds.add(Number(prev.id));
491
+ const linkedElId = spec.element_client_ref !== undefined
492
+ ? spec.element_client_ref
493
+ ? elIdByRef.get(spec.element_client_ref) ?? null
494
+ : null
495
+ : input.element_references === undefined && prev.element_reference_id !== null
496
+ ? Number(prev.element_reference_id)
497
+ : null;
498
+ const nextAttMeta = spec.update_metadata && spec.metadata ? spec.metadata : prev.metadata;
499
+ await pool.query(`UPDATE context_drop_attachments
500
+ SET element_reference_id = $1, metadata = $2::jsonb
501
+ WHERE id = $3`, [linkedElId, JSON.stringify(nextAttMeta || {}), Number(prev.id)]);
502
+ }
503
+ }
504
+ for (const prev of existing.attachments) {
505
+ if (!retainedIds.has(Number(prev.id))) {
506
+ await pool.query("DELETE FROM context_drop_attachments WHERE id = $1", [
507
+ Number(prev.id)
508
+ ]);
509
+ if (prev.blob_key && blobStore?.deleteBlob) {
510
+ await blobStore.deleteBlob(prev.blob_key);
511
+ }
512
+ }
513
+ }
514
+ for (const spec of input.attachments) {
515
+ if (spec.kind !== "create")
516
+ continue;
517
+ const linkedElId = spec.element_client_ref
518
+ ? elIdByRef.get(spec.element_client_ref) ?? null
519
+ : null;
520
+ let blobKey = null;
521
+ let inlineBytes = null;
522
+ if (spec.data) {
523
+ if (blobStore) {
524
+ const saved = await blobStore.putBlob({
525
+ key: `att_${fbId}_${crypto.randomUUID()}`,
526
+ data: spec.data,
527
+ contentType: spec.content_type || "image/png",
528
+ filename: spec.filename || "attachment.png"
529
+ });
530
+ blobKey = saved.key;
531
+ }
532
+ else {
533
+ inlineBytes = Buffer.from(spec.data);
534
+ }
535
+ }
536
+ await pool.query(`INSERT INTO context_drop_attachments
537
+ (feedback_id, element_reference_id, attachment_type, filename, content_type, byte_size, blob_key, data, metadata)
538
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb)`, [
539
+ fbId,
540
+ linkedElId,
541
+ spec.attachment_type,
542
+ spec.filename,
543
+ spec.content_type,
544
+ spec.byte_size,
545
+ blobKey,
546
+ inlineBytes,
547
+ JSON.stringify(spec.metadata || {})
548
+ ]);
549
+ }
550
+ }
551
+ return this.getFeedback(fbId);
552
+ },
553
+ async softDeleteFeedback(id) {
554
+ await ensureMigrated();
555
+ const fbId = Number(id);
556
+ const existing = await this.getFeedback(fbId);
557
+ if (!existing || existing.deleted_at)
558
+ return null;
559
+ const res = await pool.query(`UPDATE context_drop_feedbacks
560
+ SET deleted_at = NOW(), updated_at = NOW()
561
+ WHERE id = $1 AND deleted_at IS NULL
562
+ RETURNING *`, [fbId]);
563
+ const row = res.rows[0];
564
+ if (!row)
565
+ return null;
566
+ return hydrateFeedbackRow(row);
567
+ },
385
568
  async getAttachment(attachmentId) {
386
569
  await ensureMigrated();
387
570
  const res = await pool.query(`SELECT a.*, e.selector AS element_selector
@@ -428,13 +611,13 @@ export function createPostgresStorageAdapter(options) {
428
611
  async updateFeedbackStatus(id, status) {
429
612
  await ensureMigrated();
430
613
  const existing = await this.getFeedback(id);
431
- if (!existing)
614
+ if (!existing || existing.deleted_at)
432
615
  return null;
433
- const updatedRes = await pool.query(`UPDATE context_drop_feedbacks
616
+ const res = await pool.query(`UPDATE context_drop_feedbacks
434
617
  SET status = $1, updated_at = NOW()
435
618
  WHERE id = $2
436
619
  RETURNING *`, [status, Number(id)]);
437
- const row = updatedRes.rows[0];
620
+ const row = res.rows[0];
438
621
  if (!row)
439
622
  return null;
440
623
  return {
@@ -1,5 +1,5 @@
1
1
  import type { BoundingRectSnapshot, SelectionMode, ViewportSnapshot, WidgetPosition } from "../../app/javascript/context_drop/types.js";
2
- export declare const VERSION = "0.2.0";
2
+ export declare const VERSION = "0.3.0";
3
3
  export type FeedbackStatus = "new" | "reviewed" | "resolved" | "dismissed";
4
4
  export declare const FEEDBACK_STATUSES: readonly FeedbackStatus[];
5
5
  export interface SubmitterIdentity {
@@ -47,6 +47,7 @@ export interface StoredFeedbackRecord {
47
47
  attachments: StoredAttachment[];
48
48
  created_at: string;
49
49
  updated_at: string;
50
+ deleted_at?: string | null;
50
51
  }
51
52
  export interface FeedbackSummaryItem {
52
53
  id: number | string;
@@ -60,6 +61,8 @@ export interface FeedbackSummaryItem {
60
61
  element_references_count: number;
61
62
  element_selectors: string[];
62
63
  created_at: string;
64
+ deleted?: boolean;
65
+ deleted_at?: string | null;
63
66
  }
64
67
  export interface FeedbackQueryFilter {
65
68
  environment?: string | null;
@@ -68,6 +71,7 @@ export interface FeedbackQueryFilter {
68
71
  query?: string | null;
69
72
  limit?: number;
70
73
  offset?: number;
74
+ include_deleted?: boolean;
71
75
  }
72
76
  export interface ValidatedUpload {
73
77
  data: Uint8Array;
@@ -97,6 +101,17 @@ export interface CreateAttachmentInput {
97
101
  data: Uint8Array | null;
98
102
  metadata: Record<string, unknown>;
99
103
  }
104
+ export interface RetainedAttachmentInput {
105
+ existing_id: string | number;
106
+ element_client_ref?: string | null;
107
+ metadata?: Record<string, unknown>;
108
+ update_metadata?: boolean;
109
+ }
110
+ export type UpdateAttachmentSpec = ({
111
+ kind: "retain";
112
+ } & RetainedAttachmentInput) | ({
113
+ kind: "create";
114
+ } & CreateAttachmentInput);
100
115
  export interface CreateFeedbackRecordInput {
101
116
  environment: string;
102
117
  message: string | null;
@@ -108,6 +123,18 @@ export interface CreateFeedbackRecordInput {
108
123
  element_references: SanitizedElementInput[];
109
124
  attachments: CreateAttachmentInput[];
110
125
  }
126
+ export interface UpdateFeedbackRecordInput {
127
+ message?: string | null;
128
+ metadata?: Record<string, unknown>;
129
+ element_references?: SanitizedElementInput[];
130
+ attachments?: UpdateAttachmentSpec[];
131
+ }
132
+ export interface OwnFeedbackLookupQuery {
133
+ submitter?: SubmitterIdentity | null;
134
+ session_id?: string | null;
135
+ token_ids?: Array<string | number>;
136
+ limit?: number;
137
+ }
111
138
  export interface BlobStorageAdapter {
112
139
  putBlob(input: {
113
140
  key: string;
@@ -130,7 +157,13 @@ export interface StorageAdapter {
130
157
  total: number;
131
158
  records: FeedbackSummaryItem[];
132
159
  }>;
160
+ listOwnFeedbacks(query: OwnFeedbackLookupQuery): Promise<{
161
+ total: number;
162
+ records: StoredFeedbackRecord[];
163
+ }>;
133
164
  getFeedback(id: string | number): Promise<StoredFeedbackRecord | null>;
165
+ updateFeedback(id: string | number, input: UpdateFeedbackRecordInput): Promise<StoredFeedbackRecord | null>;
166
+ softDeleteFeedback(id: string | number): Promise<StoredFeedbackRecord | null>;
134
167
  getAttachment(attachmentId: string | number): Promise<{
135
168
  attachment: StoredAttachment;
136
169
  element_selector: string | null;
@@ -141,6 +174,7 @@ export interface StorageAdapter {
141
174
  previous_status: FeedbackStatus;
142
175
  feedback: StoredFeedbackRecord;
143
176
  } | null>;
177
+ getOwnershipSecret?(): Buffer;
144
178
  }
145
179
  export interface RemoteMcpEnvironmentConfig {
146
180
  url: string;
@@ -156,6 +190,7 @@ export interface ContextDropServerConfig {
156
190
  selectionMode?: "auto" | SelectionMode;
157
191
  allowAnonymous?: boolean;
158
192
  allowedOrigins?: Array<string | RegExp>;
193
+ ownershipSecret?: string;
159
194
  storage?: StorageAdapter;
160
195
  storageDir?: string;
161
196
  features?: {
@@ -181,6 +216,8 @@ export interface ContextDropServerConfig {
181
216
  resolveSubmitter?: (request: Request) => Promise<SubmitterIdentity | null> | SubmitterIdentity | null;
182
217
  authorizeSubmission?: (request: Request, submitter: SubmitterIdentity | null) => Promise<boolean> | boolean;
183
218
  onFeedbackCreated?: (feedback: StoredFeedbackRecord) => Promise<void> | void;
219
+ onFeedbackUpdated?: (feedback: StoredFeedbackRecord) => Promise<void> | void;
220
+ onFeedbackDeleted?: (feedback: StoredFeedbackRecord) => Promise<void> | void;
184
221
  mcp?: {
185
222
  enabled?: boolean;
186
223
  apiKey?: string;
@@ -1,4 +1,4 @@
1
- export const VERSION = "0.2.0";
1
+ export const VERSION = "0.3.0";
2
2
  export const FEEDBACK_STATUSES = [
3
3
  "new",
4
4
  "reviewed",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-drop",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Self-hosted contextual feedback widget, Next.js & Rails integration, and unified multi-environment MCP server for AI coding agents.",
5
5
  "type": "module",
6
6
  "main": "./dist/src/index.js",