@stablyai/playwright-test 2.1.2 → 2.1.3-rc.1

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.mjs CHANGED
@@ -2,9 +2,9 @@ import { dirname } from 'path';
2
2
  import { fileURLToPath } from 'url';
3
3
  import { test as test$2, expect as expect$1, defineConfig as defineConfig$1 } from '@playwright/test';
4
4
  export * from '@playwright/test';
5
- import { augmentPage, augmentBrowserContext, augmentBrowser, stablyPlaywrightMatchers } from '@stablyai/playwright-base';
5
+ import { requireApiKey, augmentPage, augmentBrowserContext, augmentBrowser, stablyPlaywrightMatchers } from '@stablyai/playwright-base';
6
6
  export { Agent, setApiKey } from '@stablyai/playwright-base';
7
- export { S as stablyReporter } from './index-FxXA-kJ_.mjs';
7
+ export { r as stablyReporter } from './index-BlR0M2If.mjs';
8
8
  import 'node:buffer';
9
9
  import 'node:path';
10
10
  import 'node:child_process';
@@ -19,6 +19,10 @@ import 'stream';
19
19
  import 'node:util';
20
20
  import 'node:readline';
21
21
  import 'node:stream';
22
+ import 'module';
23
+ import 'node:module';
24
+ import 'node:worker_threads';
25
+ import 'node:crypto';
22
26
  import 'util';
23
27
  import 'events';
24
28
  import 'https';
@@ -30,6 +34,946 @@ import 'zlib';
30
34
  import 'buffer';
31
35
  import 'os';
32
36
 
37
+ var jsonBodySerializer = {
38
+ bodySerializer: (body) => JSON.stringify(
39
+ body,
40
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
41
+ )
42
+ };
43
+ var createSseClient = ({
44
+ onRequest,
45
+ onSseError,
46
+ onSseEvent,
47
+ responseTransformer,
48
+ responseValidator,
49
+ sseDefaultRetryDelay,
50
+ sseMaxRetryAttempts,
51
+ sseMaxRetryDelay,
52
+ sseSleepFn,
53
+ url,
54
+ ...options
55
+ }) => {
56
+ let lastEventId;
57
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
58
+ const createStream = async function* () {
59
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
60
+ let attempt = 0;
61
+ const signal = options.signal ?? new AbortController().signal;
62
+ while (true) {
63
+ if (signal.aborted) break;
64
+ attempt++;
65
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
66
+ if (lastEventId !== void 0) {
67
+ headers.set("Last-Event-ID", lastEventId);
68
+ }
69
+ try {
70
+ const requestInit = {
71
+ redirect: "follow",
72
+ ...options,
73
+ body: options.serializedBody,
74
+ headers,
75
+ signal
76
+ };
77
+ let request = new Request(url, requestInit);
78
+ if (onRequest) {
79
+ request = await onRequest(url, requestInit);
80
+ }
81
+ const _fetch = options.fetch ?? globalThis.fetch;
82
+ const response = await _fetch(request);
83
+ if (!response.ok)
84
+ throw new Error(
85
+ `SSE failed: ${response.status} ${response.statusText}`
86
+ );
87
+ if (!response.body) throw new Error("No body in SSE response");
88
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
89
+ let buffer = "";
90
+ const abortHandler = () => {
91
+ try {
92
+ reader.cancel();
93
+ } catch {
94
+ }
95
+ };
96
+ signal.addEventListener("abort", abortHandler);
97
+ try {
98
+ while (true) {
99
+ const { done, value } = await reader.read();
100
+ if (done) break;
101
+ buffer += value;
102
+ const chunks = buffer.split("\n\n");
103
+ buffer = chunks.pop() ?? "";
104
+ for (const chunk of chunks) {
105
+ const lines = chunk.split("\n");
106
+ const dataLines = [];
107
+ let eventName;
108
+ for (const line of lines) {
109
+ if (line.startsWith("data:")) {
110
+ dataLines.push(line.replace(/^data:\s*/, ""));
111
+ } else if (line.startsWith("event:")) {
112
+ eventName = line.replace(/^event:\s*/, "");
113
+ } else if (line.startsWith("id:")) {
114
+ lastEventId = line.replace(/^id:\s*/, "");
115
+ } else if (line.startsWith("retry:")) {
116
+ const parsed = Number.parseInt(
117
+ line.replace(/^retry:\s*/, ""),
118
+ 10
119
+ );
120
+ if (!Number.isNaN(parsed)) {
121
+ retryDelay = parsed;
122
+ }
123
+ }
124
+ }
125
+ let data;
126
+ let parsedJson = false;
127
+ if (dataLines.length) {
128
+ const rawData = dataLines.join("\n");
129
+ try {
130
+ data = JSON.parse(rawData);
131
+ parsedJson = true;
132
+ } catch {
133
+ data = rawData;
134
+ }
135
+ }
136
+ if (parsedJson) {
137
+ if (responseValidator) {
138
+ await responseValidator(data);
139
+ }
140
+ if (responseTransformer) {
141
+ data = await responseTransformer(data);
142
+ }
143
+ }
144
+ onSseEvent?.({
145
+ data,
146
+ event: eventName,
147
+ id: lastEventId,
148
+ retry: retryDelay
149
+ });
150
+ if (dataLines.length) {
151
+ yield data;
152
+ }
153
+ }
154
+ }
155
+ } finally {
156
+ signal.removeEventListener("abort", abortHandler);
157
+ reader.releaseLock();
158
+ }
159
+ break;
160
+ } catch (error) {
161
+ onSseError?.(error);
162
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
163
+ break;
164
+ }
165
+ const backoff = Math.min(
166
+ retryDelay * 2 ** (attempt - 1),
167
+ sseMaxRetryDelay ?? 3e4
168
+ );
169
+ await sleep(backoff);
170
+ }
171
+ }
172
+ };
173
+ const stream = createStream();
174
+ return { stream };
175
+ };
176
+ var separatorArrayExplode = (style) => {
177
+ switch (style) {
178
+ case "label":
179
+ return ".";
180
+ case "matrix":
181
+ return ";";
182
+ case "simple":
183
+ return ",";
184
+ default:
185
+ return "&";
186
+ }
187
+ };
188
+ var separatorArrayNoExplode = (style) => {
189
+ switch (style) {
190
+ case "form":
191
+ return ",";
192
+ case "pipeDelimited":
193
+ return "|";
194
+ case "spaceDelimited":
195
+ return "%20";
196
+ default:
197
+ return ",";
198
+ }
199
+ };
200
+ var separatorObjectExplode = (style) => {
201
+ switch (style) {
202
+ case "label":
203
+ return ".";
204
+ case "matrix":
205
+ return ";";
206
+ case "simple":
207
+ return ",";
208
+ default:
209
+ return "&";
210
+ }
211
+ };
212
+ var serializeArrayParam = ({
213
+ allowReserved,
214
+ explode,
215
+ name,
216
+ style,
217
+ value
218
+ }) => {
219
+ if (!explode) {
220
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
221
+ switch (style) {
222
+ case "label":
223
+ return `.${joinedValues2}`;
224
+ case "matrix":
225
+ return `;${name}=${joinedValues2}`;
226
+ case "simple":
227
+ return joinedValues2;
228
+ default:
229
+ return `${name}=${joinedValues2}`;
230
+ }
231
+ }
232
+ const separator = separatorArrayExplode(style);
233
+ const joinedValues = value.map((v) => {
234
+ if (style === "label" || style === "simple") {
235
+ return allowReserved ? v : encodeURIComponent(v);
236
+ }
237
+ return serializePrimitiveParam({
238
+ allowReserved,
239
+ name,
240
+ value: v
241
+ });
242
+ }).join(separator);
243
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
244
+ };
245
+ var serializePrimitiveParam = ({
246
+ allowReserved,
247
+ name,
248
+ value
249
+ }) => {
250
+ if (value === void 0 || value === null) {
251
+ return "";
252
+ }
253
+ if (typeof value === "object") {
254
+ throw new Error(
255
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
256
+ );
257
+ }
258
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
259
+ };
260
+ var serializeObjectParam = ({
261
+ allowReserved,
262
+ explode,
263
+ name,
264
+ style,
265
+ value,
266
+ valueOnly
267
+ }) => {
268
+ if (value instanceof Date) {
269
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
270
+ }
271
+ if (style !== "deepObject" && !explode) {
272
+ let values = [];
273
+ Object.entries(value).forEach(([key, v]) => {
274
+ values = [
275
+ ...values,
276
+ key,
277
+ allowReserved ? v : encodeURIComponent(v)
278
+ ];
279
+ });
280
+ const joinedValues2 = values.join(",");
281
+ switch (style) {
282
+ case "form":
283
+ return `${name}=${joinedValues2}`;
284
+ case "label":
285
+ return `.${joinedValues2}`;
286
+ case "matrix":
287
+ return `;${name}=${joinedValues2}`;
288
+ default:
289
+ return joinedValues2;
290
+ }
291
+ }
292
+ const separator = separatorObjectExplode(style);
293
+ const joinedValues = Object.entries(value).map(
294
+ ([key, v]) => serializePrimitiveParam({
295
+ allowReserved,
296
+ name: style === "deepObject" ? `${name}[${key}]` : key,
297
+ value: v
298
+ })
299
+ ).join(separator);
300
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
301
+ };
302
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
303
+ var defaultPathSerializer = ({ path, url: _url }) => {
304
+ let url = _url;
305
+ const matches = _url.match(PATH_PARAM_RE);
306
+ if (matches) {
307
+ for (const match of matches) {
308
+ let explode = false;
309
+ let name = match.substring(1, match.length - 1);
310
+ let style = "simple";
311
+ if (name.endsWith("*")) {
312
+ explode = true;
313
+ name = name.substring(0, name.length - 1);
314
+ }
315
+ if (name.startsWith(".")) {
316
+ name = name.substring(1);
317
+ style = "label";
318
+ } else if (name.startsWith(";")) {
319
+ name = name.substring(1);
320
+ style = "matrix";
321
+ }
322
+ const value = path[name];
323
+ if (value === void 0 || value === null) {
324
+ continue;
325
+ }
326
+ if (Array.isArray(value)) {
327
+ url = url.replace(
328
+ match,
329
+ serializeArrayParam({ explode, name, style, value })
330
+ );
331
+ continue;
332
+ }
333
+ if (typeof value === "object") {
334
+ url = url.replace(
335
+ match,
336
+ serializeObjectParam({
337
+ explode,
338
+ name,
339
+ style,
340
+ value,
341
+ valueOnly: true
342
+ })
343
+ );
344
+ continue;
345
+ }
346
+ if (style === "matrix") {
347
+ url = url.replace(
348
+ match,
349
+ `;${serializePrimitiveParam({
350
+ name,
351
+ value
352
+ })}`
353
+ );
354
+ continue;
355
+ }
356
+ const replaceValue = encodeURIComponent(
357
+ style === "label" ? `.${value}` : value
358
+ );
359
+ url = url.replace(match, replaceValue);
360
+ }
361
+ }
362
+ return url;
363
+ };
364
+ var getUrl = ({
365
+ baseUrl,
366
+ path,
367
+ query,
368
+ querySerializer,
369
+ url: _url
370
+ }) => {
371
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
372
+ let url = (baseUrl ?? "") + pathUrl;
373
+ if (path) {
374
+ url = defaultPathSerializer({ path, url });
375
+ }
376
+ let search = query ? querySerializer(query) : "";
377
+ if (search.startsWith("?")) {
378
+ search = search.substring(1);
379
+ }
380
+ if (search) {
381
+ url += `?${search}`;
382
+ }
383
+ return url;
384
+ };
385
+ function getValidRequestBody(options) {
386
+ const hasBody = options.body !== void 0;
387
+ const isSerializedBody = hasBody && options.bodySerializer;
388
+ if (isSerializedBody) {
389
+ if ("serializedBody" in options) {
390
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
391
+ return hasSerializedBody ? options.serializedBody : null;
392
+ }
393
+ return options.body !== "" ? options.body : null;
394
+ }
395
+ if (hasBody) {
396
+ return options.body;
397
+ }
398
+ return void 0;
399
+ }
400
+ var getAuthToken = async (auth, callback) => {
401
+ const token = typeof callback === "function" ? await callback(auth) : callback;
402
+ if (!token) {
403
+ return;
404
+ }
405
+ if (auth.scheme === "bearer") {
406
+ return `Bearer ${token}`;
407
+ }
408
+ if (auth.scheme === "basic") {
409
+ return `Basic ${btoa(token)}`;
410
+ }
411
+ return token;
412
+ };
413
+ var createQuerySerializer = ({
414
+ parameters = {},
415
+ ...args
416
+ } = {}) => {
417
+ const querySerializer = (queryParams) => {
418
+ const search = [];
419
+ if (queryParams && typeof queryParams === "object") {
420
+ for (const name in queryParams) {
421
+ const value = queryParams[name];
422
+ if (value === void 0 || value === null) {
423
+ continue;
424
+ }
425
+ const options = parameters[name] || args;
426
+ if (Array.isArray(value)) {
427
+ const serializedArray = serializeArrayParam({
428
+ allowReserved: options.allowReserved,
429
+ explode: true,
430
+ name,
431
+ style: "form",
432
+ value,
433
+ ...options.array
434
+ });
435
+ if (serializedArray) search.push(serializedArray);
436
+ } else if (typeof value === "object") {
437
+ const serializedObject = serializeObjectParam({
438
+ allowReserved: options.allowReserved,
439
+ explode: true,
440
+ name,
441
+ style: "deepObject",
442
+ value,
443
+ ...options.object
444
+ });
445
+ if (serializedObject) search.push(serializedObject);
446
+ } else {
447
+ const serializedPrimitive = serializePrimitiveParam({
448
+ allowReserved: options.allowReserved,
449
+ name,
450
+ value
451
+ });
452
+ if (serializedPrimitive) search.push(serializedPrimitive);
453
+ }
454
+ }
455
+ }
456
+ return search.join("&");
457
+ };
458
+ return querySerializer;
459
+ };
460
+ var getParseAs = (contentType) => {
461
+ if (!contentType) {
462
+ return "stream";
463
+ }
464
+ const cleanContent = contentType.split(";")[0]?.trim();
465
+ if (!cleanContent) {
466
+ return;
467
+ }
468
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
469
+ return "json";
470
+ }
471
+ if (cleanContent === "multipart/form-data") {
472
+ return "formData";
473
+ }
474
+ if (["application/", "audio/", "image/", "video/"].some(
475
+ (type) => cleanContent.startsWith(type)
476
+ )) {
477
+ return "blob";
478
+ }
479
+ if (cleanContent.startsWith("text/")) {
480
+ return "text";
481
+ }
482
+ return;
483
+ };
484
+ var checkForExistence = (options, name) => {
485
+ if (!name) {
486
+ return false;
487
+ }
488
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
489
+ return true;
490
+ }
491
+ return false;
492
+ };
493
+ var setAuthParams = async ({
494
+ security,
495
+ ...options
496
+ }) => {
497
+ for (const auth of security) {
498
+ if (checkForExistence(options, auth.name)) {
499
+ continue;
500
+ }
501
+ const token = await getAuthToken(auth, options.auth);
502
+ if (!token) {
503
+ continue;
504
+ }
505
+ const name = auth.name ?? "Authorization";
506
+ switch (auth.in) {
507
+ case "query":
508
+ if (!options.query) {
509
+ options.query = {};
510
+ }
511
+ options.query[name] = token;
512
+ break;
513
+ case "cookie":
514
+ options.headers.append("Cookie", `${name}=${token}`);
515
+ break;
516
+ case "header":
517
+ default:
518
+ options.headers.set(name, token);
519
+ break;
520
+ }
521
+ }
522
+ };
523
+ var buildUrl = (options) => getUrl({
524
+ baseUrl: options.baseUrl,
525
+ path: options.path,
526
+ query: options.query,
527
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
528
+ url: options.url
529
+ });
530
+ var mergeConfigs = (a, b) => {
531
+ const config = { ...a, ...b };
532
+ if (config.baseUrl?.endsWith("/")) {
533
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
534
+ }
535
+ config.headers = mergeHeaders(a.headers, b.headers);
536
+ return config;
537
+ };
538
+ var headersEntries = (headers) => {
539
+ const entries = [];
540
+ headers.forEach((value, key) => {
541
+ entries.push([key, value]);
542
+ });
543
+ return entries;
544
+ };
545
+ var mergeHeaders = (...headers) => {
546
+ const mergedHeaders = new Headers();
547
+ for (const header of headers) {
548
+ if (!header) {
549
+ continue;
550
+ }
551
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
552
+ for (const [key, value] of iterator) {
553
+ if (value === null) {
554
+ mergedHeaders.delete(key);
555
+ } else if (Array.isArray(value)) {
556
+ for (const v of value) {
557
+ mergedHeaders.append(key, v);
558
+ }
559
+ } else if (value !== void 0) {
560
+ mergedHeaders.set(
561
+ key,
562
+ typeof value === "object" ? JSON.stringify(value) : value
563
+ );
564
+ }
565
+ }
566
+ }
567
+ return mergedHeaders;
568
+ };
569
+ var Interceptors = class {
570
+ fns = [];
571
+ clear() {
572
+ this.fns = [];
573
+ }
574
+ eject(id) {
575
+ const index = this.getInterceptorIndex(id);
576
+ if (this.fns[index]) {
577
+ this.fns[index] = null;
578
+ }
579
+ }
580
+ exists(id) {
581
+ const index = this.getInterceptorIndex(id);
582
+ return Boolean(this.fns[index]);
583
+ }
584
+ getInterceptorIndex(id) {
585
+ if (typeof id === "number") {
586
+ return this.fns[id] ? id : -1;
587
+ }
588
+ return this.fns.indexOf(id);
589
+ }
590
+ update(id, fn) {
591
+ const index = this.getInterceptorIndex(id);
592
+ if (this.fns[index]) {
593
+ this.fns[index] = fn;
594
+ return id;
595
+ }
596
+ return false;
597
+ }
598
+ use(fn) {
599
+ this.fns.push(fn);
600
+ return this.fns.length - 1;
601
+ }
602
+ };
603
+ var createInterceptors = () => ({
604
+ error: new Interceptors(),
605
+ request: new Interceptors(),
606
+ response: new Interceptors()
607
+ });
608
+ var defaultQuerySerializer = createQuerySerializer({
609
+ allowReserved: false,
610
+ array: {
611
+ explode: true,
612
+ style: "form"
613
+ },
614
+ object: {
615
+ explode: true,
616
+ style: "deepObject"
617
+ }
618
+ });
619
+ var defaultHeaders = {
620
+ "Content-Type": "application/json"
621
+ };
622
+ var createConfig = (override = {}) => ({
623
+ ...jsonBodySerializer,
624
+ headers: defaultHeaders,
625
+ parseAs: "auto",
626
+ querySerializer: defaultQuerySerializer,
627
+ ...override
628
+ });
629
+ var createClient = (config = {}) => {
630
+ let _config = mergeConfigs(createConfig(), config);
631
+ const getConfig = () => ({ ..._config });
632
+ const setConfig = (config2) => {
633
+ _config = mergeConfigs(_config, config2);
634
+ return getConfig();
635
+ };
636
+ const interceptors = createInterceptors();
637
+ const beforeRequest = async (options) => {
638
+ const opts = {
639
+ ..._config,
640
+ ...options,
641
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
642
+ headers: mergeHeaders(_config.headers, options.headers),
643
+ serializedBody: void 0
644
+ };
645
+ if (opts.security) {
646
+ await setAuthParams({
647
+ ...opts,
648
+ security: opts.security
649
+ });
650
+ }
651
+ if (opts.requestValidator) {
652
+ await opts.requestValidator(opts);
653
+ }
654
+ if (opts.body !== void 0 && opts.bodySerializer) {
655
+ opts.serializedBody = opts.bodySerializer(opts.body);
656
+ }
657
+ if (opts.body === void 0 || opts.serializedBody === "") {
658
+ opts.headers.delete("Content-Type");
659
+ }
660
+ const url = buildUrl(opts);
661
+ return { opts, url };
662
+ };
663
+ const request = async (options) => {
664
+ const { opts, url } = await beforeRequest(options);
665
+ const requestInit = {
666
+ redirect: "follow",
667
+ ...opts,
668
+ body: getValidRequestBody(opts)
669
+ };
670
+ let request2 = new Request(url, requestInit);
671
+ for (const fn of interceptors.request.fns) {
672
+ if (fn) {
673
+ request2 = await fn(request2, opts);
674
+ }
675
+ }
676
+ const _fetch = opts.fetch;
677
+ let response;
678
+ try {
679
+ response = await _fetch(request2);
680
+ } catch (error2) {
681
+ let finalError2 = error2;
682
+ for (const fn of interceptors.error.fns) {
683
+ if (fn) {
684
+ finalError2 = await fn(
685
+ error2,
686
+ void 0,
687
+ request2,
688
+ opts
689
+ );
690
+ }
691
+ }
692
+ finalError2 = finalError2 || {};
693
+ if (opts.throwOnError) {
694
+ throw finalError2;
695
+ }
696
+ return opts.responseStyle === "data" ? void 0 : {
697
+ error: finalError2,
698
+ request: request2,
699
+ response: void 0
700
+ };
701
+ }
702
+ for (const fn of interceptors.response.fns) {
703
+ if (fn) {
704
+ response = await fn(response, request2, opts);
705
+ }
706
+ }
707
+ const result = {
708
+ request: request2,
709
+ response
710
+ };
711
+ if (response.ok) {
712
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
713
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
714
+ let emptyData;
715
+ switch (parseAs) {
716
+ case "arrayBuffer":
717
+ case "blob":
718
+ case "text":
719
+ emptyData = await response[parseAs]();
720
+ break;
721
+ case "formData":
722
+ emptyData = new FormData();
723
+ break;
724
+ case "stream":
725
+ emptyData = response.body;
726
+ break;
727
+ case "json":
728
+ default:
729
+ emptyData = {};
730
+ break;
731
+ }
732
+ return opts.responseStyle === "data" ? emptyData : {
733
+ data: emptyData,
734
+ ...result
735
+ };
736
+ }
737
+ let data;
738
+ switch (parseAs) {
739
+ case "arrayBuffer":
740
+ case "blob":
741
+ case "formData":
742
+ case "json":
743
+ case "text":
744
+ data = await response[parseAs]();
745
+ break;
746
+ case "stream":
747
+ return opts.responseStyle === "data" ? response.body : {
748
+ data: response.body,
749
+ ...result
750
+ };
751
+ }
752
+ if (parseAs === "json") {
753
+ if (opts.responseValidator) {
754
+ await opts.responseValidator(data);
755
+ }
756
+ if (opts.responseTransformer) {
757
+ data = await opts.responseTransformer(data);
758
+ }
759
+ }
760
+ return opts.responseStyle === "data" ? data : {
761
+ data,
762
+ ...result
763
+ };
764
+ }
765
+ const textError = await response.text();
766
+ let jsonError;
767
+ try {
768
+ jsonError = JSON.parse(textError);
769
+ } catch {
770
+ }
771
+ const error = jsonError ?? textError;
772
+ let finalError = error;
773
+ for (const fn of interceptors.error.fns) {
774
+ if (fn) {
775
+ finalError = await fn(error, response, request2, opts);
776
+ }
777
+ }
778
+ finalError = finalError || {};
779
+ if (opts.throwOnError) {
780
+ throw finalError;
781
+ }
782
+ return opts.responseStyle === "data" ? void 0 : {
783
+ error: finalError,
784
+ ...result
785
+ };
786
+ };
787
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
788
+ const makeSseFn = (method) => async (options) => {
789
+ const { opts, url } = await beforeRequest(options);
790
+ return createSseClient({
791
+ ...opts,
792
+ body: opts.body,
793
+ headers: opts.headers,
794
+ method,
795
+ onRequest: async (url2, init) => {
796
+ let request2 = new Request(url2, init);
797
+ for (const fn of interceptors.request.fns) {
798
+ if (fn) {
799
+ request2 = await fn(request2, opts);
800
+ }
801
+ }
802
+ return request2;
803
+ },
804
+ url
805
+ });
806
+ };
807
+ return {
808
+ buildUrl,
809
+ connect: makeMethodFn("CONNECT"),
810
+ delete: makeMethodFn("DELETE"),
811
+ get: makeMethodFn("GET"),
812
+ getConfig,
813
+ head: makeMethodFn("HEAD"),
814
+ interceptors,
815
+ options: makeMethodFn("OPTIONS"),
816
+ patch: makeMethodFn("PATCH"),
817
+ post: makeMethodFn("POST"),
818
+ put: makeMethodFn("PUT"),
819
+ request,
820
+ setConfig,
821
+ sse: {
822
+ connect: makeSseFn("CONNECT"),
823
+ delete: makeSseFn("DELETE"),
824
+ get: makeSseFn("GET"),
825
+ head: makeSseFn("HEAD"),
826
+ options: makeSseFn("OPTIONS"),
827
+ patch: makeSseFn("PATCH"),
828
+ post: makeSseFn("POST"),
829
+ put: makeSseFn("PUT"),
830
+ trace: makeSseFn("TRACE")
831
+ },
832
+ trace: makeMethodFn("TRACE")
833
+ };
834
+ };
835
+ var client = createClient(createConfig({
836
+ baseUrl: "https://api.stably.ai"
837
+ }));
838
+ var postInternalV1TestAccountGoogleAuthState = (options) => {
839
+ return (options.client ?? client).post({
840
+ security: [
841
+ {
842
+ scheme: "bearer",
843
+ type: "http"
844
+ }
845
+ ],
846
+ url: "/internal/v1/test-account/google-auth-state",
847
+ ...options,
848
+ headers: {
849
+ "Content-Type": "application/json",
850
+ ...options.headers
851
+ }
852
+ });
853
+ };
854
+
855
+ const getApiUrl = () => process.env.STABLY_API_URL ?? "https://api.stably.ai";
856
+ const sdkVersion = "2.1.3-rc.1" ;
857
+ const assertNonEmptyString = (value, fieldName) => {
858
+ if (!value.trim()) {
859
+ throw new Error(`Missing required field: ${fieldName}`);
860
+ }
861
+ };
862
+ const isRecord = (value) => typeof value === "object" && value !== null;
863
+ const parseCookie = (value) => {
864
+ if (!isRecord(value)) {
865
+ throw new Error("Invalid Google storage state: cookie must be an object");
866
+ }
867
+ const { domain } = value;
868
+ const { name } = value;
869
+ const { path } = value;
870
+ const { sameSite } = value;
871
+ const valueText = value.value;
872
+ if (typeof domain !== "string" || typeof name !== "string" || typeof path !== "string" || typeof valueText !== "string") {
873
+ throw new Error(
874
+ "Invalid Google storage state: cookie is missing required fields"
875
+ );
876
+ }
877
+ return {
878
+ ...typeof value.expires === "number" ? { expires: value.expires } : {},
879
+ ...typeof value.httpOnly === "boolean" ? { httpOnly: value.httpOnly } : {},
880
+ ...typeof value.partitionKey === "string" ? { partitionKey: value.partitionKey } : {},
881
+ ...typeof value.secure === "boolean" ? { secure: value.secure } : {},
882
+ ...sameSite === "Lax" || sameSite === "None" || sameSite === "Strict" ? { sameSite } : {},
883
+ domain,
884
+ name,
885
+ path,
886
+ value: valueText
887
+ };
888
+ };
889
+ const parseLocalStorageEntry = (value) => {
890
+ if (!isRecord(value)) {
891
+ throw new Error(
892
+ "Invalid Google storage state: localStorage entry must be an object"
893
+ );
894
+ }
895
+ const { name } = value;
896
+ const storedValue = value.value;
897
+ if (typeof name !== "string" || typeof storedValue !== "string") {
898
+ throw new Error(
899
+ "Invalid Google storage state: localStorage entry must contain string name and value"
900
+ );
901
+ }
902
+ return { name, value: storedValue };
903
+ };
904
+ const parseOrigin = (value) => {
905
+ if (!isRecord(value)) {
906
+ throw new Error("Invalid Google storage state: origin must be an object");
907
+ }
908
+ const { origin } = value;
909
+ const rawLocalStorage = value.localStorage;
910
+ if (typeof origin !== "string") {
911
+ throw new Error("Invalid Google storage state: origin must be a string");
912
+ }
913
+ if (!Array.isArray(rawLocalStorage)) {
914
+ return { localStorage: [], origin };
915
+ }
916
+ return {
917
+ localStorage: rawLocalStorage.map(parseLocalStorageEntry),
918
+ origin
919
+ };
920
+ };
921
+ const parseStorageState = (value) => ({
922
+ cookies: Array.isArray(value.cookies) ? value.cookies.map(parseCookie) : [],
923
+ origins: Array.isArray(value.origins) ? value.origins.map(parseOrigin) : []
924
+ });
925
+ const applyStorageStateToContext = async (context, storageState) => {
926
+ if (storageState.cookies.length > 0) {
927
+ await context.addCookies(storageState.cookies);
928
+ }
929
+ for (const originState of storageState.origins) {
930
+ if (originState.localStorage.length === 0) {
931
+ continue;
932
+ }
933
+ const page = await context.newPage();
934
+ try {
935
+ await page.goto(originState.origin, { waitUntil: "domcontentloaded" });
936
+ await page.evaluate((entries) => {
937
+ for (const entry of entries) {
938
+ window.localStorage.setItem(entry.name, entry.value);
939
+ }
940
+ }, originState.localStorage);
941
+ } finally {
942
+ await page.close();
943
+ }
944
+ }
945
+ };
946
+ async function authWithGoogle(options) {
947
+ const apiKey = options.apiKey ?? requireApiKey();
948
+ assertNonEmptyString(options.email, "email");
949
+ assertNonEmptyString(options.password, "password");
950
+ assertNonEmptyString(options.otpSecret, "otpSecret");
951
+ const client = createClient({
952
+ baseUrl: getApiUrl(),
953
+ headers: {
954
+ Authorization: `Bearer ${apiKey}`,
955
+ "X-Client-Name": "stably-playwright-test",
956
+ "X-Client-Version": sdkVersion,
957
+ "X-Stably-SDK-Version": sdkVersion
958
+ }
959
+ });
960
+ const response = await postInternalV1TestAccountGoogleAuthState({
961
+ body: {
962
+ email: options.email,
963
+ forceRefresh: options.forceRefresh,
964
+ otpSecret: options.otpSecret,
965
+ password: options.password
966
+ },
967
+ client
968
+ });
969
+ if (response.error) {
970
+ const errorMessage = "error" in response.error ? response.error.error : "Unknown error";
971
+ throw new Error(`Failed to authenticate with Google: ${errorMessage}`);
972
+ }
973
+ const storageState = parseStorageState(response.data.storageState);
974
+ await applyStorageStateToContext(options.context, storageState);
975
+ }
976
+
33
977
  function getDirname(importMetaUrl) {
34
978
  return dirname(fileURLToPath(importMetaUrl));
35
979
  }
@@ -45,7 +989,11 @@ const test = test$2.extend({
45
989
  await use(augmentBrowser(browser));
46
990
  },
47
991
  context: async ({ context }, use) => {
48
- await use(augmentBrowserContext(context));
992
+ const augmentedContext = augmentBrowserContext(context);
993
+ if (!("authWithGoogle" in augmentedContext)) {
994
+ augmentedContext.authWithGoogle = (options) => authWithGoogle({ context: augmentedContext, ...options });
995
+ }
996
+ await use(augmentedContext);
49
997
  },
50
998
  page: async ({ page }, use) => {
51
999
  await use(augmentPage(page));
@@ -54,5 +1002,5 @@ const test = test$2.extend({
54
1002
  const expect = expect$1.extend(stablyPlaywrightMatchers);
55
1003
  const defineConfig = defineConfig$1;
56
1004
 
57
- export { defineConfig, expect, getDirname, getFilename, test };
1005
+ export { authWithGoogle, defineConfig, expect, getDirname, getFilename, test };
58
1006
  //# sourceMappingURL=index.mjs.map