-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathimporter.spec.ts
More file actions
1981 lines (1929 loc) · 62.5 KB
/
Copy pathimporter.spec.ts
File metadata and controls
1981 lines (1929 loc) · 62.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from "node:crypto";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { createServer, type ServerResponse } from "node:http";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
type BrowserContext,
test as base,
chromium,
expect,
type Page,
type TestInfo,
type Worker,
} from "@playwright/test";
import type { ImportContext } from "../src/importer/api";
import { parseInventory } from "../src/importer/inventory";
const extensionPath = path.resolve(
process.env.CAP_EXTENSION_TEST_DIR ??
path.join(path.dirname(fileURLToPath(import.meta.url)), "../dist"),
);
const authKey = "cap-extension-auth";
const settingsKey = "cap-extension-settings";
const userId = "11111111-1111-4111-8111-111111111111";
const otherUserId = "22222222-2222-4222-8222-222222222222";
const organizationId = "33333333-3333-4333-8333-333333333333";
const otherOrganizationId = "44444444-4444-4444-8444-444444444444";
const firstId = "0123456789abcdef0123456789abcdef";
const secondId = "fedcba9876543210fedcba9876543210";
const thirdId = "00112233445566778899aabbccddeeff";
const firstUrl = `https://www.loom.com/share/${firstId}`;
const secondUrl = `https://www.loom.com/share/${secondId}`;
const thirdUrl = `https://www.loom.com/share/${thirdId}`;
const mixedCsv = [
"Video Link,Video Name,Creator Email,Folder,review_decision,Duration",
`${firstUrl},Launch walkthrough,alex\\@example.test,Product / Guides,approved,02:10`,
",Unshared walkthrough,casey@example.test,Product / Private,,01:35",
`https://loom.com/embed/${firstId},Duplicate launch,alex@example.test,Product / Guides,approved,02:10`,
`${secondUrl},Needs editorial review,writer@example.test,Product / Guides,pending,03:20`,
`${thirdUrl},Release overview,pat@example.test,Engineering,approved,00:45`,
].join("\r\n");
const twoVideoCsv = [
"Video Link,Video Name,Creator Email",
`${firstUrl},First walkthrough,alex@example.test`,
`${secondUrl},Second walkthrough,casey@example.test`,
].join("\r\n");
const loomWorkspace = "Synthetic Loom workspace";
const nativeLoomCsv = [
"Video Link,Video Name,Creator Email,Workspace,Folder,Video Creation Date,Duration",
`${firstUrl},Native launch walkthrough,alex\\@example.test,Can View,Product / Guides,2026-07-15,02:10`,
",Unshared archive,casey@example.test,No Access,Private / Archive,2026-08-01,01:00",
`${secondUrl},Native release overview,pat@example.test,Can View,Engineering / Releases,2026-08-12,03:10`,
].join("\r\n");
const duplicateNativeLoomCsv = [
"Video Link,Video Name,Creator Email,Workspace,Folder,Video Creation Date,Duration",
`${firstUrl},Native launch walkthrough,alex\\@example.test,Can View,Product / Guides,2026-07-15,02:10`,
`${secondUrl},Native release overview,casey@example.test,Can View,Engineering / Releases,2026-08-12,03:10`,
`https://loom.com/embed/${firstId},Duplicate native launch,alex@example.test,Can View,Product / Guides,2026-07-15,02:10`,
].join("\r\n");
const cookieName = "cap-importer-fixture-session";
type ImportRequest = {
organizationId: string;
row: {
rowNumber: number;
loomUrl: string;
userEmail: string;
spaceName?: string;
};
};
type MigrationRequest = {
requestId: string;
expectedUserId: string;
expectedDefaultPublic: boolean;
organizationId: string;
source: {
workspace: string;
from: string;
to: string;
totalRows: number;
omittedRows: number;
};
rows: { rowNumber: number; loomUrl: string; userEmail: string }[];
};
const initialContext = (): ImportContext => ({
user: { id: userId, email: "alex@example.test" },
organizations: [
{ id: organizationId, name: "Importer fixture team", canImport: true },
],
activeOrganizationId: organizationId,
isPro: true,
defaultPublic: false,
maxRows: 500,
});
const sendJson = (response: ServerResponse, status: number, body: unknown) => {
response.writeHead(status, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Authorization, Content-Type",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Content-Type": "application/json",
});
response.end(status === 204 ? undefined : JSON.stringify(body));
};
const sendBatchReceipt = (
response: ServerResponse,
request: MigrationRequest,
) => {
sendJson(response, 200, {
operationId: "fixturebatch001",
dashboardPath: `/dashboard/import/loom/status?operationId=fixturebatch001&organizationId=${request.organizationId}`,
});
};
const createFixtureServer = async () => {
const state = {
context: initialContext(),
requests: [] as ImportRequest[],
contextRequests: 0,
holdRequests: false,
peakRequests: 0,
invalidBearerHeaders: 0,
cookieHeaders: 0,
batchRequests: [] as MigrationRequest[],
holdBatchRequests: false,
cookieSessionRequests: 0,
invalidCookieSessions: 0,
unexpectedAuthorizationHeaders: 0,
};
let authorizedCookie: string | null = null;
const authorizedTokens = new Set<string>();
const pending = new Map<number, ServerResponse>();
const pendingBatches = new Map<number, ServerResponse>();
const active = new Set<ServerResponse>();
const acceptCookieSession = (
headers: { authorization?: string; cookie?: string },
response: ServerResponse,
) => {
state.cookieSessionRequests++;
const authorized =
authorizedCookie !== null &&
headers.cookie
?.split(";")
.some((value) => value.trim() === authorizedCookie);
const hasAuthorization = headers.authorization !== undefined;
if (!authorized) state.invalidCookieSessions++;
if (hasAuthorization) state.unexpectedAuthorizationHeaders++;
if (!authorized || hasAuthorization) {
sendJson(response, 401, {
error: "The synthetic dashboard request requires its browser session.",
});
return false;
}
return true;
};
const server = createServer(async (request, response) => {
const url = new URL(request.url ?? "/", "http://127.0.0.1");
if (request.method === "OPTIONS") {
sendJson(response, 204, null);
return;
}
if (
url.pathname === "/api/extension/import-loom/batch" &&
request.method === "POST"
) {
if (!acceptCookieSession(request.headers, response)) return;
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
const body = JSON.parse(
Buffer.concat(chunks).toString("utf8"),
) as MigrationRequest;
const index = state.batchRequests.push(body) - 1;
response.once("close", () => pendingBatches.delete(index));
if (state.holdBatchRequests) pendingBatches.set(index, response);
else sendBatchReceipt(response, body);
return;
}
if (url.pathname === "/api/extension/import-loom") {
if (request.method === "GET" || request.method === "POST") {
if (authorizedCookie !== null) {
if (!acceptCookieSession(request.headers, response)) return;
} else {
const authorized =
typeof request.headers.authorization === "string" &&
authorizedTokens.has(request.headers.authorization);
const hasCookie = request.headers.cookie !== undefined;
if (!authorized) state.invalidBearerHeaders++;
if (hasCookie) state.cookieHeaders++;
if (!authorized || hasCookie) {
sendJson(response, 401, {
error: "The synthetic importer request has invalid credentials.",
});
return;
}
}
}
if (request.method === "GET") {
state.contextRequests++;
sendJson(response, 200, state.context);
return;
}
if (request.method === "POST") {
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
const body = JSON.parse(
Buffer.concat(chunks).toString("utf8"),
) as ImportRequest;
const index = state.requests.push(body) - 1;
active.add(response);
state.peakRequests = Math.max(state.peakRequests, active.size);
response.once("close", () => {
active.delete(response);
pending.delete(index);
});
if (state.holdRequests) pending.set(index, response);
else
sendJson(response, 200, {
success: true,
videoId: `fixture-video-${index + 1}`,
});
return;
}
}
if (url.pathname === "/api/extension/bootstrap") {
sendJson(response, 200, {
user: state.context.user,
organization: state.context.organizations[0],
plan: { isPro: state.context.isPro, maxRecordingSeconds: 600 },
});
return;
}
if (url.pathname.startsWith("/dashboard")) {
response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
response.end(
"<!doctype html><html><head><title>Cap fixture dashboard</title></head><body><h1>Fixture Cap dashboard</h1></body></html>",
);
return;
}
sendJson(response, 404, { error: "Unknown synthetic fixture endpoint" });
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("The importer fixture server did not get a local port.");
}
return {
origin: `http://127.0.0.1:${address.port}`,
state,
authorize: (token: string) => authorizedTokens.add(`Bearer ${token}`),
allowCookieSession: (value: string) => {
authorizedCookie = `${cookieName}=${value}`;
},
assertHeaders: () => {
expect(
state.invalidBearerHeaders,
"Importer GET and POST requests must use a seeded synthetic bearer token",
).toBe(0);
expect(
state.cookieHeaders,
"Importer GET and POST requests must omit Cookie headers",
).toBe(0);
expect(
state.invalidCookieSessions,
"Dashboard importer requests must use the seeded browser session",
).toBe(0);
expect(
state.unexpectedAuthorizationHeaders,
"Dashboard importer requests must not use extension bearer credentials",
).toBe(0);
},
respond: (index: number, body: unknown) => {
const response = pending.get(index);
if (!response) throw new Error(`No pending fixture request ${index}.`);
pending.delete(index);
sendJson(response, 200, body);
},
releaseBatch: (index: number) => {
const response = pendingBatches.get(index);
const request = state.batchRequests[index];
if (!response || !request)
throw new Error(`No pending fixture batch ${index}.`);
pendingBatches.delete(index);
sendBatchReceipt(response, request);
},
disconnect: async (index: number, headersReceived: Promise<unknown>) => {
const response = pending.get(index);
if (!response) throw new Error(`No pending fixture request ${index}.`);
pending.delete(index);
// Chromium retries a POST if its socket closes before response headers arrive.
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
"Content-Length": "128",
});
response.flushHeaders();
response.write('{"success":true,"videoId":"');
await headersReceived;
response.destroy();
},
close: () =>
new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
server.closeAllConnections();
}),
};
};
type FixtureServer = Awaited<ReturnType<typeof createFixtureServer>>;
const setConnection = async (
worker: Worker,
server: FixtureServer,
token: string,
signedIn = true,
) => {
if (signedIn) server.authorize(token);
await worker.evaluate(
async (values) => {
await chrome.storage.local.set({
[values.settingsKey]: {
apiBaseUrl: values.apiBaseUrl,
capture: {
recordingMode: "fullscreen",
camera: null,
microphone: null,
},
webcam: {
enabled: false,
deviceId: null,
position: "bottom-left",
size: 230,
shape: "round",
mirror: false,
},
microphone: { enabled: false, deviceId: null },
systemAudio: { enabled: false },
sounds: { enabled: false },
countdown: { enabled: false, seconds: 3 },
microphoneWarning: { enabled: false },
},
[values.authKey]: values.signedIn
? { authApiKey: values.token, userId: values.userId }
: null,
});
},
{
settingsKey,
authKey,
apiBaseUrl: server.origin,
token,
signedIn,
userId: server.state.context.user.id,
},
);
};
type Harness = {
context: BrowserContext;
page: Page;
worker: Worker;
server: FixtureServer;
token: string;
url: string;
open: (signedIn?: boolean) => Promise<void>;
};
const test = base.extend<{ harness: Harness }>({
harness: async ({ browserName }, use) => {
if (browserName !== "chromium")
throw new Error("The importer extension tests require Chromium.");
const profile = await mkdtemp(path.join(tmpdir(), "cap-importer-e2e-"));
const server = await createFixtureServer();
let context: BrowserContext | undefined;
try {
context = await chromium.launchPersistentContext(profile, {
channel: "chromium",
headless: true,
acceptDownloads: true,
viewport: { width: 1440, height: 1100 },
args: [
"--no-proxy-server",
// Extension-created tabs can navigate before Playwright installs their route.
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1, EXCLUDE localhost",
`--disable-extensions-except=${extensionPath}`,
`--load-extension=${extensionPath}`,
],
});
await context.route(/^https?:\/\//, async (route) => {
if (new URL(route.request().url()).hostname === "127.0.0.1")
await route.continue();
else await route.abort("blockedbyclient");
});
const worker =
context
.serviceWorkers()
.find((item) => item.url().includes("assets/service-worker.js")) ??
(await context.waitForEvent("serviceworker", (item) =>
item.url().includes("assets/service-worker.js"),
));
await worker.evaluate(async () => chrome.storage.local.clear());
const page = await context.newPage();
const url = `chrome-extension://${new URL(worker.url()).host}/import.html`;
const token = randomUUID();
await use({
context,
page,
worker,
server,
token,
url,
open: async (signedIn = true) => {
await setConnection(worker, server, token, signedIn);
await page.goto(url);
await expect(
page.getByRole("heading", { name: "Drop your export here" }),
).toBeVisible();
if (signedIn)
await expect
.poll(() => server.state.contextRequests)
.toBeGreaterThan(0);
},
});
server.assertHeaders();
} finally {
try {
await context?.close();
} finally {
await server.close();
await rm(profile, { recursive: true, force: true });
}
}
},
});
const uploadInventory = async (
page: Page,
content = mixedCsv,
name = "synthetic-loom.csv",
) => {
await page.getByLabel("Choose inventory file").setInputFiles({
name,
mimeType: name.endsWith(".json")
? "application/json"
: name.endsWith(".tsv")
? "text/tab-separated-values"
: "text/csv",
buffer: Buffer.from(content),
});
await expect(page.getByText(name, { exact: true })).toBeVisible();
await expect(
page.getByRole("region", { name: "Video inventory" }),
).toBeVisible();
};
const recordRow = (page: Page, record: number) =>
page.getByRole("row").filter({
has: page.getByRole("checkbox", {
name: `Select record ${record}`,
exact: true,
}),
});
const downloadCsv = async (
page: Page,
testInfo: TestInfo,
label: string,
filename: string,
) => {
const pending = page.waitForEvent("download");
await page.getByRole("button", { name: label, exact: true }).click();
const download = await pending;
expect(download.suggestedFilename()).toBe(filename);
const destination = testInfo.outputPath(filename);
await download.saveAs(destination);
expect(await download.failure()).toBeNull();
return readFile(destination, "utf8");
};
const confirmImport = async (page: Page, count: number) => {
await page
.getByRole("button", {
name: `Import ${count} ${count === 1 ? "video" : "videos"}`,
exact: true,
})
.click();
const dialog = page.getByRole("dialog", {
name: "Ready to bring these over?",
});
const start = dialog.getByRole("button", {
name: `Start ${count} ${count === 1 ? "import" : "imports"}`,
exact: true,
});
await expect(start).toBeDisabled();
await dialog
.getByRole("checkbox", {
name: "I’ve reviewed the selected videos, owners, Spaces and visibility.",
})
.check();
await start.click();
};
const readSaved = (page: Page, key: "draft" | "run") =>
page.evaluate(
(key) =>
new Promise<unknown>((resolve, reject) => {
const opened = indexedDB.open("cap-loom-importer", 1);
opened.onerror = () => reject(opened.error);
opened.onsuccess = () => {
const database = opened.result;
const transaction = database.transaction("inventory", "readonly");
const request = transaction.objectStore("inventory").get(key);
transaction.oncomplete = () => {
database.close();
resolve(request.result ?? null);
};
transaction.onabort = () => {
database.close();
reject(transaction.error);
};
};
}),
key,
);
const routeNativeLoom = async (
context: BrowserContext,
options: {
csv?: string;
totalRows?: number;
workspaceAfterDownload?: string;
from?: string;
to?: string;
} = {},
) => {
const state = {
requests: 0,
authorizationHeaders: 0,
cookieHeaders: 0,
};
const csv = JSON.stringify(options.csv ?? nativeLoomCsv).replaceAll(
"<",
"\\u003c",
);
const body = `<!doctype html>
<html><head><meta charset="utf-8"><title>Synthetic Loom workspace export</title></head>
<body><header><button id="workspace-selector" type="button">${loomWorkspace}</button>
<a id="loom-space-nav" href="/spaces/fixture-product-guides">Product guides</a></header>
<main><nav aria-label="Breadcrumb"><span id="workspace-breadcrumb">${loomWorkspace}</span><span> / </span></nav>
<h1>Workspace Settings Data</h1>
<section aria-label="Engagement report">
<h2>Export engagement insights</h2>
<label for="from">Start date</label><input id="from" type="date" value="${options.from ?? "2026-08-01"}">
<label for="to">End date</label><input id="to" type="date" value="${options.to ?? "2026-08-31"}">
<p>Export all ${options.totalRows ?? 3} videos created in this date range.</p>
<table><thead><tr><th>Workspace</th><th>Video Name</th></tr></thead>
<tbody><tr><td>Can View</td><td>Native launch walkthrough</td></tr></tbody></table>
<button id="download-csv" type="button">Download CSV</button>
</section></main>
<script>
window.__nativeLoomFixture = {
exports: 0,
createObjectURL: URL.createObjectURL,
anchorClick: HTMLAnchorElement.prototype.click
};
document.getElementById("download-csv").addEventListener("click", () => {
window.__nativeLoomFixture.exports += 1;
const workspaceAfterDownload = ${JSON.stringify(options.workspaceAfterDownload ?? null)};
if (workspaceAfterDownload) {
document.getElementById("workspace-selector").textContent = workspaceAfterDownload;
document.getElementById("workspace-breadcrumb").textContent = workspaceAfterDownload;
}
const url = URL.createObjectURL(new Blob([${csv}], {type: "text/csv;charset=utf-8"}));
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = "synthetic-native-loom.csv";
document.body.append(anchor);
anchor.click();
anchor.remove();
});
</script></body></html>`;
await context.route("https://www.loom.com/**", async (route) => {
state.requests++;
const headers = await route.request().allHeaders();
if (headers.authorization) state.authorizationHeaders++;
if (headers.cookie) state.cookieHeaders++;
await route.fulfill({
status: 200,
contentType: "text/html; charset=utf-8",
body,
});
});
const page = await context.newPage();
await page.goto("https://www.loom.com/settings/workspace#data");
await expect(
page.getByRole("heading", {
name: "Export engagement insights",
exact: true,
}),
).toBeVisible();
return state;
};
const readNativeCaptureState = (page: Page) =>
page.evaluate(() => {
const fixture = (
window as Window & {
__nativeLoomFixture?: {
exports: number;
createObjectURL: typeof URL.createObjectURL;
anchorClick: typeof HTMLAnchorElement.prototype.click;
};
}
).__nativeLoomFixture;
if (!fixture) throw new Error("The synthetic Loom fixture did not load.");
return {
exports: fixture.exports,
createObjectURLRestored: URL.createObjectURL === fixture.createObjectURL,
anchorClickRestored:
HTMLAnchorElement.prototype.click === fixture.anchorClick,
};
});
const openMigration = async (harness: Harness) => {
await setConnection(harness.worker, harness.server, harness.token, false);
await harness.page.goto(new URL("migrate.html", harness.url).toString());
await expect(
harness.page.getByRole("heading", {
name: "Move your Loom library to Cap",
exact: true,
}),
).toBeVisible();
};
const connectNativeLoom = async (harness: Harness) => {
const loom = harness.context
.pages()
.find(
(page) => page.url() === "https://www.loom.com/settings/workspace#data",
);
if (!loom) throw new Error("The routed synthetic Loom tab was not opened.");
await loom.reload();
await harness.page
.getByRole("button", { name: "Connect Loom", exact: true })
.click();
await expect(loom).toHaveURL("https://www.loom.com/settings/workspace#data");
await expect(
harness.page.getByText(loomWorkspace, { exact: true }),
).toBeVisible();
await expect(
harness.page.getByRole("button", { name: "Next", exact: true }),
).toBeEnabled();
return loom;
};
const prepareNativeLoom = async (harness: Harness) => {
const loom = await connectNativeLoom(harness);
await harness.page.getByRole("button", { name: "Next", exact: true }).click();
await expect(
harness.page.getByRole("heading", {
name: "Your CSV is ready",
exact: true,
}),
).toBeVisible();
return loom;
};
const expandMigrationPreview = async (page: Page) => {
await page
.getByText("Preview videos and full report", { exact: true })
.click();
await expect(
page.getByRole("region", { name: "Video inventory" }),
).toBeVisible();
};
const seedCapCookieSession = async (harness: Harness) => {
const cookie = randomUUID();
harness.server.allowCookieSession(cookie);
await harness.context.addCookies([
{
name: cookieName,
value: cookie,
url: harness.server.origin,
httpOnly: true,
sameSite: "Lax",
},
]);
};
const connectCookieCap = async (harness: Harness) => {
await seedCapCookieSession(harness);
const existing = harness.context
.pages()
.find((page) =>
page.url().startsWith(`${harness.server.origin}/dashboard`),
);
const opened = existing
? Promise.resolve(existing)
: harness.context.waitForEvent("page");
await harness.page
.getByRole("button", { name: "Import to Cap", exact: true })
.click();
const cap = await opened;
await expect(cap).toHaveURL(`${harness.server.origin}/dashboard/caps`);
await expect(
harness.page.getByRole("heading", { name: "Import to Cap", exact: true }),
).toBeVisible();
await expect(
harness.page
.getByRole("region", {
name: "Confirm your Cap destination",
exact: true,
})
.getByText("alex@example.test", { exact: true }),
).toBeVisible();
await expect(
harness.page.getByRole("combobox", {
name: "Cap organization",
exact: true,
}),
).toHaveValue(organizationId);
return cap;
};
test("signed-out review retains attention records and downloads only the selected import rows", async ({
harness,
}, testInfo) => {
const { page, server } = harness;
await harness.open(false);
await page.evaluate(() => window.scrollTo(0, 0));
await page.screenshot({
path: testInfo.outputPath("importer-empty.png"),
fullPage: true,
animations: "disabled",
});
await uploadInventory(page);
await expect(
page.getByText("5 source records · saved locally"),
).toBeVisible();
await expect(
page.getByRole("checkbox", { name: "Select record 1", exact: true }),
).toBeChecked();
await expect(
page.getByRole("checkbox", { name: "Select record 5", exact: true }),
).toBeChecked();
for (const record of [2, 3, 4]) {
await expect(
page.getByRole("checkbox", {
name: `Select record ${record}`,
exact: true,
}),
).not.toBeChecked();
}
await expect(
page.getByRole("checkbox", { name: "Select record 2", exact: true }),
).toBeDisabled();
await expect(
page.getByRole("checkbox", { name: "Select record 3", exact: true }),
).toBeDisabled();
await expect(recordRow(page, 2)).toContainText("Missing link");
await expect(recordRow(page, 3)).toContainText("Duplicate");
await expect(recordRow(page, 4)).toContainText("Needs review");
await page.getByRole("button", { name: "Select ready", exact: true }).click();
await expect(
page.getByRole("checkbox", { name: "Select record 4", exact: true }),
).not.toBeChecked();
await expect(
page.getByRole("button", { name: "Sign in to Cap", exact: true }),
).toBeVisible();
await page.evaluate(() => window.scrollTo(0, 0));
await page.screenshot({
path: testInfo.outputPath("importer-inventory.png"),
fullPage: true,
animations: "disabled",
});
const selected = parseInventory(
await downloadCsv(
page,
testInfo,
"Download import CSV",
"cap-loom-import.csv",
),
"selected.csv",
);
expect(selected.headers).toEqual([
"loom_video_url",
"user_email",
"space_name",
]);
expect(selected.records).toEqual([
[firstUrl, "alex@example.test", ""],
[thirdUrl, "pat@example.test", ""],
]);
const report = parseInventory(
await downloadCsv(
page,
testInfo,
"Download full report",
"cap-loom-inventory-report.csv",
),
"report.csv",
);
expect(report.records).toHaveLength(5);
expect(
report.records.map(
(record) => record[report.headers.indexOf("source_record_number")],
),
).toEqual(["1", "2", "3", "4", "5"]);
expect(
report.records.map(
(record) => record[report.headers.indexOf("validation_status")],
),
).toEqual(["ready", "missing-link", "duplicate", "review-required", "ready"]);
expect(report.records[1].slice(0, 4)).toEqual([
"",
"Unshared walkthrough",
"casey@example.test",
"Product / Private",
]);
expect(server.state.requests).toEqual([]);
expect(server.state.contextRequests).toBe(0);
await page.setViewportSize({ width: 480, height: 960 });
await page.evaluate(() => window.scrollTo(0, 0));
await page.screenshot({
path: testInfo.outputPath("importer-inventory-narrow.png"),
fullPage: true,
animations: "disabled",
});
});
test("the signed-out popup opens account migration and keeps the manual CSV tool available", async ({
harness,
}) => {
const { page, context, server, worker, token } = harness;
await setConnection(worker, server, token, false);
await page.goto(new URL("popup.html", harness.url).toString());
const opened = context.waitForEvent("page");
await page
.getByRole("button", { name: "Import from Loom", exact: true })
.click();
const importer = await opened;
await expect(importer).toHaveURL(
new URL("migrate.html", harness.url).toString(),
);
await expect(
importer.getByRole("heading", {
name: "Move your Loom library to Cap",
exact: true,
}),
).toBeVisible();
await expect(
importer.getByRole("button", { name: "Connect Loom", exact: true }),
).toBeVisible();
await importer
.getByRole("link", { name: "Open the CSV file tool", exact: true })
.click();
await expect(importer).toHaveURL(harness.url);
await uploadInventory(importer, twoVideoCsv);
await expect(
importer.getByRole("button", { name: "Sign in to Cap", exact: true }),
).toBeVisible();
expect(server.state.requests).toEqual([]);
expect(server.state.contextRequests).toBe(0);
});
test("empty and malformed files show errors, then a valid JSON inventory can be reviewed", async ({
harness,
}) => {
const { page, server } = harness;
await harness.open(false);
await page.getByLabel("Choose inventory file").setInputFiles({
name: "empty.csv",
mimeType: "text/csv",
buffer: Buffer.alloc(0),
});
await expect(page.getByRole("alert")).toContainText("This file is empty.");
await expect(
page.getByRole("heading", { name: "Drop your export here", exact: true }),
).toBeVisible();
await page.getByLabel("Choose inventory file").setInputFiles({
name: "malformed.json",
mimeType: "application/json",
buffer: Buffer.from('{"videos":['),
});
await expect(page.getByRole("alert")).toContainText("not valid JSON");
await uploadInventory(
page,
JSON.stringify({
videos: [
{
loom_video_url: firstUrl,
title: "JSON walkthrough",
user_email: "alex@example.test",
review_decision: "",
},
],
}),
"synthetic-loom.json",
);
await expect(page.getByRole("alert")).toHaveCount(0);
await expect(recordRow(page, 1)).toContainText("JSON walkthrough");
await expect(recordRow(page, 1)).toContainText("Needs review");
await page.getByRole("button", { name: "Select ready", exact: true }).click();
await expect(
page.getByRole("checkbox", { name: "Select record 1", exact: true }),
).not.toBeChecked();
await expect(
page.getByRole("button", { name: "Download import CSV", exact: true }),
).toBeDisabled();
await page
.getByRole("checkbox", { name: "Select record 1", exact: true })
.check();
await expect(
page.getByRole("checkbox", { name: "Select record 1", exact: true }),
).toBeChecked();
expect(server.state.requests).toEqual([]);
});
test("owner overrides keep provenance and folder paths map only to an explicitly chosen flat Space", async ({
harness,
}, testInfo) => {
const { page } = harness;
await harness.open(false);
await uploadInventory(
page,
`Video Link\tVideo Name\tCreator\tFolder\n${firstUrl}\tTraining walkthrough\talex\\@example.test\tTeams / Enablement\n${secondUrl}\tSupport walkthrough\tcasey@example.test\tTeams / Support`,
"synthetic-loom.tsv",
);
await expect(
page.getByRole("combobox", { name: "Destination Space", exact: true }),
).toHaveValue("none");
await expect(recordRow(page, 1)).toContainText("No Space");
await page
.getByRole("combobox", { name: "Cap video owner", exact: true })
.selectOption("override");
await page
.getByLabel("Owner email", { exact: true })
.fill("import-owner@example.test");
await expect(recordRow(page, 1)).toContainText("From alex@example.test");
await page
.getByRole("combobox", { name: "Destination Space", exact: true })
.selectOption("column");
await expect(
page.getByRole("combobox", { name: "Space column", exact: true }),
).toHaveValue("-1");
await page
.getByRole("combobox", { name: "Space column", exact: true })
.selectOption({ label: "Folder" });
await expect(recordRow(page, 1).locator("td").nth(3)).toHaveText(
"Teams / Enablement",
);
await expect(
page.getByText("Named Spaces are reused or created as flat Spaces.", {
exact: false,
}),
).toBeVisible();
await page
.getByRole("button", { name: "Source details for record 1", exact: true })
.click();
await expect(
page.getByText("alex\\@example.test", { exact: true }),
).toBeVisible();
const csv = parseInventory(
await downloadCsv(
page,
testInfo,
"Download import CSV",
"cap-loom-import.csv",
),
"selected.csv",
);
expect(csv.records).toEqual([
[firstUrl, "import-owner@example.test", "Teams / Enablement"],
[secondUrl, "import-owner@example.test", "Teams / Support"],
]);
});
test("Pro and organization-role gates disable submission without blocking local review", async ({
harness,
}) => {
const { page, server } = harness;
server.state.context.isPro = false;
server.state.context.organizations = [
{ id: organizationId, name: "Read-only fixture team", canImport: false },
{ id: otherOrganizationId, name: "Managed fixture team", canImport: true },
];
await harness.open();