-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
219 lines (204 loc) · 6.22 KB
/
utils.js
File metadata and controls
219 lines (204 loc) · 6.22 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
// MIT License
// Copyright (c) 2026 Open2b
// See the LICENSE file for full text.
const isIE = !globalThis.ActiveXObject && 'ActiveXObject' in globalThis
// campaign returns a Map with the UTM parameters of the campaign.
function campaign() {
const campaign = parseQueryString(globalThis.location.search, 'utm_')
if (campaign.has('campaign')) {
campaign.set('name', campaign.get('campaign'))
campaign.delete('campaign')
}
return campaign
}
// debug returns a logging function for debug messages if 'on' is true;
// otherwise, it returns undefined.
function debug(on) {
if (on) {
if (isIE) {
return (...msg) => {
console.debug(`[${getTime()}] krenalis:`, ...msg)
}
}
return (...msg) => {
console.debug('%c krenalis ', 'background:#606060;color:#eee', `[${getTime()}]`, ...msg)
}
}
}
const textDecoder = typeof globalThis.TextDecoder === 'function' ? new globalThis.TextDecoder() : null
const textEncoder = typeof globalThis.TextEncoder === 'function' ? new globalThis.TextEncoder() : null
// decodeBase64 returns a string represented by the base64 encoded string s.
// If s is prefixed by _, the subsequent characters of s are interpreted as
// UTF-16 encoded characters (each represented by pairs of bytes), instead of
// UTF-8.
function decodeBase64(s) {
if (s === '') {
return ''
}
const utf16 = s[0] === '_'
if (utf16) {
s = s.slice(1)
}
const b = atob(s)
const buf = new Uint8Array(b.length)
for (let i = 0; i < buf.length; i++) {
buf[i] = b.charCodeAt(i)
}
if (!utf16) {
return textDecoder.decode(buf)
}
return String.fromCharCode.apply(null, new Uint16Array(buf.buffer))
}
// encodeBase64 returns the base64 encoding of the string src. If TextDecoder
// and TextEncoder are not supported, it returns the base64 encoding of the
// UTF-16 encoded content of src, instead of UTF-8, prefixed by _. If src is
// empty, it returns an empty string.
function encodeBase64(src) {
if (src === '') {
return ''
}
let s
// The condition has not simplified to "textDecoder && textEncoder" to allow tests.
if (globalThis.TextDecoder && globalThis.TextEncoder) {
s = btoa(String.fromCodePoint.apply(null, textEncoder.encode(src)))
} else {
const b = new Uint16Array(src.length)
for (let i = 0; i < b.length; i++) {
b[i] = src.charCodeAt(i)
}
s = '_' + btoa(String.fromCharCode.apply(null, new Uint8Array(b.buffer)))
}
return s.replace(/=+$/, '')
}
// getTime returns the current UTC time in milliseconds from the epoch.
function getTime() {
return new Date().getTime()
}
// isPlainObject reports whether obj is a plain object.
function isPlainObject(obj) {
return typeof obj === 'object' && !Array.isArray(obj) && obj != null
}
// isURL reports whether url is a URL.
function isURL(url) {
if (typeof url !== 'string' || !/^https?:\/\/\S+$/.test(url)) {
return false
}
if (typeof globalThis.URL === 'function') {
try {
new URL(url)
} catch {
return false
}
return true
}
const a = document.createElement('a')
a.href = url
return a.href !== '' && a.hostname !== ''
}
// log returns a logging function for log error messages on the console.
function log(...msg) {
if (isIE) {
console.error('krenalis:', ...msg)
return
}
console.error('%c krenalis ', 'background:#dc362e;color:#dcdcdc', ...msg)
}
// onVisibilityChange calls cb when the browser shows or hides the current page.
// It passed as argument a boolean indicating if the page is visible.
function onVisibilityChange(cb) {
function isVisible() {
const state = document.visibilityState || document.webkitvisibilitychange
return state !== 'hidden'
}
let visible = isVisible()
const change = () => {
if (visible !== isVisible()) {
visible = !visible
cb(visible)
}
}
// IE 11 do not support 'visibilitychange'.
// In Safari before 14 'visibilitychange' does not work on globalThis but works on document.
// In Safari before 14.5 'visibilitychange' does not fire on page hide, but 'pagehide' does.
document.addEventListener('visibilitychange', change)
addEventListener('pagehide', change)
addEventListener('pageshow', change)
}
// parseQueryString parses the provided query string, beginning with '?', and
// returns a Map with keys starting with the given prefix. If a key is repeated,
// only the value of the last occurrence is returned.
function parseQueryString(query, prefix) {
const values = new Map()
// ES5: "URLSearchParams" is not available.
const search = query.substring(1).replace(/\?/g, '&')
const params = search.split('&')
for (let i = 0; i < params.length; i++) {
let p = params[i].indexOf(prefix)
if (p !== 0) {
continue
}
const kv = params[i].substring(prefix.length)
p = kv.indexOf('=')
if (p < 0) {
p = kv.length
}
const k = kv.substring(0, p)
const v = kv.substring(p + 1)
try {
// ES5: "replaceAll" is not available.
values.set(k, decodeURIComponent(v.replace(/\+/g, ' ')))
} catch {
// nothing.
}
}
return values
}
// _uuid_imp returns a function that returns random UUIDs or undefined if the
// browser is not supported.
function _uuid_imp() {
let crypto = globalThis.crypto
if (crypto && typeof crypto.randomUUID === 'function') {
return () => crypto.randomUUID()
}
// The following statement could be simplified to "crypto ||= globalThis.msCrypto",
// but it hasn't been done because it wouldn't be testable.
// Therefore, do not change it.
if (!crypto || typeof crypto.getRandomValues !== 'function') {
crypto = globalThis.msCrypto
}
if (crypto && typeof crypto.getRandomValues === 'function') {
return function () {
// See https://stackoverflow.com/questions/105034/#2117523
return '10000000-1000-4000-8000-100000000000'.replace(
/[018]/g,
(c) => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16),
)
}
}
const URL = globalThis.URL
if (URL && typeof URL.createObjectURL === 'function') {
return function () {
const url = URL.createObjectURL(new Blob())
const uuid = url.toString()
URL.revokeObjectURL(url)
return uuid.split(/[:\/]/g).pop()
}
}
}
// uuid returns a random UUID.
// The uuid function is undefined for unsupported browsers.
const uuid = _uuid_imp()
export {
_uuid_imp,
campaign,
debug,
decodeBase64,
encodeBase64,
getTime,
isPlainObject,
isURL,
log,
onVisibilityChange,
parseQueryString,
uuid,
}