@seaproof/core 0.1.0-beta.1 → 0.1.0-beta.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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "0.1.0-beta.1";
2
+ var SDK_VERSION = "0.1.0-beta.2";
3
3
 
4
4
  // src/context.ts
5
5
  function browserContext() {
@@ -205,6 +205,113 @@ function describeError(error) {
205
205
  return error instanceof Error ? error.message : String(error);
206
206
  }
207
207
 
208
+ // src/errorReporter.ts
209
+ var MAX_BATCH = 20;
210
+ var MAX_PENDING = 50;
211
+ var MAX_PER_PAGE = 100;
212
+ var MAX_PER_PROBLEM = 10;
213
+ var MAX_ATTEMPTS = 4;
214
+ var MAX_BREADCRUMBS = 30;
215
+ var ErrorReporter = class {
216
+ constructor(options) {
217
+ this.options = options;
218
+ }
219
+ options;
220
+ pending = [];
221
+ perProblem = /* @__PURE__ */ new Map();
222
+ total = 0;
223
+ timer;
224
+ sending = false;
225
+ attempts = 0;
226
+ /** Events waiting, for tests and `flush`. */
227
+ get size() {
228
+ return this.pending.length;
229
+ }
230
+ add(event) {
231
+ if (this.options.enabled() === false) return;
232
+ const key = event.fingerprint ?? `${event.type}|${event.message}|${firstFrame(event.stack)}`;
233
+ const seen = this.perProblem.get(key) ?? 0;
234
+ if (this.total >= MAX_PER_PAGE || seen >= MAX_PER_PROBLEM) return;
235
+ this.perProblem.set(key, seen + 1);
236
+ this.total++;
237
+ this.pending.push(event);
238
+ if (this.pending.length > MAX_PENDING) this.pending.splice(0, this.pending.length - MAX_PENDING);
239
+ this.schedule(this.options.delayMs ?? 1e3);
240
+ }
241
+ /** Call when the environment becomes known: sends what waited, or forgets it. */
242
+ decided() {
243
+ if (this.options.enabled() === false) this.pending = [];
244
+ else this.schedule(0);
245
+ }
246
+ /** Sends what is waiting now. With `keepalive` the request outlives the page, for `pagehide`. */
247
+ async flush(keepalive = false) {
248
+ if (this.timer !== void 0) clearTimeout(this.timer);
249
+ this.timer = void 0;
250
+ if (this.sending || this.options.enabled() !== true || this.pending.length === 0) return;
251
+ const batch = this.pending.splice(0, MAX_BATCH);
252
+ this.sending = true;
253
+ try {
254
+ await this.options.send(batch, keepalive);
255
+ this.attempts = 0;
256
+ } catch (error) {
257
+ const retry = !(error instanceof SeaproofError) || error.status === 429 || error.status >= 500;
258
+ if (retry && ++this.attempts < MAX_ATTEMPTS) {
259
+ this.pending.unshift(...batch);
260
+ this.sending = false;
261
+ this.schedule(2e3 * 2 ** this.attempts);
262
+ return;
263
+ }
264
+ this.attempts = 0;
265
+ } finally {
266
+ this.sending = false;
267
+ }
268
+ if (this.pending.length > 0) this.schedule(0);
269
+ }
270
+ dispose() {
271
+ if (this.timer !== void 0) clearTimeout(this.timer);
272
+ this.timer = void 0;
273
+ this.pending = [];
274
+ }
275
+ schedule(delayMs) {
276
+ if (this.options.enabled() !== true || this.timer !== void 0) return;
277
+ this.timer = setTimeout(() => {
278
+ this.timer = void 0;
279
+ void this.flush();
280
+ }, delayMs);
281
+ }
282
+ };
283
+ function firstFrame(stack) {
284
+ return stack?.split("\n").find((line) => /^\s*at |@/.test(line))?.trim() ?? "";
285
+ }
286
+ function describeThrown(error, fallbackMessage) {
287
+ if (error instanceof Error) {
288
+ return { type: error.name || error.constructor?.name || "Error", message: error.message || fallbackMessage || "", stack: error.stack };
289
+ }
290
+ if (typeof error === "string") return { type: "Error", message: error };
291
+ let message = fallbackMessage ?? "";
292
+ try {
293
+ message = fallbackMessage ?? JSON.stringify(error) ?? String(error);
294
+ } catch {
295
+ message = String(error);
296
+ }
297
+ return { type: "Error", message };
298
+ }
299
+ function breadcrumbsFrom(entries, message) {
300
+ const list = [...entries];
301
+ const last = list.at(-1);
302
+ if (last?.kind === "error" && message.includes(last.message)) list.pop();
303
+ return list.slice(-MAX_BREADCRUMBS).map((e) => {
304
+ const level = typeof e.level === "string" ? e.level : e.kind === "network" && (typeof e.error === "string" || typeof e.status === "number" && e.status >= 500) ? "error" : void 0;
305
+ return { at: e.t, kind: e.kind, message: e.message, ...level ? { level } : {} };
306
+ });
307
+ }
308
+
309
+ // src/fastTrack.ts
310
+ function canFastTrackType(tester, type) {
311
+ if (!tester?.canFastTrack || type === "question") return false;
312
+ return tester.fastTrackTypes ? tester.fastTrackTypes.includes(type) : true;
313
+ }
314
+
208
315
  // src/reporter.ts
209
316
  var KEY = "seaproof.reporter-key";
210
317
  var SEEN = "seaproof.seen-replies";
@@ -256,7 +363,7 @@ function defaultStorage() {
256
363
 
257
364
  // src/client.ts
258
365
  var DEFAULT_ENDPOINT = "https://api.seaproof.io";
259
- var MAX_CRASH_REPORTS = 3;
366
+ var TESTER_SESSION = "seaproof.tester-session";
260
367
  function newConversationId() {
261
368
  if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
262
369
  const bytes = crypto.getRandomValues(new Uint8Array(16));
@@ -273,22 +380,29 @@ function createSeaproof(options) {
273
380
  const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
274
381
  const diagnostics = new Diagnostics();
275
382
  const listeners = /* @__PURE__ */ new Set();
276
- const reportedCrashes = /* @__PURE__ */ new Set();
277
- const identity = new ReporterIdentity(options.storage ?? defaultStorage());
383
+ const sessionId = newConversationId();
384
+ const storage = options.storage ?? defaultStorage();
385
+ const identity = new ReporterIdentity(storage);
278
386
  let environment;
279
387
  let environmentName;
280
388
  let branding;
281
389
  let launcher;
390
+ let showPoweredBy = false;
282
391
  let reporter = options.reporter;
392
+ let tester;
393
+ const testerToken = () => storage.getItem(TESTER_SESSION) || void 0;
283
394
  const userHeaders = (user) => user?.externalId && user.userHash ? { "X-Seaproof-User": encodeURIComponent(user.externalId), "X-Seaproof-User-Hash": user.userHash } : {};
284
- async function api(path, body, method = "POST", user = reporter) {
395
+ async function api(path, body, method = "POST", user = reporter, keepalive = false) {
285
396
  const response = await doFetch(`${endpoint}${path}`, {
286
397
  method,
398
+ ...keepalive ? { keepalive } : {},
287
399
  headers: {
288
400
  "Content-Type": "application/json",
289
401
  "X-Seaproof-Key": options.apiKey,
290
402
  "X-Seaproof-Reporter": identity.key,
291
- ...userHeaders(user)
403
+ ...userHeaders(user),
404
+ // The tester session means nothing to a production key; it is never sent there.
405
+ ...isTesterMode() && testerToken() ? { "X-Seaproof-Tester": testerToken() } : {}
292
406
  },
293
407
  body: body === void 0 ? void 0 : JSON.stringify(body)
294
408
  });
@@ -310,6 +424,43 @@ function createSeaproof(options) {
310
424
  );
311
425
  }
312
426
  const isTesterMode = () => options.mode === "tester" || (options.mode ?? "auto") === "auto" && environment === "test";
427
+ const errorsEnabled = () => {
428
+ const chosen = options.reportErrors ?? options.reportCrashes;
429
+ if (chosen !== void 0) return chosen;
430
+ if (options.mode === "tester") return true;
431
+ if (options.mode === "production") return false;
432
+ return environment === void 0 ? void 0 : environment === "test";
433
+ };
434
+ const errors = new ErrorReporter({
435
+ enabled: errorsEnabled,
436
+ send: async (events, keepalive) => {
437
+ await api("/api/v1/sdk/errors", { events }, "POST", reporter, keepalive);
438
+ }
439
+ });
440
+ function captureError(error, handled, capture = {}, fallbackMessage) {
441
+ if (errorsEnabled() === false) return;
442
+ const thrown = describeThrown(error, fallbackMessage);
443
+ const event = {
444
+ id: newConversationId(),
445
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
446
+ type: thrown.type,
447
+ message: thrown.message,
448
+ stack: thrown.stack,
449
+ handled,
450
+ sessionId,
451
+ fingerprint: capture.fingerprint,
452
+ context: mergeContext(
453
+ browserContext(),
454
+ options.appVersion ? { appVersion: options.appVersion } : void 0,
455
+ options.commit ? { commit: options.commit } : void 0,
456
+ options.context?.(),
457
+ capture.context
458
+ ),
459
+ // An uncaught error was just added to the diagnostics under the browser's message.
460
+ breadcrumbs: breadcrumbsFrom(diagnostics.list(), fallbackMessage ?? thrown.message)
461
+ };
462
+ errors.add(event);
463
+ }
313
464
  const client = {
314
465
  get environment() {
315
466
  return environment;
@@ -326,10 +477,20 @@ function createSeaproof(options) {
326
477
  get launcher() {
327
478
  return launcher;
328
479
  },
480
+ get tester() {
481
+ return tester;
482
+ },
483
+ get showPoweredBy() {
484
+ return showPoweredBy;
485
+ },
329
486
  identify(next) {
330
487
  reporter = next ?? void 0;
331
488
  },
332
489
  diagnostics,
490
+ sessionId,
491
+ captureException(error, capture) {
492
+ captureError(error, capture?.handled ?? true, capture);
493
+ },
333
494
  async whoAmI() {
334
495
  return await (await api("/api/v1/sdk/whoami", void 0, "GET")).json();
335
496
  },
@@ -340,7 +501,10 @@ function createSeaproof(options) {
340
501
  environmentName = project.environmentName;
341
502
  if (options.branding !== false) branding = project.branding;
342
503
  launcher = project.launcher;
504
+ showPoweredBy = project.showPoweredBy === true;
505
+ errors.decided();
343
506
  listeners.forEach((l) => l());
507
+ if (isTesterMode() && testerToken()) await refreshTester();
344
508
  } catch (error) {
345
509
  console.warn(`Seaproof: could not fetch the project for the API key. ${describeError(error)}`);
346
510
  }
@@ -367,7 +531,8 @@ function createSeaproof(options) {
367
531
  options.commit ? { commit: options.commit } : void 0,
368
532
  options.context?.(),
369
533
  feedback.context,
370
- automatic ? { custom: { "seaproof.source": "crash" } } : void 0
534
+ automatic ? { custom: { "seaproof.source": "crash" } } : void 0,
535
+ { sessionId }
371
536
  );
372
537
  const sender = feedback.reporter ?? reporter;
373
538
  const response = await api(
@@ -378,6 +543,7 @@ function createSeaproof(options) {
378
543
  description: feedback.description,
379
544
  severity: feedback.severity,
380
545
  linkedTo: feedback.linkedTo,
546
+ doItNow: feedback.doItNow && canFastTrackType(tester, feedback.type ?? "bug") ? true : void 0,
381
547
  reporter: withoutHash(sender),
382
548
  context,
383
549
  attachments: attachments.map(describeAttachment)
@@ -446,32 +612,52 @@ function createSeaproof(options) {
446
612
  return false;
447
613
  }
448
614
  },
615
+ async requestTesterCode(email) {
616
+ await api("/api/v1/sdk/testers/code", { email });
617
+ },
618
+ async signInTester(email, code) {
619
+ const session = await (await api("/api/v1/sdk/testers/session", { email, code })).json();
620
+ storage.setItem(TESTER_SESSION, session.token);
621
+ tester = session.tester;
622
+ listeners.forEach((l) => l());
623
+ return session.tester;
624
+ },
625
+ async signOutTester() {
626
+ try {
627
+ if (testerToken()) await api("/api/v1/sdk/testers/session", void 0, "DELETE");
628
+ } finally {
629
+ storage.setItem(TESTER_SESSION, "");
630
+ tester = void 0;
631
+ listeners.forEach((l) => l());
632
+ }
633
+ },
449
634
  dispose() {
635
+ void errors.flush(true);
636
+ errors.dispose();
450
637
  uninstall();
638
+ removePageHide();
451
639
  listeners.clear();
452
640
  }
453
641
  };
454
- function reportCrash(error, message) {
455
- if (!options.reportCrashes || reportedCrashes.size >= MAX_CRASH_REPORTS || reportedCrashes.has(message)) return;
456
- reportedCrashes.add(message);
457
- const firstLine = message.split("\n")[0];
458
- const stack = error instanceof Error && error.stack ? `
459
-
460
- ${error.stack}` : "";
461
- client.submit(
462
- {
463
- type: "bug",
464
- title: `Crash: ${firstLine.length <= 180 ? firstLine : `${firstLine.slice(0, 177)}...`}`,
465
- description: `${message}${stack}`
466
- },
467
- { automatic: true }
468
- ).catch((e) => console.warn(`Seaproof: could not report the crash. ${describeError(e)}`));
642
+ async function refreshTester() {
643
+ try {
644
+ tester = await (await api("/api/v1/sdk/testers/me", void 0, "GET")).json();
645
+ } catch (error) {
646
+ if (error instanceof SeaproofError && error.status === 401) storage.setItem(TESTER_SESSION, "");
647
+ tester = void 0;
648
+ }
649
+ listeners.forEach((l) => l());
469
650
  }
651
+ const onPageHide = () => void errors.flush(true);
652
+ if (typeof window !== "undefined") window.addEventListener("pagehide", onPageHide);
653
+ const removePageHide = () => {
654
+ if (typeof window !== "undefined") window.removeEventListener("pagehide", onPageHide);
655
+ };
470
656
  const uninstall = options.diagnostics === false ? () => {
471
657
  } : installCapture(diagnostics, {
472
658
  ...options.diagnostics,
473
659
  ignoreUrl: (url) => url.startsWith(endpoint),
474
- onError: reportCrash
660
+ onError: (error, message) => captureError(error, false, {}, message)
475
661
  });
476
662
  return client;
477
663
  }
@@ -570,6 +756,242 @@ var ScreenRecorder = class {
570
756
  }
571
757
  };
572
758
 
759
+ // src/pointing.ts
760
+ var INTERACTIVE = [
761
+ "a[href]",
762
+ "button",
763
+ "input:not([type=hidden])",
764
+ "select",
765
+ "textarea",
766
+ "summary",
767
+ "label",
768
+ "[role=button]",
769
+ "[role=link]",
770
+ "[role=tab]",
771
+ "[role=menuitem]",
772
+ "[role=checkbox]",
773
+ "[role=radio]",
774
+ "[role=switch]",
775
+ "[role=option]",
776
+ "[contenteditable=true]"
777
+ ].join(",");
778
+ var SIMPLE = "img,svg,h1,h2,h3,h4,h5,h6,li,tr,td,th,p";
779
+ var MAX_SHARE = 0.4;
780
+ var MAX_NAME = 60;
781
+ function elementAt(x, y, doc = document) {
782
+ const view = doc.defaultView;
783
+ const area = (view?.innerWidth ?? 0) * (view?.innerHeight ?? 0);
784
+ const hit = doc.elementsFromPoint(x, y).find((el) => !el.closest("[data-seaproof-ignore]"));
785
+ if (!hit || hit === doc.documentElement || hit === doc.body) return null;
786
+ const target = hit.closest(INTERACTIVE) ?? hit.closest(SIMPLE) ?? hit;
787
+ const rect = target.getBoundingClientRect();
788
+ if (rect.width === 0 || rect.height === 0) return null;
789
+ if (area > 0 && rect.width * rect.height / area > MAX_SHARE) return null;
790
+ return { box: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, ...describeElement(target) };
791
+ }
792
+ function describeElement(el) {
793
+ return { role: roleOf(el), name: isMasked(el) ? null : nameOf(el) };
794
+ }
795
+ function pinLabel(element) {
796
+ if (!element) return null;
797
+ const { role, name } = element;
798
+ if (role && name) return `${role} "${name}"`;
799
+ return role ?? (name ? `"${name}"` : null);
800
+ }
801
+ function pinMessage(pins) {
802
+ return pins.map((p) => {
803
+ const note = p.note?.trim();
804
+ return `Pin ${p.number}: ${pinLabel(p.element) ?? "a spot on the screen"}${note ? `: "${note}"` : ""}`;
805
+ }).join("\n");
806
+ }
807
+ function isMasked(el) {
808
+ if (el.closest("[data-seaproof-mask]")) return true;
809
+ return el instanceof HTMLInputElement && el.type === "password";
810
+ }
811
+ function roleOf(el) {
812
+ const explicit = el.getAttribute("role");
813
+ if (explicit) return capitalize(explicit.replace(/item$/, " item"));
814
+ const tag = el.tagName.toLowerCase();
815
+ switch (tag) {
816
+ case "button":
817
+ case "summary":
818
+ return "Button";
819
+ case "a":
820
+ return "Link";
821
+ case "select":
822
+ return "List";
823
+ case "textarea":
824
+ return "Field";
825
+ case "img":
826
+ case "svg":
827
+ return "Image";
828
+ case "li":
829
+ return "List item";
830
+ case "tr":
831
+ return "Row";
832
+ case "td":
833
+ case "th":
834
+ return "Cell";
835
+ case "label":
836
+ return "Label";
837
+ case "p":
838
+ return "Text";
839
+ case "input": {
840
+ const type = el.type;
841
+ if (type === "checkbox") return "Checkbox";
842
+ if (type === "radio") return "Option";
843
+ if (type === "button" || type === "submit" || type === "reset") return "Button";
844
+ return "Field";
845
+ }
846
+ }
847
+ return /^h[1-6]$/.test(tag) ? "Heading" : null;
848
+ }
849
+ function nameOf(el) {
850
+ const aria = el.getAttribute("aria-label");
851
+ if (aria?.trim()) return clip(aria);
852
+ const labelledBy = el.getAttribute("aria-labelledby");
853
+ if (labelledBy) {
854
+ const text2 = labelledBy.split(/\s+/).map((id) => el.ownerDocument.getElementById(id)?.textContent ?? "").join(" ");
855
+ if (text2.trim()) return clip(text2);
856
+ }
857
+ if (el instanceof HTMLImageElement) return el.alt.trim() ? clip(el.alt) : null;
858
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) {
859
+ if (el instanceof HTMLInputElement && ["button", "submit", "reset"].includes(el.type) && el.value.trim()) return clip(el.value);
860
+ const label = el.labels?.[0]?.textContent;
861
+ if (label?.trim()) return clip(label);
862
+ const placeholder = el.getAttribute("placeholder");
863
+ return placeholder?.trim() ? clip(placeholder) : null;
864
+ }
865
+ const title = el.getAttribute("title");
866
+ if (title?.trim()) return clip(title);
867
+ const text = el.textContent ?? "";
868
+ return text.trim() ? clip(text) : null;
869
+ }
870
+ function clip(text) {
871
+ const flat = text.replace(/\s+/g, " ").trim();
872
+ return flat.length > MAX_NAME ? `${flat.slice(0, MAX_NAME - 1)}\u2026` : flat;
873
+ }
874
+ function capitalize(text) {
875
+ return text.charAt(0).toUpperCase() + text.slice(1);
876
+ }
877
+ var SIGNAL = "#e8590c";
878
+ async function drawPins(screenshot, pins, frame) {
879
+ const image = await loadImage(screenshot);
880
+ const canvas = document.createElement("canvas");
881
+ canvas.width = image.naturalWidth;
882
+ canvas.height = image.naturalHeight;
883
+ const ctx = canvas.getContext("2d");
884
+ if (!ctx) return screenshot;
885
+ ctx.drawImage(image, 0, 0);
886
+ const px = (x) => (x - frame.originX) * frame.scale;
887
+ const py = (y) => (y - frame.originY) * frame.scale;
888
+ const line = Math.max(3, Math.round(3 * frame.scale));
889
+ const radius = 12 * frame.scale;
890
+ for (const pin of pins) {
891
+ ctx.lineWidth = line;
892
+ ctx.strokeStyle = SIGNAL;
893
+ let cx = px(pin.x);
894
+ let cy = py(pin.y);
895
+ const box = pin.element?.box;
896
+ if (box) {
897
+ const pad = 4 * frame.scale;
898
+ ctx.beginPath();
899
+ ctx.roundRect(px(box.x) - pad, py(box.y) - pad, box.width * frame.scale + pad * 2, box.height * frame.scale + pad * 2, 8 * frame.scale);
900
+ ctx.stroke();
901
+ cx = px(box.x + box.width) + pad;
902
+ cy = py(box.y) - pad;
903
+ } else {
904
+ ctx.beginPath();
905
+ ctx.arc(cx, cy, radius * 1.6, 0, Math.PI * 2);
906
+ ctx.stroke();
907
+ }
908
+ ctx.beginPath();
909
+ ctx.arc(cx, cy, radius, 0, Math.PI * 2);
910
+ ctx.fillStyle = SIGNAL;
911
+ ctx.fill();
912
+ ctx.fillStyle = "#fff";
913
+ ctx.font = `700 ${Math.round(13 * frame.scale)}px Inter, system-ui, sans-serif`;
914
+ ctx.textAlign = "center";
915
+ ctx.textBaseline = "middle";
916
+ ctx.fillText(String(pin.number), cx, cy + frame.scale);
917
+ const note = pin.note?.trim();
918
+ if (note) {
919
+ const moved = pin.notePosition ? { x: px(pin.notePosition.x), y: py(pin.notePosition.y) } : null;
920
+ drawNote(ctx, note, cx, cy, radius, frame.scale, canvas.width, moved);
921
+ }
922
+ }
923
+ return new Promise((resolve) => canvas.toBlob((blob) => resolve(blob ?? screenshot), "image/png"));
924
+ }
925
+ var NOTE_INK = "#0a1f2e";
926
+ var NOTE_MAX_WIDTH = 240;
927
+ var NOTE_MAX_LINES = 4;
928
+ function drawNote(ctx, note, cx, cy, radius, scale, canvasWidth, moved) {
929
+ const size = Math.round(13 * scale);
930
+ const pad = 8 * scale;
931
+ const lineHeight = Math.round(size * 1.35);
932
+ ctx.font = `600 ${size}px Inter, system-ui, sans-serif`;
933
+ const lines = wrap(ctx, note, NOTE_MAX_WIDTH * scale);
934
+ const width = Math.max(...lines.map((l) => ctx.measureText(l).width)) + pad * 2;
935
+ const height = lines.length * lineHeight + pad * 2;
936
+ const gap = 6 * scale;
937
+ const right = cx + radius + gap;
938
+ const x = moved?.x ?? (right + width <= canvasWidth ? right : Math.max(0, cx - radius - gap - width));
939
+ const y = moved?.y ?? Math.max(0, cy - height / 2);
940
+ if (moved) {
941
+ const [lx, ly] = nearestPoint(cx, cy, x, y, width, height);
942
+ const length = Math.hypot(lx - cx, ly - cy) || 1;
943
+ ctx.beginPath();
944
+ ctx.moveTo(cx + (lx - cx) / length * radius, cy + (ly - cy) / length * radius);
945
+ ctx.lineTo(lx, ly);
946
+ ctx.lineWidth = Math.max(2, 2 * scale);
947
+ ctx.strokeStyle = NOTE_INK;
948
+ ctx.stroke();
949
+ }
950
+ ctx.beginPath();
951
+ ctx.roundRect(x, y, width, height, 8 * scale);
952
+ ctx.fillStyle = NOTE_INK;
953
+ ctx.fill();
954
+ ctx.fillStyle = "#fff";
955
+ ctx.textAlign = "left";
956
+ ctx.textBaseline = "top";
957
+ lines.forEach((line, i) => ctx.fillText(line, x + pad, y + pad + i * lineHeight));
958
+ }
959
+ function nearestPoint(px, py, x, y, width, height) {
960
+ return [Math.min(Math.max(px, x), x + width), Math.min(Math.max(py, y), y + height)];
961
+ }
962
+ function wrap(ctx, text, maxWidth) {
963
+ const lines = [];
964
+ let line = "";
965
+ for (const word of text.replace(/\s+/g, " ").split(" ")) {
966
+ const next = line ? `${line} ${word}` : word;
967
+ if (ctx.measureText(next).width <= maxWidth || !line) line = next;
968
+ else {
969
+ lines.push(line);
970
+ line = word;
971
+ }
972
+ }
973
+ if (line) lines.push(line);
974
+ if (lines.length <= NOTE_MAX_LINES) return lines;
975
+ const kept = lines.slice(0, NOTE_MAX_LINES);
976
+ kept[NOTE_MAX_LINES - 1] = `${kept[NOTE_MAX_LINES - 1]}\u2026`;
977
+ return kept;
978
+ }
979
+ function loadImage(blob) {
980
+ return new Promise((resolve, reject) => {
981
+ const url = URL.createObjectURL(blob);
982
+ const img = new Image();
983
+ img.onload = () => {
984
+ URL.revokeObjectURL(url);
985
+ resolve(img);
986
+ };
987
+ img.onerror = () => {
988
+ URL.revokeObjectURL(url);
989
+ reject(new Error("Seaproof: the screenshot could not be read."));
990
+ };
991
+ img.src = url;
992
+ });
993
+ }
994
+
573
995
  // src/screenshot.ts
574
996
  import { toBlob } from "html-to-image";
575
997
  function excludedFromScreenshot(node) {
@@ -578,15 +1000,20 @@ function excludedFromScreenshot(node) {
578
1000
  return node instanceof HTMLInputElement && node.type === "password";
579
1001
  }
580
1002
  async function captureScreenshot(element = document.body) {
1003
+ return (await captureScreenshotWithFrame(element)).file;
1004
+ }
1005
+ async function captureScreenshotWithFrame(element = document.body) {
1006
+ const pixelRatio = Math.min(window.devicePixelRatio || 1, 2);
1007
+ const rect = element.getBoundingClientRect();
581
1008
  const blob = await toBlob(element, {
582
1009
  cacheBust: true,
583
- pixelRatio: Math.min(window.devicePixelRatio || 1, 2),
1010
+ pixelRatio,
584
1011
  filter: (node) => !excludedFromScreenshot(node)
585
1012
  });
586
1013
  if (!blob) {
587
1014
  throw new Error("Seaproof: the screenshot could not be captured.");
588
1015
  }
589
- return blob;
1016
+ return { file: blob, frame: { originX: rect.left, originY: rect.top, scale: pixelRatio } };
590
1017
  }
591
1018
  export {
592
1019
  Diagnostics,
@@ -596,13 +1023,21 @@ export {
596
1023
  ScreenRecorder,
597
1024
  SeaproofError,
598
1025
  browserContext,
1026
+ canFastTrackType,
599
1027
  canRecordScreen,
600
1028
  captureScreenshot,
1029
+ captureScreenshotWithFrame,
601
1030
  createSeaproof,
602
1031
  defaultStorage,
1032
+ describeElement,
603
1033
  describeError,
1034
+ drawPins,
1035
+ elementAt,
604
1036
  excludedFromScreenshot,
605
1037
  installCapture,
1038
+ nearestPoint,
606
1039
  newConversationId,
1040
+ pinLabel,
1041
+ pinMessage,
607
1042
  redactUrl
608
1043
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seaproof/core",
3
- "version": "0.1.0-beta.1",
3
+ "version": "0.1.0-beta.2",
4
4
  "description": "Seaproof client for any web app: send bug reports, feedback and ideas with screenshots, diagnostics and screen recordings.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://seaproof.io",