bbo
Version:
bbo is a utility library of zero dependencies for javascript.
137 lines (104 loc) • 3.54 kB
JavaScript
;
var has_own_property = require('./has_own_property.js');
require('./get_tag.js');
require('./is_array.js');
require('./is_string.js');
require('./is_map.js');
require('./is_set.js');
var size = require('./size.js');
var is_number = require('./is_number.js');
/* eslint-disable guard-for-in */
var cookie = () => {
function cookieAttrExtend() {
var i = 0;
var result = {};
for (; i < arguments.length; i++) {
var attributes = arguments[i];
for (var key in attributes) {
if (has_own_property(attributes, key)) {
result[key] = attributes[key];
}
}
}
return result;
}
function init(converter) {
function api(key, value, attributes) {
var result;
if (size(arguments) > 1) {
attributes = cookieAttrExtend({
path: '/'
}, api.defaults, attributes);
if (is_number(attributes.expires)) {
var expires = new Date();
expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e5);
attributes.expires = expires;
}
try {
result = JSON.stringify(value);
if (/^[\{\[]/.test(result)) {
value = result;
}
} catch (e) {}
if (!converter.write) {
value = encodeURIComponent(String(value)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
} else {
value = converter.write(value, key);
}
key = encodeURIComponent(String(key));
key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
key = key.replace(/[\(\)]/g, escape); // eslint-disable-next-line no-return-assign
return document.cookie = [key, '=', value, attributes.expires ? '; expires=' + attributes.expires.toUTCString() : '', attributes.path ? '; path=' + attributes.path : '', attributes.domain ? '; domain=' + attributes.domain : '', attributes.secure ? '; secure' : ''].join('');
}
if (!key) {
result = {};
}
var cookies = document.cookie ? document.cookie.split('; ') : [];
var rdecode = /(%[0-9A-Z]{2})+/g;
var i = 0;
for (; i < cookies.length; i++) {
var parts = cookies[i].split('=');
var _cookie = parts.slice(1).join('=');
if (_cookie.charAt(0) === '"') {
_cookie = _cookie.slice(1, -1);
}
try {
var name = parts[0].replace(rdecode, decodeURIComponent);
_cookie = converter.read ? converter.read(_cookie, name) : converter(_cookie, name) || _cookie.replace(rdecode, decodeURIComponent); // eslint-disable-next-line no-invalid-this
if (this.json) {
try {
_cookie = JSON.parse(_cookie);
} catch (e) {}
}
if (key === name) {
result = _cookie;
break;
}
if (!key) {
result[name] = _cookie;
}
} catch (e) {}
}
return result;
}
api.set = api;
api.get = function (key) {
return api.call(api, key);
};
api.getJson = api.getJSON = function () {
return api.apply({
json: true
}, [].slice.call(arguments));
};
api.defaults = {};
api.remove = function (key, attributes) {
api(key, '', cookieAttrExtend(attributes, {
expires: -1
}));
};
api.withConverter = init;
return api;
}
return init(function () {});
};
module.exports = cookie;