smtp/date: add isRFC2822Date api & use in tests

This commit is contained in:
Zack Schuster 2020-10-30 13:46:42 -07:00 committed by Zack Schuster
parent b6aa8133b1
commit c13356b51e
2 changed files with 21 additions and 9 deletions

View File

@ -33,3 +33,18 @@ export function getRFC2822DateUTC(date = new Date()) {
dates.push('+0000');
return dates.join(' ');
}
/**
* RFC 2822 regex
* @see https://tools.ietf.org/html/rfc2822#section-3.3
* @see https://github.com/moment/moment/blob/a831fc7e2694281ce31e4f090bbcf90a690f0277/src/lib/create/from-string.js#L101
*/
const rfc2822re = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/.compile();
/**
* @param {string} [date] a string to check for conformance to the [rfc2822](https://tools.ietf.org/html/rfc2822#section-3.3) standard
* @returns {boolean} the result of the conformance check
*/
export function isRFC2822Date(date: string) {
return rfc2822re.test(date);
}

View File

@ -1,18 +1,15 @@
import test from 'ava';
import { getRFC2822Date, getRFC2822DateUTC } from '../email';
import { getRFC2822Date, getRFC2822DateUTC, isRFC2822Date } from '../email';
const toD_utc = (dt: number) => getRFC2822DateUTC(new Date(dt));
const toD = (dt: number, utc = false) => getRFC2822Date(new Date(dt), utc);
test('rfc2822 non-UTC', async (t) => {
// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
// thanks to moment.js for the listing: https://github.com/moment/moment/blob/a831fc7e2694281ce31e4f090bbcf90a690f0277/src/lib/create/from-string.js#L101
const rfc2822re = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
t.regex(toD(0), rfc2822re);
t.regex(toD(329629726785), rfc2822re);
t.regex(toD(729629726785), rfc2822re);
t.regex(toD(1129629726785), rfc2822re);
t.regex(toD(1529629726785), rfc2822re);
t.true(isRFC2822Date(toD(0)));
t.true(isRFC2822Date(toD(329629726785)));
t.true(isRFC2822Date(toD(729629726785)));
t.true(isRFC2822Date(toD(1129629726785)));
t.true(isRFC2822Date(toD(1529629726785)));
});
test('rfc2822 UTC', async (t) => {