+const validTokenRE = /^[!#$%&'*+-.0-9A-Z^_`a-z~]+$/;
+const validValueRE = /^[!#$%&'()*+-./0-9:<=>?@A-Z[\]^_`a-z{|}~]*$/;
+const validPathRE = /^[ !"#$%&'()*+,-./0-9:<=>?@A-Z[\\\]^_`a-z{|}~]*$/;
+const validLabelRE = /^[a-zA-Z0-9-]+$/;
+const invalidLabelRE = /--|^-|-$/;
+
+/**
+ * Adds a new set-cookie header value to response, with supplied data.
+ * @param {http.ServerResponse} res response
+ * @param {(string, string) => void} res.appendHeader sets header values
+ * @param {string} name cookie name
+ * @param {string} value cookie value
+ * @param {object=} opt cookie options
+ * @param {string=} opt.domain cookie domain
+ * @param {Date=} opt.expires cookie expiration
+ * @param {boolean=} opt.httpOnly cookie client visibility
+ * @param {number=} opt.maxAge cookie lifetime
+ * @param {string=} opt.path cookie path
+ * @param {string=} opt.sameSite cookie sharing
+ * @param {boolean=} opt.secure cookie security
+ * @param {string[]=} opt.extension cookie extension attribute values
+ */
+function addCookie(res, name, value, opt = {}) {
+ const options = {
+ domain: undefined,
+ expires: undefined,
+ httpOnly: false,
+ maxAge: undefined,
+ path: undefined,
+ sameSite: undefined,
+ secure: false,
+ extension: [],
+ ...opt,
+ };
+
+ if (!validTokenRE.test(name)) {
+ throw new RangeError('invalid cookie name');
+ }
+
+ if (value.startsWith('"') && value.endsWith('"')) {
+ if (!validValueRE.test(value.slice(1, value.length - 1))) {
+ throw new RangeError('invalid cookie value');
+ };
+ } else if (!validValueRE.test(value)) {
+ throw new RangeError('invalid cookie value');
+ }
+
+ const cookieParts = [
+ `${name}=${value}`,
+ ];
+
+ if (options.domain) {
+ for (const label of options.domain.split('.')) {
+ if (!validLabelRE.test(label) || invalidLabelRE.test(label)) {
+ throw new RangeError('invalid cookie domain');
+ }
+