-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_fake.js
More file actions
626 lines (579 loc) · 15.2 KB
/
test_fake.js
File metadata and controls
626 lines (579 loc) · 15.2 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
// MIT License
// Copyright (c) 2026 Open2b
// See the LICENSE file for full text.
import { assert, assertEquals, AssertionError } from '@std/assert'
import { DOMParser } from 'https://deno.land/x/deno_dom/deno-dom-wasm.ts'
import * as uuid from '@std/uuid/v4'
import { MaxBodySize } from './sender.js'
import * as utils from './utils.js'
// Cookie represents a cookie stored by CookieDocument.
class Cookie {
name
value
path
expires
sameSite
secure
domain
}
// CookieDocument implements a fake document with a 'document.cookie' property
// that accept cookie from a domain and its subdomains.
class CookieDocument {
#location
#domain
#cookies = []
// constructor returns a new CookieDocument with the provided location and
// the domain to use for cookies.
constructor(location, domain) {
if (!(location instanceof URL)) {
throw new Error('location is not an instance of URL')
}
this.#location = location
this.#domain = domain
}
get cookie() {
return this.#cookies.map((cookie) => `${cookie.name}=${cookie.value}`).join('; ')
}
set cookie(s) {
const cookie = CookieDocument.#parse(s)
if (cookie.domain != null && !cookie.domain.endsWith(this.#domain)) {
return
}
if (cookie.path == null) {
cookie.path = this.#location.path
}
for (let i = 0; i < this.#cookies.length; i++) {
const c = this.#cookies[i]
if (c.name === cookie.name && c.domain === cookie.domain) {
if (cookie.expires != null && cookie.expires < new Date()) {
this.#cookies.splice(i, 1)
} else {
c.value = cookie.value
c.path = cookie.path
c.expires = cookie.expires
}
return
}
}
this.#cookies.push(cookie)
}
// getCookie returns the cookie with the provides key and domain as a Cookie
// value. If such cookie does non exist, it returns undefined.
getCookie(name, domain) {
for (let i = 0; i < this.#cookies.length; i++) {
const c = this.#cookies[i]
if (c.name === name && c.domain === domain) {
return Object.assign(Object.create(Object.getPrototypeOf(c)), c)
}
}
}
static #parse(s) {
const cookie = new Cookie()
const parts = s.split(/\s*;\s*/)
for (let i = 0; i < parts.length; i++) {
const pair = parts[i].split(/\s*=\s*/)
if (i === 0) {
cookie.name = pair[0]
cookie.value = pair[1]
continue
}
switch (pair[0]) {
case 'path':
cookie.path = pair[1]
break
case 'domain':
cookie.domain = pair[1]
if (cookie.domain.length > 0 && cookie.domain[0] === '.') {
cookie.domain = cookie.domain.slice(1)
}
break
case 'expires':
cookie.expires = new Date(pair[1])
break
case 'samesite':
cookie.sameSite = pair[1]
break
case 'secure':
cookie.secure = true
break
default:
throw new Error(`Unknown cookie attribute '${pair[0]}'`)
}
}
return cookie
}
}
// Fetch implements a fake fetch.
class Fetch {
#installTime
#writeKey
#endpoint
#keepalive
#events = []
#wait = null
#error
#fetch
#originalFetch
#debug
constructor(writeKey, endpoint, keepalive, debug) {
this.#writeKey = writeKey
this.#endpoint = endpoint
this.#keepalive = keepalive
this.#fetch = async (resource, options) => {
let events
try {
assertEquals(resource, endpoint)
events = await parseRequest(this.#writeKey, this.#installTime, this.#keepalive, options)
} catch (error) {
if (this.#wait != null) {
this.#wait.reject(error)
} else {
this.#error = error
}
throw error
}
this.#events.push(...events)
const min = this.#wait?.min
if (min != null && this.#events.length >= min) {
const events = this.#events
const resolve = this.#wait.resolve
this.#events = []
this.#wait = null
this.#debug?.(`promise resolution is resolved: Fetch.events(${min})`)
resolve(events)
}
const res = new Response('', {
status: 200,
statusText: 'OK',
headers: new Headers({ 'content-type': 'text/plain' }),
})
return res
}
this.#debug = utils.debug(debug)
}
events(min) {
if (this.#installTime == null) {
return new Promise((_, reject) => {
reject(new Error('Fake fetch is not installed'))
})
}
if (this.#wait != null) {
return new Promise((_, reject) => {
reject(new Error('events already called'))
})
}
return new Promise((resolve, reject) => {
if (this.#error != null) {
reject(this.#error)
return
}
if (this.#events.length < min) {
this.#wait = {
min: min,
resolve: resolve,
reject: reject,
}
this.#debug?.(`promise resolution is pending: Fetch.events(${min})`)
} else {
const events = this.#events
this.#events = []
this.#wait = null
resolve(events)
}
})
}
install() {
if (this.#originalFetch != null) {
throw new Error('Fake fetch is already installed')
}
this.#installTime = utils.getTime()
this.#events = []
this.#wait = null
this.#originalFetch = globalThis.fetch
assert(this.#originalFetch != null)
globalThis.fetch = this.#fetch
}
restore() {
if (this.#originalFetch == null) {
throw new Error('Fake fetch is not installed')
}
globalThis.fetch = this.#originalFetch
this.#originalFetch = null
if (this.#events.length > 0) {
throw new AssertionError(
`Fake fetch has been restored; however, there are ${this.#events.length} unread events`,
)
}
}
}
// SendBeacon implements a fake sendBeacon.
class SendBeacon {
#installTime
#writeKey
#endpoint
#events = []
#wait = null
#error
#sendBeacon
#debug
constructor(writeKey, endpoint, debug) {
this.#writeKey = writeKey
this.#endpoint = endpoint
this.#sendBeacon = (url, data) => {
try {
assertEquals(url, endpoint)
assert(data instanceof Blob)
assertEquals(data.type, 'text/plain')
parseRequest(this.#writeKey, this.#installTime, false, {
method: 'POST',
headers: { 'Content-Type': data.type },
body: data,
redirect: 'error',
}).then((events) => {
this.#events.push(...events)
const min = this.#wait?.min
if (min != null && this.#events.length >= min) {
const events = this.#events
const resolve = this.#wait.resolve
this.#events = []
this.#wait = null
this.#debug?.(`promise resolution is resolved: SendBeacon.events(${min})`)
resolve(events)
}
})
} catch (error) {
if (this.#wait != null) {
this.#wait.reject(error)
} else {
this.#error = error
}
throw error
}
return true
}
this.#debug = utils.debug(debug)
}
events(min) {
if (this.#installTime == null) {
return new Promise((_, reject) => {
reject(new Error('Fake sendBeacon is not installed'))
})
}
if (this.#wait != null) {
return new Promise((_, reject) => {
reject(new Error('events already called'))
})
}
return new Promise((resolve, reject) => {
if (this.#error != null) {
reject(this.#error)
return
}
if (this.#events.length < min) {
this.#wait = {
min: min,
resolve: resolve,
}
this.#debug?.(`promise resolution is pending: SendBeacon.events(${min})`)
} else {
const events = this.#events
this.#events = []
this.#wait = null
resolve(events)
}
})
}
install() {
if (this.#installTime != null) {
throw new Error('Fake sendBeacon is already installed')
}
this.#installTime = utils.getTime()
this.#events = []
this.#wait = null
navigator.sendBeacon = this.#sendBeacon
}
restore() {
if (this.#installTime == null) {
throw new Error('Fake sendBeacon is not installed')
}
this.#installTime = null
if (this.#events.length > 0) {
throw new AssertionError(
`Fake sendBeacon has been restored; however, there are ${this.#events.length} unread events`,
)
}
delete navigator.sendBeacon
}
}
// HTMLDocument is a fake HTMLDocument.
class HTMLDocument {
#dom
#visibilityState = 'visible'
referrer = ''
title = 'Hello from Krenalis'
get visibilityState() {
return this.#visibilityState
}
set visibilityState(value) {
if (value !== 'visible' && value !== 'hidden') {
throw new Error(`invalid visibility state '${value}'`)
}
if (value === this.#visibilityState) {
return
}
this.#visibilityState = value
dispatchEvent(new Event('visibilitychange'))
}
constructor() {
this.#dom = new DOMParser().parseFromString('<!DOCTYPE html>', 'text/html')
}
addEventListener() {
addEventListener.bind(globalThis)(...arguments)
}
createElement() {
return this.#dom.createElement(...arguments)
}
querySelector(selectors) {
if (selectors !== 'link[rel="canonical"]') {
throw new Error(`query selector '${selector}' is not supported by the fake HTMLDocument`)
}
const element = this.#dom.createElement('link')
element.setAttribute('rel', 'canonical')
element.setAttribute('href', '/path?query=123')
element.href = 'https://example.com:8080/path?query=123'
return element
}
}
// Navigator is a fake Navigator.
class Navigator {
language = 'en-US'
userAgent =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'
onLine = true
#originalNavigator
install() {
if (this.#originalNavigator != null) {
throw new Error('Fake Navigator is already installed')
}
this.#originalNavigator = navigator
delete (globalThis.navigator)
globalThis.navigator = this
}
restore() {
if (this.#originalNavigator == null) {
throw new Error('Fake Navigator is not installed')
}
delete (globalThis.navigator)
globalThis.navigator = this.#originalNavigator
this.#originalNavigator = null
}
}
// Storage implements a fake storage that raises an exception at each method
// call.
//
// As a special case, getItem, setItem, and removeItem methods behave as
// expected if the key is '__test__'.
class Storage {
#testValue = null
length = 0
key() {
throw new Error('No storage available')
}
getItem(key) {
if (key === '__test__') {
return this.#testValue
}
throw new Error('No storage available')
}
setItem(key, value) {
if (key === '__test__') {
this.#testValue = String(value)
return
}
throw new Error('Quota exceeded')
}
removeItem(key) {
if (key === '__test__') {
this.#testValue = null
return
}
throw new Error('No storage available')
}
clear() {
throw new Error('No storage available')
}
}
// XMLHttpRequest is a fake XMLHttpRequest.
class XMLHttpRequest {
static #installTime
static #writeKey
static #endpoint
static #events
static #wait
static #error
static #debug
#method
#url
#headers = new Headers()
onerror
onreadystatechange
readyState
status
statusText
open(method, endpoint, async) {
assert(endpoint, XMLHttpRequest.#endpoint)
assert(async)
this.#method = method.toUpperCase()
this.#url = endpoint
}
setRequestHeader(name, value) {
this.#headers.set(name.toLowerCase(), value)
}
send(body) {
this.readyState = 4
this.status = 200
this.statusText = 'OK'
try {
parseRequest(XMLHttpRequest.#writeKey, XMLHttpRequest.#installTime, false, {
method: this.#method,
headers: this.#headers,
body: body,
redirect: 'error',
}).then((events) => {
XMLHttpRequest.#events.push(...events)
const min = XMLHttpRequest.#wait?.min
if (min != null && XMLHttpRequest.#events.length >= min) {
const events = XMLHttpRequest.#events
const resolve = XMLHttpRequest.#wait.resolve
XMLHttpRequest.#events = []
XMLHttpRequest.#wait = null
XMLHttpRequest.#debug?.(`promise resolution is resolved: XMLHttpRequest.events(${min})`)
resolve(events)
}
}).catch((error) => {
console.error(error)
})
} catch (error) {
if (XMLHttpRequest.#wait.reject != null) {
XMLHttpRequest.#wait.reject(error)
} else {
XMLHttpRequest.#error = error
}
throw error
}
if (typeof this.onreadystatechange === 'function') {
this.onreadystatechange()
}
}
static events(min) {
if (XMLHttpRequest.#installTime == null) {
return new Promise((_, reject) => {
reject(new Error('Fake XMLHttpRequest is not installed'))
})
}
if (XMLHttpRequest.#wait != null) {
return new Promise((_, reject) => {
reject(new Error('events already called'))
})
}
return new Promise((resolve, reject) => {
if (XMLHttpRequest.#error != null) {
reject(this.#error)
return
}
if (XMLHttpRequest.#events.length < min) {
XMLHttpRequest.#wait = {
min: min,
resolve: resolve,
}
XMLHttpRequest.#debug?.(`promise resolution is pending: XMLHttpRequest.events(${min})`)
} else {
const events = XMLHttpRequest.#events
XMLHttpRequest.#events = []
XMLHttpRequest.#wait = null
resolve(events)
}
})
}
static install(writeKey, endpoint, debug) {
if (XMLHttpRequest.#installTime != null) {
throw new Error('Fake XMLHttpRequest is already installed')
}
XMLHttpRequest.#installTime = utils.getTime()
XMLHttpRequest.#events = []
XMLHttpRequest.#wait = null
XMLHttpRequest.#writeKey = writeKey
XMLHttpRequest.#endpoint = endpoint
XMLHttpRequest.#debug = utils.debug(debug)
globalThis.XMLHttpRequest = XMLHttpRequest
}
static restore() {
if (XMLHttpRequest.#installTime == null) {
throw new Error('Fake XMLHttpRequest is not installed')
}
XMLHttpRequest.#installTime = null
delete (globalThis.XMLHttpRequest)
if (this.#events.length > 0) {
throw new AssertionError(
`Fake fetch has been restored; however, there are ${this.#events.length} unread events`,
)
}
}
}
// RandomUUID implements a fake crypto.randomUUID function.
class RandomUUID {
#uuid
#originalRandomUUID
constructor(uuid) {
this.#uuid = uuid
}
install() {
if (this.#originalRandomUUID != null) {
throw new Error('Fake crypto.randomUUID is already installed')
}
this.#originalRandomUUID = crypto.randomUUID.bind(crypto)
crypto.randomUUID = () => this.#uuid
}
restore() {
if (this.#originalRandomUUID == null) {
throw new Error('Fake crypto.randomUUID is not installed')
}
crypto.randomUUID = this.#originalRandomUUID
this.#originalRandomUUID = null
}
}
// parseRequest parses a request to the fake fetch and XMLHttpRequest.send functions
async function parseRequest(writeKey, minTime, keepalive, options) {
const now = utils.getTime()
assertEquals(options.method, 'POST')
let headers = options.headers
if (!(options.headers instanceof Headers)) {
headers = new Headers(options.headers)
}
assertEquals(Array.from(headers.keys()).length, 1)
assertEquals(headers.get('content-type'), 'text/plain')
assertEquals(options.redirect, 'error')
assertEquals(Boolean(options.keepalive), keepalive)
assert(options.body instanceof Blob)
if (options.body.size > MaxBodySize) {
throw new AssertionError(`batch body size (${options.body.size}) is greater than ${MaxBodySize}`)
}
const body = JSON.parse(await options.body.text())
assertEquals(typeof body.batch, 'object')
assert(body.batch instanceof Array)
assert(body.batch.length > 0)
assertEquals(typeof body.sentAt, 'string')
const sentAt = new Date(body.sentAt)
assert(minTime <= sentAt && sentAt <= now)
assertEquals(body.writeKey, writeKey)
const events = []
for (let i = 0; i < body.batch.length; i++) {
const event = body.batch[i]
assertEquals(typeof event, 'object')
assertEquals(typeof event.messageId, 'string')
assert(uuid.validate(event.messageId))
events.push(event)
}
return events
}
export { Cookie, CookieDocument, Fetch, HTMLDocument, Navigator, RandomUUID, SendBeacon, Storage, XMLHttpRequest }