-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (98 loc) · 2.62 KB
/
index.js
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
export default class Cookie
{
/**
* Make a new Cookie instance.
*
* @param {string} namespace
*/
constructor(namespace = '')
{
this.namespace = namespace;
}
/**
* Set a cookie value for the given key.
*
* @param {string} key
* @param {string} value
* @param {Date|string|number|null} expires - Number of days, Date, or string for expiry.
* @param {string} path
* @param {object} options
* @return {void}
*/
set(key, value, expires = null, path = '/', options = {})
{
key = this._qualify(key);
value = encodeURIComponent(value).replace(
/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
window.decodeURIComponent
);
if (typeof expires === 'number') {
const date = new Date();
date.setDate(date.getDate() + expires);
expires = date;
}
if (expires instanceof Date) {
expires = expires.toUTCString();
}
const cookie = {
[key]: value,
expires,
path,
SameSite: 'Lax',
Secure: true,
...options,
};
/** @type {string[]} */
const initialValue = [];
document.cookie = Object.entries(cookie)
.reduce((stack, entry) => stack.concat(entry.join('=')), initialValue)
.join('; ');
}
/**
* Get the cookie with the given key.
*
* @param {string} key
* @param {*} value
* @return {*}
*/
get(key, value = null)
{
key = this._qualify(key);
const cookie = document.cookie.match(new RegExp('(^| )' + key + '=([^;]+)'));
const value = (cookie && cookie[2]) ? cookie[2] : value;
return value.replace(/(%[\dA-F]{2})+/gi, window.decodeURIComponent);
}
/**
* Determine if the given cookie exists.
*
* @param {string} key
* @return {boolean}
*/
isset(key)
{
key = this._qualify(key);
return document.cookie.match(new RegExp('(^| )' + key + '=([^;]+)')) !== null;
}
/**
* Remove the given cookie.
*
* @param {string} key
* @return {void}
*/
remove(key)
{
this.set(key, '', 'Thu, 01 Jan 1970 00:00:01 GMT');
}
/**
* Qualify the given key.
*
* @param {string} key
* @return {string}
*/
_qualify(key)
{
return window.encodeURIComponent(this.namespace + key)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/%(2[346B]|5E|60|7C)/g, window.decodeURIComponent);
}
}