김대선

00시 00분 자동으로 데이터를 받아와서 datas 폴더에 년.월.시간 형식으로 저장

Showing 189 changed files with 20800 additions and 7 deletions
const express = require('express')
const schedule = require('node-schedule')
const fs = require('fs')
const functions = require('./function')
const app = express();
const server = app.listen(3000,()=>{
const host = server.address().address
const port = server.address().port
console.log("app listening at http://%s:%s", host, port)
})
const readData = async () =>{
const data = []
let title = ""
let tags = []
let url = ""
const today = new Date()
const string = fs.readFileSync(`./datas/${today.getFullYear()}.${today.getMonth()}.${today.getDate()}`, 'utf-8', 'r')
const stringArray = string.split('\n')
const size = stringArray.length
for(let i = 0 ; i < size; i++){
if( i % 3 == 0){
title = stringArray[i].replace("title : ", "")
}
else if( i % 3 == 1){
tags = stringArray[i].replace("tags : ", "").split(",")
}
else if ( i % 3 == 2){
url = stringArray[i].replace("url : ", "")
data.push({
title : title,
tags : tags,
url : url
})
}
}
console.log(data)
}
app.get('/', async (req, res)=>{
const save = async()=> {
try {
let string = ""
let data = await functions.getKakaoData()
let temp = ""
......@@ -46,6 +71,30 @@ app.get('/', async (req, res)=>{
temp = "url : " + i.url
string = string + temp + "\n"
}
const today = new Date()
fs.writeFile(`./datas/${today.getFullYear()}.${today.getMonth()}.${today.getDate()}`, string, 'utf-8', (err)=>{
if(err){
save()
}
else console.log("저장완료!")
})
} catch (error) {
console.log(error)
save()
}
}
const saveData = schedule.scheduleJob('0 0 0 * * *', save)
const server = app.listen(3000,()=>{
const host = server.address().address
const port = server.address().port
console.log("app listening at http://%s:%s", host, port)
})
app.get('/', async (req, res)=>{
res.send(string)
})
\ No newline at end of file
......
title : 카카오전문연구요원(전직및보충역)모집
tags : #Android,#iOS,#Windows,#Webfront,#System,#Network,#Cloud,#DB,#Security,#Algorithm/ML,#Algorithm/Ranking,#Hadoopecosystem,#Server,#Statistics/Analysis,#기타
url : https://careers.kakao.com/jobs/P-9349
title : 악성코드및엔드포인트위협대응보안엔지니어모집(경력)
tags : #Windows,#Security,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-12045
title : 카카오톡안티어뷰징을위한데이터/백엔드엔지니어및머신러닝전문가모집
tags : #Algorithm/ML,#Hadoopecosystem,#Server,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11083
title : [티스토리,브런치]프론트엔드개발자모집(경력)
tags : #Webfront
url : https://careers.kakao.com/jobs/P-11790
title : [톡캘린더웹서비스]프론트엔드개발자모집(경력)
tags : #Webfront
url : https://careers.kakao.com/jobs/P-11796
title : [사내플랫폼개발]프론트엔드개발자모집(경력)
tags : #Webfront
url : https://careers.kakao.com/jobs/P-11890
title : [지도서비스/FE플랫폼팀]프론트엔드개발자모집(경력)
tags : #Webfront
url : https://careers.kakao.com/jobs/P-12014
title : [비즈니스서비스/FE플랫폼팀]프론트엔드개발자모집(경력)
tags : #Webfront
url : https://careers.kakao.com/jobs/P-12016
title : [포털/다음앱]콘텐츠플랫폼개발자모집(경력)
tags : #Server
url : https://careers.kakao.com/jobs/P-11671
title : [브런치]webbackend경력개발자모집
tags : #Webfront,#Server
url : https://careers.kakao.com/jobs/P-11322
title : [카카오톡]콘텐츠구독서비스개발자모집(경력)
tags : #DB,#Server
url : https://careers.kakao.com/jobs/P-11575
title : [카카오맵]검색/추천개발자모집
tags : #Algorithm/ML,#Algorithm/Ranking,#Server,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-12022
title : [동영상플랫폼]동영상패키징서버개발자모집
tags : #System,#Server
url : https://careers.kakao.com/jobs/P-12021
title : [포털서비스]AB테스트설계/분석데이터엔지니어및서버개발자모집(경력)
tags : #Cloud,#Hadoopecosystem,#Server,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11872
title : [카카오맵](경력)서버개발자모집
tags : #Server
url : https://careers.kakao.com/jobs/P-11953
title : 컨텐츠API서버개발자모집(경력)
tags : #Server
url : https://careers.kakao.com/jobs/P-11689?page=2
title : 카카오API플랫폼개발자모집(경력)
tags : #Webfront,#Server
url : https://careers.kakao.com/jobs/P-11698?page=2
title : [다음포털](경력)카카오미래미디어셀챗봇개발자모집
tags : #Server
url : https://careers.kakao.com/jobs/P-12017?page=2
title : 빅데이터활용분석플랫폼개발자모집
tags : #Hadoopecosystem,#Server,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-10682?page=2
title : AR/VRSDK개발자모집(경력)
tags : #Android,#iOS,#Algorithm/ML,#기타
url : https://careers.kakao.com/jobs/P-11971?page=2
title : 모니터링솔루션개발자모집(경력)
tags : #Android,#iOS,#Webfront,#Server
url : https://careers.kakao.com/jobs/P-11720?page=2
title : [멜론CIC]멜론iOS앱개발자모집
tags : #iOS
url : https://careers.kakao.com/jobs/P-11252?page=2
title : 카카오지갑/인증플랫폼서버개발자모집
tags : #Server
url : https://careers.kakao.com/jobs/P-11944?page=2
title : 카카오톡안드로이드클라이언트개발자모집(경력)
tags : #Android
url : https://careers.kakao.com/jobs/P-11713?page=2
title : [카카오스토리]개발자모집(서버)
tags : #Server
url : https://careers.kakao.com/jobs/P-11333?page=2
title : [카카오스토리]iOS개발자모집(경력)
tags : #iOS
url : https://careers.kakao.com/jobs/P-11967?page=2
title : 데이터전문가(모델러/분석가/엔지니어)모집
tags : #Algorithm/ML,#Algorithm/Ranking,#Hadoopecosystem,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-12003?page=2
title : 카카오톡/계정/메일서버개발자모집공고
tags : #Server
url : https://careers.kakao.com/jobs/P-11081?page=2
title : 카카오데이터의가치를발굴할데이터분석가모집(경력)
tags : #Algorithm/ML,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11899?page=2
title : 데이터엔지니어및사이언티스트(경력)
tags : #Algorithm/ML,#Hadoopecosystem,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11888?page=2
title : [멜론CIC]멜론PC개발팀윈도우개발자모집
tags : #Windows,#Webfront
url : https://careers.kakao.com/jobs/P-11922?page=3
title : [멜론CIC]멜론서버개발자모집
tags : #Server
url : https://careers.kakao.com/jobs/P-10885?page=3
title : 오픈소스관리서비스(OlivePlatform)개발자모집(경력)
tags : #Webfront,#Server
url : https://careers.kakao.com/jobs/P-11991?page=3
title : [데이터센터](경력/신입)카카오데이터센터DataScientist모집
tags : #Algorithm/ML,#Algorithm/Ranking,#Hadoopecosystem,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11984?page=3
title : 빅데이터플랫폼개발자모집
tags : #Hadoopecosystem,#Server
url : https://careers.kakao.com/jobs/P-11132?page=3
title : 카카오데이터분석플랫폼Frontend개발자모집
tags : #Webfront
url : https://careers.kakao.com/jobs/P-11498?page=3
title : 침해사고분석/대응담당자모집(경력)
tags : #Security,#System,#Cloud,#Network
url : https://careers.kakao.com/jobs/P-11986?page=3
title : 데이터정책및데이터자산관리담당자모집(경력)
tags : #Statistics/Analysis,#기타
url : https://careers.kakao.com/jobs/P-11843?page=3
title : 머신러닝엔지니어모집
tags : #Algorithm/ML,#Algorithm/Ranking,#Statistics/Analysis,#NLP
url : https://careers.kakao.com/jobs/P-11842?page=3
title : 데이터인프라담당자모집(경력)
tags : #Hadoopecosystem,#Server,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11841?page=3
title : 광고데이터플랫폼개발자모집
tags : #Webfront,#Server
url : https://careers.kakao.com/jobs/P-11770?page=3
title : 카카오재무시스템개발자모집
tags : #Webfront,#Server
url : https://careers.kakao.com/jobs/P-11166?page=3
title : 비즈개발실서버개발자모집(경력)
tags : #Hadoopecosystem,#Server
url : https://careers.kakao.com/jobs/P-10931?page=3
title : [동영상플랫폼]플랫폼서버개발자모집(경력)
tags : #Webfront,#Network,#System,#Server
url : https://careers.kakao.com/jobs/P-11977?page=3
title : 동영상스트리밍플랫폼개발자모집(경력)
tags : #System,#Cloud,#Server
url : https://careers.kakao.com/jobs/P-11973?page=3
title : 동영상그리드플랫폼개발자모집(경력)
tags : #Network,#System,#기타
url : https://careers.kakao.com/jobs/P-11974?page=4
title : 챗봇및상담플랫폼서버개발자모집
tags : #Hadoopecosystem,#Server
url : https://careers.kakao.com/jobs/P-11133?page=4
title : 추천시스템소프트웨어엔지니어
tags : #System,#Network,#Cloud,#DB,#Algorithm/ML,#Algorithm/Ranking,#Server
url : https://careers.kakao.com/jobs/P-10200?page=4
title : 추천통계분석/데이터사이언티스트
tags : #Algorithm/ML,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-10913?page=4
title : 빌링플랫폼개발자모집(경력)
tags : #Server
url : https://careers.kakao.com/jobs/P-11583?page=4
title : [브런치/티스토리]iOS앱개발자모집(경력)
tags : #iOS
url : https://careers.kakao.com/jobs/P-11965?page=4
title : [카카오맵]안드로이드지도API개발자모집
tags : #Android,#기타
url : https://careers.kakao.com/jobs/P-11966?page=4
title : 시스템엔지니어를모십니다.
tags : #System,#Network,#Cloud,#DB,#Security
url : https://careers.kakao.com/jobs/P-10266?page=4
title : 카카오전사QA모집(경력)
tags : #QA
url : https://careers.kakao.com/jobs/P-11723?page=4
title : 광고어뷰징방지Platform연구및개발
tags : #Algorithm/ML,#Algorithm/Ranking,#Hadoopecosystem,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-10249?page=4
title : 카카오SAPBC구축및운영채용(경력)
tags : #기타
url : https://careers.kakao.com/jobs/P-11902?page=4
title : 추천시스템연구/개발
tags : #Algorithm/ML,#Algorithm/Ranking,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-9883?page=4
title : 인사시스템개발자모집
tags : #Webfront,#Server
url : https://careers.kakao.com/jobs/P-9336?page=4
title : 인프라서비스플랫폼개발자모집
tags : #Webfront,#System,#Cloud,#Server
url : https://careers.kakao.com/jobs/P-11485?page=4
title : 업무지원시스템개발자모집
tags : #Webfront,#DB,#Server
url : https://careers.kakao.com/jobs/P-11515?page=4
title : PostgreSQL운영및데이터베이스관리자모집
tags : #DB,#Server
url : https://careers.kakao.com/jobs/P-10791?page=5
title : [멜론CIC]멜론상품구독&amp;마케팅서비스개발자모집(경력)
tags : #Server
url : https://careers.kakao.com/jobs/P-11375?page=5
title : 카카오댓글/투표/공감웹서비스개발자모집
tags : #Webfront,#Server
url : https://careers.kakao.com/jobs/P-11102?page=5
title : My구독서버개발자모집(경력)
tags : #Server
url : https://careers.kakao.com/jobs/P-11914?page=5
title : 스팸및어뷰징분석/대응시스템개발자모집(경력)
tags : #Server
url : https://careers.kakao.com/jobs/P-11736?page=5
title : 보안모니터링시스템개발및운영담당자모집(경력)
tags : #Security,#Cloud,#DB,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11877?page=5
title : 비즈플랫폼개발팀클라이언트개발자모집
tags : #Android,#iOS
url : https://careers.kakao.com/jobs/P-11164?page=5
title : [API플랫폼]테크니컬어카운트매니저(TechnicalAccountManager)경력직모집
tags : #Android,#iOS,#Webfront,#DB,#System,#Security,#Server
url : https://careers.kakao.com/jobs/P-11541?page=5
title : [티스토리/Daum블로그]Server경력개발자모집
tags : #Webfront,#Server
url : https://careers.kakao.com/jobs/P-11111?page=5
title : 클라우드플랫폼TechnicalProductManager
tags : #Cloud
url : https://careers.kakao.com/jobs/P-11893?page=5
title : 카카오분석플랫폼경력개발자모집
tags : #Server,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11396?page=5
title : 카카오서비스클라이언트Windows개발자모집(경력)
tags : #Windows
url : https://careers.kakao.com/jobs/P-11745?page=5
title : 동영상서비스/플랫폼서버개발자모집
tags : #Server
url : https://careers.kakao.com/jobs/P-11395?page=5
title : 동영상데이터/비즈플랫폼서버개발자모집
tags : #Server
url : https://careers.kakao.com/jobs/P-11430?page=5
title : 테크니컬라이터(TechnicalWriter),DocumentationEngineering모집(경력)
tags : #기타
url : https://careers.kakao.com/jobs/P-11766?page=5
title : KakaoTV동영상서비스모바일앱IOS개발자모집(경력)
tags : #iOS
url : https://careers.kakao.com/jobs/P-11735?page=6
title : 카카오에디터SDK개발자모집(iOS)
tags : #iOS
url : https://careers.kakao.com/jobs/P-11323?page=6
title : 사내계정플랫폼개발및운영담당자모집(경력)
tags : #Webfront,#DB,#Server
url : https://careers.kakao.com/jobs/P-11649?page=6
title : 카카오광고서비스알고리즘및시스템개발
tags : #Algorithm/Ranking
url : https://careers.kakao.com/jobs/P-11011?page=6
title : 카카오톡#탭,다음앱서비스앱개발자모집(Android,iOS)
tags : #Android,#iOS
url : https://careers.kakao.com/jobs/P-11095?page=6
title : [톡캘린더]서버개발자모집(경력)
tags : #Server
url : https://careers.kakao.com/jobs/P-11687?page=6
title : 데이터사이언티스트모집(경력)
tags : #Algorithm/ML,#Algorithm/Ranking,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11816?page=6
title : 융합기술개발자영입
tags : #Algorithm/ML
url : https://careers.kakao.com/jobs/P-10637?page=6
title : [카카오톡]macOS클라이언트개발자모집(경력)
tags : #iOS,#기타
url : https://careers.kakao.com/jobs/P-11797?page=6
title : 카카오톡보이스톡/페이스톡/라이브톡개발자모집
tags : #Android,#iOS,#Windows,#Webfront,#Server,#기타
url : https://careers.kakao.com/jobs/P-11082?page=6
title : 미래전략추진실데이터분석플랫폼개발자모집(경력)
tags : #Webfront,#Hadoopecosystem,#Server,#Statistics/Analysis
url : https://careers.kakao.com/jobs/P-11694?page=6
title : [KakaoTV]동영상서비스Frontend개발자모집(경력)
tags : #Webfront
url : https://careers.kakao.com/jobs/P-11783?page=6
title : 개발자를위한기술플랫폼엔지니어모집(경력)
tags : #Webfront,#Server
url : https://careers.kakao.com/jobs/P-11779?page=6
title : Hbase,mongoDB,kafka개발자모집(경력)
tags : #Server
url : https://careers.kakao.com/jobs/P-11677?page=6
title : 카카오톡QA모집
tags : #QA
url : https://careers.kakao.com/jobs/P-11348?page=6
title : [조기마감예정][Search] NLP 기술 개발 체험형 인턴십 모집
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005599&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : NAVER FINANCIAL 2021 상반기 경력 개발자 공채
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005943&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [Papago] 파파고 머신러닝(자연어처리) 엔지니어 체험형 인턴 모집
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005884&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [Platform Engineering] Front-end Engineer
tags : Platform Engineering,Software Development,Front-end,경력
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20003277&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [Platform Engineering] Server Engineer
tags : Platform Engineering,Software Development,Server,경력,Backend
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20002849&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [AR] Graphics Engineer
tags : AR,Graphics,경력,신입
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20003590&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [AR] AR Software Engineer
tags : AR,신입,경력
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005864&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 네이버 전사 장애/변경 관리자 경력사원 모집
tags : 장애,변경,ITIL,재발방지,모니터링
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005368&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : 네이버웹툰(유) SW 개발자(경력) 모집
tags : BE,FE,빅데이터플랫폼,안드로이드,iOS
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005947&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : 네이버웹툰(유) AI/ML 연구 개발자(경력) 모집
tags : 리서처,리서치엔지니어
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005948&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : Android 개발자 모집
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005944&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 인프라 보안 경력사원 모집
tags : 클라우드 보안,클라우드 인프라 보안,인프라 보안
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005698&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 개인정보보호 경력사원 모집
tags : 개인정보보호,클라우드 개인정보,클라우드 정보보호
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005699&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 서비스 보안 인증 대응 경력사원 모집
tags : 클라우드 보안,보안 인증,보안 컨설팅
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005322&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 RootCA 서비스 운영 경력사원 모집
tags : RootCA,SSL,PKI,WebTrust
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005324&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 보안 컨설팅 경력사원 모집
tags : 클라우드 보안 컨설팅,보안 아키텍트
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005325&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 보안 서비스 기획 경력사원 모집
tags : 보안 서비스,클라우드 보안 기획
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005326&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Infrastructure Security Engineer_오피스 보안 경력사원 모집
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005942&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] MYBOX Desktop Client 개발 경력사원 모집
tags : C,C++,C,Windows,Objecive-c
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005796&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] WORKBOX(파일공유) 서버 개발 경력사원 모집
tags : 백엔드,Java,Spring,ElasticSearch
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005798&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] WORKBOX(파일공유) 모바일 앱 개발 경력사원 모집
tags : 모바일,APP,iOS,Android
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005799&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 네이버 폼 신규 개발 경력사원 모집
tags : 프론트엔드,백엔드,Javascript,node.js,typescript
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005818&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 PaaS 상품 개발 (Backend) 경력사원 모집
tags : Backend,Java,Spring,Cloud,PaaS
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005402&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] PaaS-TA 서비스 개발 경력사원 모집
tags : Backend,Java,PaaS-TA,CloudFoundry,BOSH
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005403&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Kubernetes 서비스 개발 경력사원 모집
tags : Golang,kubernetes,CNI,Ansible
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005404&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Blockchain 서비스 개발 경력사원 모집
tags : Blockchain,Hyperledger,Kubernetes
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005405&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] API Gateway 서비스 개발 경력사원 모집
tags : Java,Spring,API Gateway,RESTful
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005406&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Data Analytics 서비스 개발 경력사원 모집
tags : Java,Spring,하둡,빅데이터,ELK
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005407&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Marketplace 서비스 개발 경력사원 모집
tags : Backend,Java,Spring
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005408&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] MLOps 서비스 개발 경력사원 모집
tags : Backend,Java,Kubeflow,Tensorflow,ML
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005409&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Object Storage 서비스 개발 경력사원 모집
tags : Backend,Java,C/C++,Storage
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005410&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Data Sandbox 서비스 개발 경력사원 모집
tags : Backend,Java,Spring
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005411&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] IoT 서비스 개발 경력사원 모집
tags : Backend
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005412&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Cloud Functions 서비스 개발 경력사원 모집
tags : Backend
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005414&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Video Conference 서비스 개발 경력사원 모집
tags : Backend,Java,Spring,WebRT,C Media
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005416&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 품질 보증 관리자 경력사원 모집
tags : QA,Test,Automation,Process
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005417&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 Portal 서비스 개발 (FE 직무) 경력사원 모집
tags : Frontend,Javascript,Typescript,vue.js
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005454&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 Console 서비스 개발 경력사원 모집
tags : Frontend,Javascript,Typescript,vue.js
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005456&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 상품 기술지원 엔지니어 경력사원 모집
tags : Technical support,System operator,기술지원
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005474&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 Portal 서비스 개발 (BE 직무) 경력사원 모집
tags : Backend,Java,Spring
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005739&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Cloud System Engineer 경력사원 모집
tags : system,engineer,Hypervisor,Linux,Windows
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005379&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Network Engineering 경력사원 모집
tags : Network,Routing,Switching
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005330&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] System Engineering 경력사원 모집
tags : Server. DevOps. Linux. KVM. Container
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005377&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 네트워크 운영 경력사원 모집
tags : 네트워크 가상화,MPLS VPN,EVPN,IPSecVPN
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005622&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 데이터센터 엔지니어(건축) 경력사원 모집
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005734&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Security Engineer_모의해킹 경력사원 모집
tags : 모의해킹,취약점,화이트해커,해킹,CVE
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005894&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Security Engineer_취약점 분석 경력사원 모집
tags : 취약점,보안점검,어플리케이션,소스코드
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005895&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 서비스 플랫폼 테크니컬 매니저 경력사원 모집
tags : Cloud Consulting,technical support,Platform 기획/관리,Customer care
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005309&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 SaaS 개발
tags : Java,Spring,ERP,그룹웨어
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005360&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Infra Security 경력사원 모집
tags : security,보안솔루션
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005362&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] CERT 경력사원 모집
tags : security,침해사고,cert
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005363&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 가상화 코어 기술 연구 및 개발 (하드웨어 분야) 경력사원 모집
tags : FPGA,Verilog,System Verilog
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005370&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 가상화 코어 기술 연구 및 개발 (소프트웨어 분야) 경력사원 모집
tags : 백엔드,Go,C/C++,가상화
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005373&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Naver Cloud Platform의 hypervisor orchestration 및 RESTful api 와 관리도구 개발 경력사원 모집
tags : java,go,python,shell script,linux
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005378&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 네이버클라우드 클라우드 데이터베이스 상품개발 (MSSQL) 경력사원 모집
tags : C,PowerShell,Cloud,Cloud DB,MSSQL
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005382&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 네이버클라우드 빅데이터플랫폼 상품개발 경력사원 모집
tags : Hadoop,Cloud,EMR,HDInsight,BigQuery
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005383&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] MySQL 데이터베이스 엔지니어 (DBA) 경력사원 모집
tags : MySQL,DBA,Database,데이터베이스,DB
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005384&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] PostgreSQL 데이터베이스 엔지니어 (DBA) 경력사원 모집
tags : PostgreSQL,DBA,Database,데이터베이스,DB
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005386&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] MongoDB 데이터베이스 엔지니어 (DBA) 경력사원 모집
tags : MongoDB,DBA,Database,데이터베이스
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005393&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 데이터베이스 엔지니어 (DBA) 경력사원 모집
tags : MySQL,Redis,Cloud,Cloud DB,DBA
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005394&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] Cloud 네트워크 솔루션 및 SDN 기술 개발 경력사원 모집
tags : Network,Golang,SDN
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005396&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 데이터 보호 서비스 개발 경력사원 모집
tags : Java,Spring,JPA,암호화
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005398&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 보안 서비스 개발 경력사원 모집
tags : Java,Spring,Javascript,보안
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005399&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] 클라우드 개발자 도구 서비스 개발 경력사원 모집
tags : Java,Node.js,Javascript,Typescript,DevOps
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005400&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] NAVER Cloud Platform 빌링 경력사원 모집
tags : 백엔드,java,미터링,빌링,Rest API
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005401&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : [NAVER Cloud] MYBOX 서버 개발 경력사원 모집
tags : 백엔드,Java,C++,Spring,ElasticSearch
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005267&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : 2021 WORKS MOBILE 경력사원 인재 Pool
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20003639&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : 네이버 월간영입 : 기술 직군(6월)
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005978&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : 정보 보안 담당자 모집
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005902&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : NAVER D2 Startup Factory 스타트업 투자담당 경력사원 모집
tags : D2,투자,경력
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005542&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : 프론트엔드 개발자 상시 모집 (경력 3년 이상)
tags : FE ,프론트엔드 ,상시지원 ,상시검토
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005030&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : 백엔드 개발자 상시 모집 (경력 3년 이상)
tags : BE ,백엔드 ,상시지원 ,상시검토
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005204&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
title : NAVER 기술플랫폼 전략 담당자 모집
tags :
url : https://recruit.navercorp.com/naver/job/detail/developer?annoId=20005897&amp;classId=&amp;jobId=&amp;entTypeCd=&amp;searchTxt=&amp;searchSysComCd=
......@@ -27,7 +27,8 @@ const makeObject = (array)=>{
else if (tempData.length == 4){
result.push({
title : tempData[0],
url : tempData[3]
url : tempData[3],
tags : []
})
}
}
......
......@@ -180,6 +180,18 @@
"node": ">= 0.8"
}
},
"node_modules/call-bind": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
"integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==",
"dependencies": {
"function-bind": "^1.1.1",
"get-intrinsic": "^1.0.2"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/cheerio": {
"version": "1.0.0-rc.9",
"resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.9.tgz",
......@@ -262,6 +274,18 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
},
"node_modules/cron-parser": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-3.5.0.tgz",
"integrity": "sha512-wyVZtbRs6qDfFd8ap457w3XVntdvqcwBGxBoTvJQH9KGVKL/fB+h2k3C8AqiVxvUQKN1Ps/Ns46CNViOpVDhfQ==",
"dependencies": {
"is-nan": "^1.3.2",
"luxon": "^1.26.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/css-select": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/css-select/-/css-select-4.1.2.tgz",
......@@ -304,6 +328,17 @@
"node": ">=0.10.0"
}
},
"node_modules/define-properties": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz",
"integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==",
"dependencies": {
"object-keys": "^1.0.12"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
......@@ -570,6 +605,24 @@
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8="
},
"node_modules/function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
"integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A=="
},
"node_modules/get-intrinsic": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz",
"integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==",
"dependencies": {
"function-bind": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.1"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-stream": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
......@@ -603,6 +656,28 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/has": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
"integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
"dependencies": {
"function-bind": "^1.1.1"
},
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/has-symbols": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz",
"integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/htmlparser2": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-6.1.0.tgz",
......@@ -721,6 +796,21 @@
"node": ">= 0.10"
}
},
"node_modules/is-nan": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/is-nan/-/is-nan-1.3.2.tgz",
"integrity": "sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w==",
"dependencies": {
"call-bind": "^1.0.0",
"define-properties": "^1.1.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-plain-object": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
......@@ -748,6 +838,19 @@
"node": ">=8"
}
},
"node_modules/long-timeout": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/long-timeout/-/long-timeout-0.1.1.tgz",
"integrity": "sha1-lyHXiLR+C8taJMLivuGg2lXatRQ="
},
"node_modules/luxon": {
"version": "1.27.0",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-1.27.0.tgz",
"integrity": "sha512-VKsFsPggTA0DvnxtJdiExAucKdAnwbCCNlMM5ENvHlxubqWd0xhZcdb4XgZ7QFNhaRhilXCFxHuoObP5BNA4PA==",
"engines": {
"node": "*"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
......@@ -847,6 +950,19 @@
"node": "4.x || >=6.0.0"
}
},
"node_modules/node-schedule": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/node-schedule/-/node-schedule-2.0.0.tgz",
"integrity": "sha512-cHc9KEcfiuXxYDU+HjsBVo2FkWL1jRAUoczFoMIzRBpOA4p/NRHuuLs85AWOLgKsHtSPjN8csvwIxc2SqMv+CQ==",
"dependencies": {
"cron-parser": "^3.1.0",
"long-timeout": "0.1.1",
"sorted-array-functions": "^1.3.0"
},
"engines": {
"node": ">=6"
}
},
"node_modules/nth-check": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.0.0.tgz",
......@@ -858,6 +974,14 @@
"url": "https://github.com/fb55/nth-check?sponsor=1"
}
},
"node_modules/object-keys": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
......@@ -1196,6 +1320,11 @@
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
"integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw=="
},
"node_modules/sorted-array-functions": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/sorted-array-functions/-/sorted-array-functions-1.3.0.tgz",
"integrity": "sha512-2sqgzeFlid6N4Z2fUQ1cvFmTOLRi/sEDzSQ0OKYchqgoPmQBVyM3959qYx3fpS6Esef80KjmpgPeEr028dP3OA=="
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
......
{
"root": true,
"extends": "@ljharb",
"rules": {
"func-name-matching": 0,
"id-length": 0,
"new-cap": [2, {
"capIsNewExceptions": [
"GetIntrinsic",
],
}],
"no-magic-numbers": 0,
"operator-linebreak": [2, "before"],
},
}
# These are supported funding model platforms
github: [ljharb]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: npm/call-bind
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"lines": 86,
"statements": 85.93,
"functions": 82.43,
"branches": 76.06,
"exclude": [
"coverage",
"test"
]
}
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.0.2](https://github.com/ljharb/call-bind/compare/v1.0.1...v1.0.2) - 2021-01-11
### Commits
- [Fix] properly include the receiver in the bound length [`dbae7bc`](https://github.com/ljharb/call-bind/commit/dbae7bc676c079a0d33c0a43e9ef92cb7b01345d)
## [v1.0.1](https://github.com/ljharb/call-bind/compare/v1.0.0...v1.0.1) - 2021-01-08
### Commits
- [Tests] migrate tests to Github Actions [`b6db284`](https://github.com/ljharb/call-bind/commit/b6db284c36f8ccd195b88a6764fe84b7223a0da1)
- [meta] do not publish github action workflow files [`ec7fe46`](https://github.com/ljharb/call-bind/commit/ec7fe46e60cfa4764ee943d2755f5e5a366e578e)
- [Fix] preserve original function’s length when possible [`adbceaa`](https://github.com/ljharb/call-bind/commit/adbceaa3cac4b41ea78bb19d7ccdbaaf7e0bdadb)
- [Tests] gather coverage data on every job [`d69e23c`](https://github.com/ljharb/call-bind/commit/d69e23cc65f101ba1d4c19bb07fa8eb0ec624be8)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`2fd3586`](https://github.com/ljharb/call-bind/commit/2fd3586c5d47b335364c14293114c6b625ae1f71)
- [Deps] update `get-intrinsic` [`f23e931`](https://github.com/ljharb/call-bind/commit/f23e9318cc271c2add8bb38cfded85ee7baf8eee)
- [Deps] update `get-intrinsic` [`72d9f44`](https://github.com/ljharb/call-bind/commit/72d9f44e184465ba8dd3fb48260bbcff234985f2)
- [meta] fix FUNDING.yml [`e723573`](https://github.com/ljharb/call-bind/commit/e723573438c5a68dcec31fb5d96ea6b7e4a93be8)
- [eslint] ignore coverage output [`15e76d2`](https://github.com/ljharb/call-bind/commit/15e76d28a5f43e504696401e5b31ebb78ee1b532)
- [meta] add Automatic Rebase and Require Allow Edits workflows [`8fa4dab`](https://github.com/ljharb/call-bind/commit/8fa4dabb23ba3dd7bb92c9571c1241c08b56e4b6)
## v1.0.0 - 2020-10-30
### Commits
- Initial commit [`306cf98`](https://github.com/ljharb/call-bind/commit/306cf98c7ec9e7ef66b653ec152277ac1381eb50)
- Tests [`e10d0bb`](https://github.com/ljharb/call-bind/commit/e10d0bbdadc7a10ecedc9a1c035112d3e368b8df)
- Implementation [`43852ed`](https://github.com/ljharb/call-bind/commit/43852eda0f187327b7fad2423ca972149a52bd65)
- npm init [`408f860`](https://github.com/ljharb/call-bind/commit/408f860b773a2f610805fd3613d0d71bac1b6249)
- [meta] add Automatic Rebase and Require Allow Edits workflows [`fb349b2`](https://github.com/ljharb/call-bind/commit/fb349b2e48defbec8b5ec8a8395cc8f69f220b13)
- [meta] add `auto-changelog` [`c4001fc`](https://github.com/ljharb/call-bind/commit/c4001fc43031799ef908211c98d3b0fb2b60fde4)
- [meta] add "funding"; create `FUNDING.yml` [`d4d6d29`](https://github.com/ljharb/call-bind/commit/d4d6d2974a14bc2e98830468eda7fe6d6a776717)
- [Tests] add `npm run lint` [`dedfb98`](https://github.com/ljharb/call-bind/commit/dedfb98bd0ecefb08ddb9a94061bd10cde4332af)
- Only apps should have lockfiles [`54ac776`](https://github.com/ljharb/call-bind/commit/54ac77653db45a7361dc153d2f478e743f110650)
- [meta] add `safe-publish-latest` [`9ea8e43`](https://github.com/ljharb/call-bind/commit/9ea8e435b950ce9b705559cd651039f9bf40140f)
MIT License
Copyright (c) 2020 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# call-bind
Robustly `.call.bind()` a function.
'use strict';
var GetIntrinsic = require('get-intrinsic');
var callBind = require('./');
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
'use strict';
var bind = require('function-bind');
var GetIntrinsic = require('get-intrinsic');
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
var $max = GetIntrinsic('%Math.max%');
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = null;
}
}
module.exports = function callBind(originalFunction) {
var func = $reflectApply(bind, $call, arguments);
if ($gOPD && $defineProperty) {
var desc = $gOPD(func, 'length');
if (desc.configurable) {
// original length, plus the receiver, minus any additional arguments (after the receiver)
$defineProperty(
func,
'length',
{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
);
}
}
return func;
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
{
"name": "call-bind",
"version": "1.0.2",
"description": "Robustly `.call.bind()` a function",
"main": "index.js",
"exports": {
".": [
{
"default": "./index.js"
},
"./index.js"
],
"./callBound": [
{
"default": "./callBound.js"
},
"./callBound.js"
],
"./package.json": "./package.json"
},
"scripts": {
"prepublish": "safe-publish-latest",
"lint": "eslint --ext=.js,.mjs .",
"pretest": "npm run lint",
"tests-only": "nyc tape 'test/*'",
"test": "npm run tests-only",
"posttest": "aud --production",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/ljharb/call-bind.git"
},
"keywords": [
"javascript",
"ecmascript",
"es",
"js",
"callbind",
"callbound",
"call",
"bind",
"bound",
"call-bind",
"call-bound",
"function",
"es-abstract"
],
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/ljharb/call-bind/issues"
},
"homepage": "https://github.com/ljharb/call-bind#readme",
"devDependencies": {
"@ljharb/eslint-config": "^17.3.0",
"aud": "^1.1.3",
"auto-changelog": "^2.2.1",
"eslint": "^7.17.0",
"nyc": "^10.3.2",
"safe-publish-latest": "^1.1.4",
"tape": "^5.1.1"
},
"dependencies": {
"function-bind": "^1.1.1",
"get-intrinsic": "^1.0.2"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
}
}
'use strict';
var test = require('tape');
var callBound = require('../callBound');
test('callBound', function (t) {
// static primitive
t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself');
t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself');
// static non-function object
t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself');
t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself');
t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself');
t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself');
// static function
t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself');
t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself');
// prototype primitive
t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself');
t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself');
// prototype function
t.notEqual(callBound('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString does not yield itself');
t.notEqual(callBound('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% does not yield itself');
t.equal(callBound('Object.prototype.toString')(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original');
t.equal(callBound('%Object.prototype.toString%')(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original');
t['throws'](
function () { callBound('does not exist'); },
SyntaxError,
'nonexistent intrinsic throws'
);
t['throws'](
function () { callBound('does not exist', true); },
SyntaxError,
'allowMissing arg still throws for unknown intrinsic'
);
/* globals WeakRef: false */
t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) {
st['throws'](
function () { callBound('WeakRef'); },
TypeError,
'real but absent intrinsic throws'
);
st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception');
st.end();
});
t.end();
});
'use strict';
var callBind = require('../');
var bind = require('function-bind');
var test = require('tape');
/*
* older engines have length nonconfigurable
* in io.js v3, it is configurable except on bound functions, hence the .bind()
*/
var functionsHaveConfigurableLengths = !!(
Object.getOwnPropertyDescriptor
&& Object.getOwnPropertyDescriptor(bind.call(function () {}), 'length').configurable
);
test('callBind', function (t) {
var sentinel = { sentinel: true };
var func = function (a, b) {
// eslint-disable-next-line no-invalid-this
return [this, a, b];
};
t.equal(func.length, 2, 'original function length is 2');
t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args');
t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args');
t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args');
var bound = callBind(func);
t.equal(bound.length, func.length + 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths });
t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with too few args');
t.deepEqual(bound(1, 2), [1, 2, undefined], 'bound func with right args');
t.deepEqual(bound(1, 2, 3), [1, 2, 3], 'bound func with too many args');
var boundR = callBind(func, sentinel);
t.equal(boundR.length, func.length, 'function length is preserved', { skip: !functionsHaveConfigurableLengths });
t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args');
t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args');
t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args');
var boundArg = callBind(func, sentinel, 1);
t.equal(boundArg.length, func.length - 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths });
t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args');
t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg');
t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args');
t.test('callBind.apply', function (st) {
var aBound = callBind.apply(func);
st.deepEqual(aBound(sentinel), [sentinel, undefined, undefined], 'apply-bound func with no args');
st.deepEqual(aBound(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args');
st.deepEqual(aBound(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args');
var aBoundArg = callBind.apply(func);
st.deepEqual(aBoundArg(sentinel, [1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with too many args');
st.deepEqual(aBoundArg(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args');
st.deepEqual(aBoundArg(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args');
var aBoundR = callBind.apply(func, sentinel);
st.deepEqual(aBoundR([1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with receiver and too many args');
st.deepEqual(aBoundR([1, 2], 4), [sentinel, 1, 2], 'apply-bound func with receiver and right args');
st.deepEqual(aBoundR([1], 4), [sentinel, 1, undefined], 'apply-bound func with receiver and too few args');
st.end();
});
t.end();
});
{
"rules": {
"eol-last": ["error", "always"],
"quotes": ["error", "single"],
"semi": ["error", "always"]
},
"overrides": [
{
"files": ["test/**.js"],
"parserOptions": {
"ecmaVersion": 6
}
}
]
}
language: node_js
node_js:
- '10'
- '12'
- '14'
- '15'
The MIT License (MIT)
Copyright (c) 2014-2016 Harri Siirak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
cron-parser
================
[![Build Status](https://travis-ci.com/harrisiirak/cron-parser.svg?branch=master)](https://travis-ci.com/harrisiirak/cron-parser)
[![NPM version](https://badge.fury.io/js/cron-parser.png)](http://badge.fury.io/js/cron-parser)
Node.js library for parsing and manipulating crontab instructions. It includes support for timezones and DST transitions.
__Compatibility__
Node >= 0.8
Typescript <= 4.2
Setup
========
```bash
npm install cron-parser
```
Supported format
========
```
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31, L)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, optional)
```
Supports mixed use of ranges and range increments (L and W characters are not supported currently). See tests for examples.
Usage
========
Simple expression.
```javascript
var parser = require('cron-parser');
try {
var interval = parser.parseExpression('*/2 * * * *');
console.log('Date: ', interval.next().toString()); // Sat Dec 29 2012 00:42:00 GMT+0200 (EET)
console.log('Date: ', interval.next().toString()); // Sat Dec 29 2012 00:44:00 GMT+0200 (EET)
console.log('Date: ', interval.prev().toString()); // Sat Dec 29 2012 00:42:00 GMT+0200 (EET)
console.log('Date: ', interval.prev().toString()); // Sat Dec 29 2012 00:40:00 GMT+0200 (EET)
} catch (err) {
console.log('Error: ' + err.message);
}
```
Iteration with limited timespan. Also returns ES6 compatible iterator (when iterator flag is set to true).
```javascript
var parser = require('cron-parser');
var options = {
currentDate: new Date('Wed, 26 Dec 2012 12:38:53 UTC'),
endDate: new Date('Wed, 26 Dec 2012 14:40:00 UTC'),
iterator: true
};
try {
var interval = parser.parseExpression('*/22 * * * *', options);
while (true) {
try {
var obj = interval.next();
console.log('value:', obj.value.toString(), 'done:', obj.done);
} catch (e) {
break;
}
}
// value: Wed Dec 26 2012 14:44:00 GMT+0200 (EET) done: false
// value: Wed Dec 26 2012 15:00:00 GMT+0200 (EET) done: false
// value: Wed Dec 26 2012 15:22:00 GMT+0200 (EET) done: false
// value: Wed Dec 26 2012 15:44:00 GMT+0200 (EET) done: false
// value: Wed Dec 26 2012 16:00:00 GMT+0200 (EET) done: false
// value: Wed Dec 26 2012 16:22:00 GMT+0200 (EET) done: true
} catch (err) {
console.log('Error: ' + err.message);
}
```
Timezone support
```javascript
var parser = require('cron-parser');
var options = {
currentDate: '2016-03-27 00:00:01',
tz: 'Europe/Athens'
};
try {
var interval = parser.parseExpression('0 * * * *', options);
console.log('Date: ', interval.next().toString()); // Date: Sun Mar 27 2016 01:00:00 GMT+0200
console.log('Date: ', interval.next().toString()); // Date: Sun Mar 27 2016 02:00:00 GMT+0200
console.log('Date: ', interval.next().toString()); // Date: Sun Mar 27 2016 04:00:00 GMT+0300 (Notice DST transition)
} catch (err) {
console.log('Error: ' + err.message);
}
```
Manipulation
```javascript
var parser = require('cron-parser');
var interval = parser.parseExpression('0 7 * * 0-4');
var fields = JSON.parse(JSON.stringify(interval.fields)); // Fields is immutable
fields.hour = [8];
fields.minute = [29];
fields.dayOfWeek = [1,3,4,5,6,7];
var modifiedInterval = parser.fieldsToExpression(fields);
var cronString = modifiedInterval.stringify();
console.log(cronString); // "29 8 * * 1,3-7"
```
Options
========
* *currentDate* - Start date of the iteration
* *endDate* - End date of the iteration
`currentDate` and `endDate` accept `string`, `integer` and `Date` as input.
In case of using `string` as input, not every string format accepted
by the `Date` constructor will work correctly. The supported formats are: [`ISO8601`](http://momentjs.com/docs/#/parsing/string/) and the older
[`ASP.NET JSON Date`](http://momentjs.com/docs/#/parsing/asp-net-json-date/) format. The reason being that those are the formats accepted by the
[`moment`](http://momentjs.com) library which is being used to handle dates.
Using `Date` as an input can be problematic specially when using the `tz` option. The issue being that, when creating a new `Date` object without
any timezone information, it will be created in the timezone of the system that is running the code. This (most of times) won't be what the user
will be expecting. Using one of the supported `string` formats will solve the issue(see timezone example).
* *iterator* - Return ES6 compatible iterator object
* *utc* - Enable UTC
* *tz* - Timezone string. It won't be used in case `utc` is enabled
{
"name": "cron-parser",
"repo": "harrisiirak/cron-parser",
"description": "Node.js library for parsing crontab instructions",
"version": "2.13.0",
"keywords": ["cron", "crontab", "parser"],
"dependencies": {},
"development": {},
"main": "lib/parser.js",
"scripts": ["lib/parser.js", "lib/expression.js", "lib/date.js", "lib/field_compactor.js", "lib/field_stringify.js"]
}
'use strict';
var luxon = require('luxon');
CronDate.prototype.addYear = function() {
this._date = this._date.plus({ years: 1 });
};
CronDate.prototype.addMonth = function() {
this._date = this._date.plus({ months: 1 }).startOf('month');
};
CronDate.prototype.addDay = function() {
this._date = this._date.plus({ days: 1 }).startOf('day');
};
CronDate.prototype.addHour = function() {
var prev = this._date;
this._date = this._date.plus({ hours: 1 }).startOf('hour');
if (this._date <= prev) {
this._date = this._date.plus({ hours: 1 });
}
};
CronDate.prototype.addMinute = function() {
var prev = this._date;
this._date = this._date.plus({ minutes: 1 }).startOf('minute');
if (this._date < prev) {
this._date = this._date.plus({ hours: 1 });
}
};
CronDate.prototype.addSecond = function() {
var prev = this._date;
this._date = this._date.plus({ seconds: 1 }).startOf('second');
if (this._date < prev) {
this._date = this._date.plus({ hours: 1 });
}
};
CronDate.prototype.subtractYear = function() {
this._date = this._date.minus({ years: 1 });
};
CronDate.prototype.subtractMonth = function() {
this._date = this._date
.minus({ months: 1 })
.endOf('month')
.startOf('second');
};
CronDate.prototype.subtractDay = function() {
this._date = this._date
.minus({ days: 1 })
.endOf('day')
.startOf('second');
};
CronDate.prototype.subtractHour = function() {
var prev = this._date;
this._date = this._date
.minus({ hours: 1 })
.endOf('hour')
.startOf('second');
if (this._date >= prev) {
this._date = this._date.minus({ hours: 1 });
}
};
CronDate.prototype.subtractMinute = function() {
var prev = this._date;
this._date = this._date.minus({ minutes: 1 })
.endOf('minute')
.startOf('second');
if (this._date > prev) {
this._date = this._date.minus({ hours: 1 });
}
};
CronDate.prototype.subtractSecond = function() {
var prev = this._date;
this._date = this._date
.minus({ seconds: 1 })
.startOf('second');
if (this._date > prev) {
this._date = this._date.minus({ hours: 1 });
}
};
CronDate.prototype.getDate = function() {
return this._date.day;
};
CronDate.prototype.getFullYear = function() {
return this._date.year;
};
CronDate.prototype.getDay = function() {
var weekday = this._date.weekday;
return weekday == 7 ? 0 : weekday;
};
CronDate.prototype.getMonth = function() {
return this._date.month - 1;
};
CronDate.prototype.getHours = function() {
return this._date.hour;
};
CronDate.prototype.getMinutes = function() {
return this._date.minute;
};
CronDate.prototype.getSeconds = function() {
return this._date.second;
};
CronDate.prototype.getMilliseconds = function() {
return this._date.millisecond;
};
CronDate.prototype.getTime = function() {
return this._date.valueOf();
};
CronDate.prototype.getUTCDate = function() {
return this._getUTC().day;
};
CronDate.prototype.getUTCFullYear = function() {
return this._getUTC().year;
};
CronDate.prototype.getUTCDay = function() {
var weekday = this._getUTC().weekday;
return weekday == 7 ? 0 : weekday;
};
CronDate.prototype.getUTCMonth = function() {
return this._getUTC().month - 1;
};
CronDate.prototype.getUTCHours = function() {
return this._getUTC().hour;
};
CronDate.prototype.getUTCMinutes = function() {
return this._getUTC().minute;
};
CronDate.prototype.getUTCSeconds = function() {
return this._getUTC().second;
};
CronDate.prototype.toISOString = function() {
return this._date.toUTC().toISO();
};
CronDate.prototype.toJSON = function() {
return this._date.toJSON();
};
CronDate.prototype.setDate = function(d) {
this._date = this._date.set({ day: d });
};
CronDate.prototype.setFullYear = function(y) {
this._date = this._date.set({ year: y });
};
CronDate.prototype.setDay = function(d) {
this._date = this._date.set({ weekday: d });
};
CronDate.prototype.setMonth = function(m) {
this._date = this._date.set({ month: m + 1 });
};
CronDate.prototype.setHours = function(h) {
this._date = this._date.set({ hour: h });
};
CronDate.prototype.setMinutes = function(m) {
this._date = this._date.set({ minute: m });
};
CronDate.prototype.setSeconds = function(s) {
this._date = this._date.set({ second: s });
};
CronDate.prototype.setMilliseconds = function(s) {
this._date = this._date.set({ millisecond: s });
};
CronDate.prototype._getUTC = function() {
return this._date.toUTC();
};
CronDate.prototype.toString = function() {
return this.toDate().toString();
};
CronDate.prototype.toDate = function() {
return this._date.toJSDate();
};
CronDate.prototype.isLastDayOfMonth = function() {
//next day
var newDate = this._date.plus({ days: 1 }).startOf('day');
return this._date.month !== newDate.month;
};
function CronDate (timestamp, tz) {
var dateOpts = { zone: tz };
if (!timestamp) {
this._date = luxon.DateTime.local();
} else if (timestamp instanceof CronDate) {
this._date = timestamp._date;
} else if (timestamp instanceof Date) {
this._date = luxon.DateTime.fromJSDate(timestamp, dateOpts);
} else if (typeof timestamp === 'number') {
this._date = luxon.DateTime.fromMillis(timestamp, dateOpts);
} else if (typeof timestamp === 'string') {
this._date = luxon.DateTime.fromISO(timestamp, dateOpts);
this._date.isValid || (this._date = luxon.DateTime.fromRFC2822(timestamp, dateOpts));
this._date.isValid || (this._date = luxon.DateTime.fromSQL(timestamp, dateOpts));
// RFC2822-like format without the required timezone offset (used in tests)
this._date.isValid || (this._date = luxon.DateTime.fromFormat(timestamp, 'EEE, d MMM yyyy HH:mm:ss', dateOpts));
}
if (!this._date || !this._date.isValid) {
throw new Error('CronDate: unhandled timestamp: ' + JSON.stringify(timestamp));
}
if (tz && tz !== this._date.zoneName) {
this._date = this._date.setZone(tz);
}
}
module.exports = CronDate;
'use strict';
// Load Date class extensions
var CronDate = require('./date');
// Get Number.isNaN or the polyfill
var safeIsNaN = require('is-nan');
var stringifyField = require('./field_stringify');
/**
* Cron iteration loop safety limit
*/
var LOOP_LIMIT = 10000;
/**
* Construct a new expression parser
*
* Options:
* currentDate: iterator start date
* endDate: iterator end date
*
* @constructor
* @private
* @param {Object} fields Expression fields parsed values
* @param {Object} options Parser options
*/
function CronExpression (fields, options) {
this._options = options;
this._utc = options.utc || false;
this._tz = this._utc ? 'UTC' : options.tz;
this._currentDate = new CronDate(options.currentDate, this._tz);
this._startDate = options.startDate ? new CronDate(options.startDate, this._tz) : null;
this._endDate = options.endDate ? new CronDate(options.endDate, this._tz) : null;
this._isIterator = options.iterator || false;
this._hasIterated = false;
this._nthDayOfWeek = options.nthDayOfWeek || 0;
this.fields = CronExpression._freezeFields(fields);
}
/**
* Field mappings
* @type {Array}
*/
CronExpression.map = [ 'second', 'minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek' ];
/**
* Prefined intervals
* @type {Object}
*/
CronExpression.predefined = {
'@yearly': '0 0 1 1 *',
'@monthly': '0 0 1 * *',
'@weekly': '0 0 * * 0',
'@daily': '0 0 * * *',
'@hourly': '0 * * * *'
};
/**
* Fields constraints
* @type {Array}
*/
CronExpression.constraints = [
{ min: 0, max: 59, chars: [] }, // Second
{ min: 0, max: 59, chars: [] }, // Minute
{ min: 0, max: 23, chars: [] }, // Hour
{ min: 1, max: 31, chars: ['L'] }, // Day of month
{ min: 1, max: 12, chars: [] }, // Month
{ min: 0, max: 7, chars: [] }, // Day of week
];
/**
* Days in month
* @type {number[]}
*/
CronExpression.daysInMonth = [
31,
29,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
/**
* Field aliases
* @type {Object}
*/
CronExpression.aliases = {
month: {
jan: 1,
feb: 2,
mar: 3,
apr: 4,
may: 5,
jun: 6,
jul: 7,
aug: 8,
sep: 9,
oct: 10,
nov: 11,
dec: 12
},
dayOfWeek: {
sun: 0,
mon: 1,
tue: 2,
wed: 3,
thu: 4,
fri: 5,
sat: 6
}
};
/**
* Field defaults
* @type {Array}
*/
CronExpression.parseDefaults = [ '0', '*', '*', '*', '*', '*' ];
CronExpression.standardValidCharacters = /^[\d|/|*|\-|,]+$/;
CronExpression.dayOfWeekValidCharacters = /^[\d|/|*|\-|,|\?]+$/;
CronExpression.dayOfMonthValidCharacters = /^[\d|L|/|*|\-|,|\?]+$/;
CronExpression.validCharacters = {
second: CronExpression.standardValidCharacters,
minute: CronExpression.standardValidCharacters,
hour: CronExpression.standardValidCharacters,
dayOfMonth: CronExpression.dayOfMonthValidCharacters,
month: CronExpression.standardValidCharacters,
dayOfWeek: CronExpression.dayOfWeekValidCharacters,
};
/**
* Parse input interval
*
* @param {String} field Field symbolic name
* @param {String} value Field value
* @param {Array} constraints Range upper and lower constraints
* @return {Array} Sequence of sorted values
* @private
*/
CronExpression._parseField = function _parseField (field, value, constraints) {
// Replace aliases
switch (field) {
case 'month':
case 'dayOfWeek':
var aliases = CronExpression.aliases[field];
value = value.replace(/[a-z]{1,3}/gi, function(match) {
match = match.toLowerCase();
if (typeof aliases[match] !== 'undefined') {
return aliases[match];
} else {
throw new Error('Validation error, cannot resolve alias "' + match + '"');
}
});
break;
}
// Check for valid characters.
if (!(CronExpression.validCharacters[field].test(value))) {
throw new Error('Invalid characters, got value: ' + value);
}
// Replace '*' and '?'
if (value.indexOf('*') !== -1) {
value = value.replace(/\*/g, constraints.min + '-' + constraints.max);
} else if (value.indexOf('?') !== -1) {
value = value.replace(/\?/g, constraints.min + '-' + constraints.max);
}
//
// Inline parsing functions
//
// Parser path:
// - parseSequence
// - parseRepeat
// - parseRange
/**
* Parse sequence
*
* @param {String} val
* @return {Array}
* @private
*/
function parseSequence (val) {
var stack = [];
function handleResult (result) {
if (result instanceof Array) { // Make sequence linear
for (var i = 0, c = result.length; i < c; i++) {
var value = result[i];
if (typeof value === 'string' && constraints.chars.indexOf(value) > -1) {
stack.push(value);
continue;
}
// Check constraints
if (typeof value !== 'number' || safeIsNaN(value) || value < constraints.min || value > constraints.max) {
throw new Error(
'Constraint error, got value ' + value + ' expected range ' +
constraints.min + '-' + constraints.max
);
}
stack.push(value);
}
} else { // Scalar value
if (typeof result === 'string' && constraints.chars.indexOf(result) > -1) {
stack.push(result);
return;
}
var numResult = +result;
// Check constraints
if (safeIsNaN(numResult) || numResult < constraints.min || numResult > constraints.max) {
throw new Error(
'Constraint error, got value ' + result + ' expected range ' +
constraints.min + '-' + constraints.max
);
}
if (field === 'dayOfWeek') {
numResult = numResult % 7;
}
stack.push(numResult);
}
}
var atoms = val.split(',');
if (!atoms.every(function (atom) {
return atom.length > 0;
})) {
throw new Error('Invalid list value format');
}
if (atoms.length > 1) {
for (var i = 0, c = atoms.length; i < c; i++) {
handleResult(parseRepeat(atoms[i]));
}
} else {
handleResult(parseRepeat(val));
}
stack.sort(CronExpression._sortCompareFn);
return stack;
}
/**
* Parse repetition interval
*
* @param {String} val
* @return {Array}
*/
function parseRepeat (val) {
var repeatInterval = 1;
var atoms = val.split('/');
if (atoms.length > 1) {
if (atoms[0] == +atoms[0]) {
atoms = [atoms[0] + '-' + constraints.max, atoms[1]];
}
return parseRange(atoms[0], atoms[atoms.length - 1]);
}
return parseRange(val, repeatInterval);
}
/**
* Parse range
*
* @param {String} val
* @param {Number} repeatInterval Repetition interval
* @return {Array}
* @private
*/
function parseRange (val, repeatInterval) {
var stack = [];
var atoms = val.split('-');
if (atoms.length > 1 ) {
// Invalid range, return value
if (atoms.length < 2) {
return +val;
}
if (!atoms[0].length) {
if (!atoms[1].length) {
throw new Error('Invalid range: ' + val);
}
return +val;
}
// Validate range
var min = +atoms[0];
var max = +atoms[1];
if (safeIsNaN(min) || safeIsNaN(max) ||
min < constraints.min || max > constraints.max) {
throw new Error(
'Constraint error, got range ' +
min + '-' + max +
' expected range ' +
constraints.min + '-' + constraints.max
);
} else if (min >= max) {
throw new Error('Invalid range: ' + val);
}
// Create range
var repeatIndex = +repeatInterval;
if (safeIsNaN(repeatIndex) || repeatIndex <= 0) {
throw new Error('Constraint error, cannot repeat at every ' + repeatIndex + ' time.');
}
for (var index = min, count = max; index <= count; index++) {
if (repeatIndex > 0 && (repeatIndex % repeatInterval) === 0) {
repeatIndex = 1;
stack.push(index);
} else {
repeatIndex++;
}
}
return stack;
}
return safeIsNaN(+val) ? val : +val;
}
return parseSequence(value);
};
CronExpression._sortCompareFn = function(a, b) {
var aIsNumber = typeof a === 'number';
var bIsNumber = typeof b === 'number';
if (aIsNumber && bIsNumber) {
return a - b;
}
if (!aIsNumber && bIsNumber) {
return 1;
}
if (aIsNumber && !bIsNumber) {
return -1;
}
return a.localeCompare(b);
};
CronExpression._handleMaxDaysInMonth = function(mappedFields) {
// Filter out any day of month value that is larger than given month expects
if (mappedFields.month.length === 1) {
var daysInMonth = CronExpression.daysInMonth[mappedFields.month[0] - 1];
if (mappedFields.dayOfMonth[0] > daysInMonth) {
throw new Error('Invalid explicit day of month definition');
}
return mappedFields.dayOfMonth
.filter(function(dayOfMonth) {
return dayOfMonth === 'L' ? true : dayOfMonth <= daysInMonth;
})
.sort(CronExpression._sortCompareFn);
}
};
CronExpression._freezeFields = function(fields) {
for (var i = 0, c = CronExpression.map.length; i < c; ++i) {
var field = CronExpression.map[i]; // Field name
var value = fields[field];
fields[field] = Object.freeze(value);
}
return Object.freeze(fields);
};
CronExpression.prototype._applyTimezoneShift = function(currentDate, dateMathVerb, method) {
if ((method === 'Month') || (method === 'Day')) {
var prevTime = currentDate.getTime();
currentDate[dateMathVerb + method]();
var currTime = currentDate.getTime();
if (prevTime === currTime) {
// Jumped into a not existent date due to a DST transition
if ((currentDate.getMinutes() === 0) &&
(currentDate.getSeconds() === 0)) {
currentDate.addHour();
} else if ((currentDate.getMinutes() === 59) &&
(currentDate.getSeconds() === 59)) {
currentDate.subtractHour();
}
}
} else {
var previousHour = currentDate.getHours();
currentDate[dateMathVerb + method]();
var currentHour = currentDate.getHours();
var diff = currentHour - previousHour;
if (diff === 2) {
// Starting DST
if (this.fields.hour.length !== 24) {
// Hour is specified
this._dstStart = currentHour;
}
} else if ((diff === 0) &&
(currentDate.getMinutes() === 0) &&
(currentDate.getSeconds() === 0)) {
// Ending DST
if (this.fields.hour.length !== 24) {
// Hour is specified
this._dstEnd = currentHour;
}
}
}
};
/**
* Find next or previous matching schedule date
*
* @return {CronDate}
* @private
*/
CronExpression.prototype._findSchedule = function _findSchedule (reverse) {
/**
* Match field value
*
* @param {String} value
* @param {Array} sequence
* @return {Boolean}
* @private
*/
function matchSchedule (value, sequence) {
for (var i = 0, c = sequence.length; i < c; i++) {
if (sequence[i] >= value) {
return sequence[i] === value;
}
}
return sequence[0] === value;
}
/**
* Helps determine if the provided date is the correct nth occurence of the
* desired day of week.
*
* @param {CronDate} date
* @param {Number} nthDayOfWeek
* @return {Boolean}
* @private
*/
function isNthDayMatch(date, nthDayOfWeek) {
if (nthDayOfWeek < 6) {
if (
date.getDate() < 8 &&
nthDayOfWeek === 1 // First occurence has to happen in first 7 days of the month
) {
return true;
}
var offset = date.getDate() % 7 ? 1 : 0; // Math is off by 1 when dayOfWeek isn't divisible by 7
var adjustedDate = date.getDate() - (date.getDate() % 7); // find the first occurance
var occurrence = Math.floor(adjustedDate / 7) + offset;
return occurrence === nthDayOfWeek;
}
return false;
}
/**
* Helper function that checks if 'L' is in the array
*
* @param {Array} dayOfMonth
*/
function isLInDayOfMonth(dayOfMonth) {
return dayOfMonth.length > 0 && dayOfMonth.indexOf('L') >= 0;
}
// Whether to use backwards directionality when searching
reverse = reverse || false;
var dateMathVerb = reverse ? 'subtract' : 'add';
var currentDate = new CronDate(this._currentDate, this._tz);
var startDate = this._startDate;
var endDate = this._endDate;
// Find matching schedule
var startTimestamp = currentDate.getTime();
var stepCount = 0;
while (stepCount < LOOP_LIMIT) {
stepCount++;
// Validate timespan
if (reverse) {
if (startDate && (currentDate.getTime() - startDate.getTime() < 0)) {
throw new Error('Out of the timespan range');
}
} else {
if (endDate && (endDate.getTime() - currentDate.getTime()) < 0) {
throw new Error('Out of the timespan range');
}
}
// Day of month and week matching:
//
// "The day of a command's execution can be specified by two fields --
// day of month, and day of week. If both fields are restricted (ie,
// aren't *), the command will be run when either field matches the cur-
// rent time. For example, "30 4 1,15 * 5" would cause a command to be
// run at 4:30 am on the 1st and 15th of each month, plus every Friday."
//
// http://unixhelp.ed.ac.uk/CGI/man-cgi?crontab+5
//
var dayOfMonthMatch = matchSchedule(currentDate.getDate(), this.fields.dayOfMonth);
if (isLInDayOfMonth(this.fields.dayOfMonth)) {
dayOfMonthMatch = dayOfMonthMatch || currentDate.isLastDayOfMonth();
}
var dayOfWeekMatch = matchSchedule(currentDate.getDay(), this.fields.dayOfWeek);
var isDayOfMonthWildcardMatch = this.fields.dayOfMonth.length >= CronExpression.daysInMonth[currentDate.getMonth()];
var isDayOfWeekWildcardMatch = this.fields.dayOfWeek.length === CronExpression.constraints[5].max - CronExpression.constraints[5].min + 1;
var currentHour = currentDate.getHours();
// Add or subtract day if select day not match with month (according to calendar)
if (!dayOfMonthMatch && !dayOfWeekMatch) {
this._applyTimezoneShift(currentDate, dateMathVerb, 'Day');
continue;
}
// Add or subtract day if not day of month is set (and no match) and day of week is wildcard
if (!isDayOfMonthWildcardMatch && isDayOfWeekWildcardMatch && !dayOfMonthMatch) {
this._applyTimezoneShift(currentDate, dateMathVerb, 'Day');
continue;
}
// Add or subtract day if not day of week is set (and no match) and day of month is wildcard
if (isDayOfMonthWildcardMatch && !isDayOfWeekWildcardMatch && !dayOfWeekMatch) {
this._applyTimezoneShift(currentDate, dateMathVerb, 'Day');
continue;
}
// Add or subtract day if day of week & nthDayOfWeek are set (and no match)
if (
this._nthDayOfWeek > 0 &&
!isNthDayMatch(currentDate, this._nthDayOfWeek)
) {
this._applyTimezoneShift(currentDate, dateMathVerb, 'Day');
continue;
}
// Match month
if (!matchSchedule(currentDate.getMonth() + 1, this.fields.month)) {
this._applyTimezoneShift(currentDate, dateMathVerb, 'Month');
continue;
}
// Match hour
if (!matchSchedule(currentHour, this.fields.hour)) {
if (this._dstStart !== currentHour) {
this._dstStart = null;
this._applyTimezoneShift(currentDate, dateMathVerb, 'Hour');
continue;
} else if (!matchSchedule(currentHour - 1, this.fields.hour)) {
currentDate[dateMathVerb + 'Hour']();
continue;
}
} else if (this._dstEnd === currentHour) {
if (!reverse) {
this._dstEnd = null;
this._applyTimezoneShift(currentDate, 'add', 'Hour');
continue;
}
}
// Match minute
if (!matchSchedule(currentDate.getMinutes(), this.fields.minute)) {
this._applyTimezoneShift(currentDate, dateMathVerb, 'Minute');
continue;
}
// Match second
if (!matchSchedule(currentDate.getSeconds(), this.fields.second)) {
this._applyTimezoneShift(currentDate, dateMathVerb, 'Second');
continue;
}
// Increase a second in case in the first iteration the currentDate was not
// modified
if (startTimestamp === currentDate.getTime()) {
if ((dateMathVerb === 'add') || (currentDate.getMilliseconds() === 0)) {
this._applyTimezoneShift(currentDate, dateMathVerb, 'Second');
} else {
currentDate.setMilliseconds(0);
}
continue;
}
break;
}
if (stepCount >= LOOP_LIMIT) {
throw new Error('Invalid expression, loop limit exceeded');
}
this._currentDate = new CronDate(currentDate, this._tz);
this._hasIterated = true;
return currentDate;
};
/**
* Find next suitable date
*
* @public
* @return {CronDate|Object}
*/
CronExpression.prototype.next = function next () {
var schedule = this._findSchedule();
// Try to return ES6 compatible iterator
if (this._isIterator) {
return {
value: schedule,
done: !this.hasNext()
};
}
return schedule;
};
/**
* Find previous suitable date
*
* @public
* @return {CronDate|Object}
*/
CronExpression.prototype.prev = function prev () {
var schedule = this._findSchedule(true);
// Try to return ES6 compatible iterator
if (this._isIterator) {
return {
value: schedule,
done: !this.hasPrev()
};
}
return schedule;
};
/**
* Check if next suitable date exists
*
* @public
* @return {Boolean}
*/
CronExpression.prototype.hasNext = function() {
var current = this._currentDate;
var hasIterated = this._hasIterated;
try {
this._findSchedule();
return true;
} catch (err) {
return false;
} finally {
this._currentDate = current;
this._hasIterated = hasIterated;
}
};
/**
* Check if previous suitable date exists
*
* @public
* @return {Boolean}
*/
CronExpression.prototype.hasPrev = function() {
var current = this._currentDate;
var hasIterated = this._hasIterated;
try {
this._findSchedule(true);
return true;
} catch (err) {
return false;
} finally {
this._currentDate = current;
this._hasIterated = hasIterated;
}
};
/**
* Iterate over expression iterator
*
* @public
* @param {Number} steps Numbers of steps to iterate
* @param {Function} callback Optional callback
* @return {Array} Array of the iterated results
*/
CronExpression.prototype.iterate = function iterate (steps, callback) {
var dates = [];
if (steps >= 0) {
for (var i = 0, c = steps; i < c; i++) {
try {
var item = this.next();
dates.push(item);
// Fire the callback
if (callback) {
callback(item, i);
}
} catch (err) {
break;
}
}
} else {
for (var i = 0, c = steps; i > c; i--) {
try {
var item = this.prev();
dates.push(item);
// Fire the callback
if (callback) {
callback(item, i);
}
} catch (err) {
break;
}
}
}
return dates;
};
/**
* Reset expression iterator state
*
* @public
*/
CronExpression.prototype.reset = function reset (newDate) {
this._currentDate = new CronDate(newDate || this._options.currentDate);
};
/**
* Stringify the expression
*
* @public
* @param {Boolean} [includeSeconds] Should stringify seconds
* @return {String}
*/
CronExpression.prototype.stringify = function stringify(includeSeconds) {
var resultArr = [];
for (var i = includeSeconds ? 0 : 1, c = CronExpression.map.length; i < c; ++i) {
var field = CronExpression.map[i];
var value = this.fields[field];
var constraint = CronExpression.constraints[i];
resultArr.push(stringifyField(value, constraint.min, constraint.max));
}
return resultArr.join(' ');
};
/**
* Parse input expression (async)
*
* @public
* @param {String} expression Input expression
* @param {Object} [options] Parsing options
*/
CronExpression.parse = function parse(expression, options) {
var self = this;
if (typeof options === 'function') {
options = {};
}
function parse (expression, options) {
if (!options) {
options = {};
}
if (typeof options.currentDate === 'undefined') {
options.currentDate = new CronDate(undefined, self._tz);
}
// Is input expression predefined?
if (CronExpression.predefined[expression]) {
expression = CronExpression.predefined[expression];
}
// Split fields
var fields = [];
var atoms = (expression + '').trim().split(/\s+/);
if (atoms.length > 6) {
throw new Error('Invalid cron expression');
}
// Resolve fields
var start = (CronExpression.map.length - atoms.length);
for (var i = 0, c = CronExpression.map.length; i < c; ++i) {
var field = CronExpression.map[i]; // Field name
var value = atoms[atoms.length > c ? i : i - start]; // Field value
if (i < start || !value) { // Use default value
fields.push(CronExpression._parseField(
field,
CronExpression.parseDefaults[i],
CronExpression.constraints[i]
)
);
} else {
var val = field === 'dayOfWeek' ? parseNthDay(value) : value;
fields.push(CronExpression._parseField(
field,
val,
CronExpression.constraints[i]
)
);
}
}
var mappedFields = {};
for (var i = 0, c = CronExpression.map.length; i < c; i++) {
var key = CronExpression.map[i];
mappedFields[key] = fields[i];
}
var dayOfMonth = CronExpression._handleMaxDaysInMonth(mappedFields);
mappedFields.dayOfMonth = dayOfMonth || mappedFields.dayOfMonth;
return new CronExpression(mappedFields, options);
/**
* Parses out the # special character for the dayOfWeek field & adds it to options.
*
* @param {String} val
* @return {String}
* @private
*/
function parseNthDay(val) {
var atoms = val.split('#');
if (atoms.length > 1) {
var nthValue = +atoms[atoms.length - 1];
if(/,/.test(val)) {
throw new Error('Constraint error, invalid dayOfWeek `#` and `,` '
+ 'special characters are incompatible');
}
if(/\//.test(val)) {
throw new Error('Constraint error, invalid dayOfWeek `#` and `/` '
+ 'special characters are incompatible');
}
if(/-/.test(val)) {
throw new Error('Constraint error, invalid dayOfWeek `#` and `-` '
+ 'special characters are incompatible');
}
if (atoms.length > 2 || safeIsNaN(nthValue) || (nthValue < 1 || nthValue > 5)) {
throw new Error('Constraint error, invalid dayOfWeek occurrence number (#)');
}
options.nthDayOfWeek = nthValue;
return atoms[0];
}
return val;
}
}
return parse(expression, options);
};
/**
* Convert cron fields back to Cron Expression
*
* @public
* @param {Object} fields Input fields
* @param {Object} [options] Parsing options
* @return {Object}
*/
CronExpression.fieldsToExpression = function fieldsToExpression(fields, options) {
function validateConstraints (field, values, constraints) {
if (!values) {
throw new Error('Validation error, Field ' + field + ' is missing');
}
if (values.length === 0) {
throw new Error('Validation error, Field ' + field + ' contains no values');
}
for (var i = 0, c = values.length; i < c; i++) {
var value = values[i];
if (typeof value === 'string' && constraints.chars.indexOf(value) > -1) {
continue;
}
// Check constraints
if (typeof value !== 'number' || safeIsNaN(value) || value < constraints.min || value > constraints.max) {
throw new Error(
'Constraint error, got value ' + value + ' expected range ' +
constraints.min + '-' + constraints.max
);
}
}
}
var mappedFields = {};
for (var i = 0, c = CronExpression.map.length; i < c; ++i) {
var field = CronExpression.map[i]; // Field name
var values = fields[field];
validateConstraints(
field,
values,
CronExpression.constraints[i]
);
var copy = [];
var j = -1;
while (++j < values.length) {
copy[j] = values[j];
}
values = copy.sort(CronExpression._sortCompareFn)
.filter(function(item, pos, ary) {
return !pos || item !== ary[pos - 1];
});
if (values.length !== copy.length) {
throw new Error('Validation error, Field ' + field + ' contains duplicate values');
}
mappedFields[field] = values;
}
var dayOfMonth = CronExpression._handleMaxDaysInMonth(mappedFields);
mappedFields.dayOfMonth = dayOfMonth || mappedFields.dayOfMonth;
return new CronExpression(mappedFields, options || {});
};
module.exports = CronExpression;
'use strict';
function buildRange(item) {
return {
start: item,
count: 1
};
}
function completeRangeWithItem(range, item) {
range.end = item;
range.step = item - range.start;
range.count = 2;
}
function finalizeCurrentRange(results, currentRange, currentItemRange) {
if (currentRange) {
// Two elements do not form a range so split them into 2 single elements
if (currentRange.count === 2) {
results.push(buildRange(currentRange.start));
results.push(buildRange(currentRange.end));
} else {
results.push(currentRange);
}
}
if (currentItemRange) {
results.push(currentItemRange);
}
}
function compactField(arr) {
var results = [];
var currentRange = undefined;
for (var i = 0; i < arr.length; i++) {
var currentItem = arr[i];
if (typeof currentItem !== 'number') {
// String elements can't form a range
finalizeCurrentRange(results, currentRange, buildRange(currentItem));
currentRange = undefined;
} else if (!currentRange) {
// Start a new range
currentRange = buildRange(currentItem);
} else if (currentRange.count === 1) {
// Guess that the current item starts a range
completeRangeWithItem(currentRange, currentItem);
} else {
if (currentRange.step === currentItem - currentRange.end) {
// We found another item that matches the current range
currentRange.count++;
currentRange.end = currentItem;
} else if (currentRange.count === 2) { // The current range can't be continued
// Break the first item of the current range into a single element, and try to start a new range with the second item
results.push(buildRange(currentRange.start));
currentRange = buildRange(currentRange.end);
completeRangeWithItem(currentRange, currentItem);
} else {
// Persist the current range and start a new one with current item
finalizeCurrentRange(results, currentRange);
currentRange = buildRange(currentItem);
}
}
}
finalizeCurrentRange(results, currentRange);
return results;
}
module.exports = compactField;
'use strict';
var compactField = require('./field_compactor');
function stringifyField(arr, min, max) {
var ranges = compactField(arr);
if (ranges.length === 1) {
var singleRange = ranges[0];
var step = singleRange.step;
if (step === 1 && singleRange.start === min && singleRange.end === max) {
return '*';
}
if (step !== 1 && singleRange.start === min && singleRange.end === max - step + 1) {
return '*/' + step;
}
}
var resultArr = [];
for (var i = 0, l = ranges.length; i < l; ++i) {
var range = ranges[i];
if (range.count === 1) {
resultArr.push(range.start);
} else {
var step = range.step;
if (step === 1) {
resultArr.push(range.start + '-' + range.end);
} else {
if (range.end === max - step + 1) {
resultArr.push(range.start + '/' + step);
} else {
resultArr.push(range.start + '-' + range.end + '/' + step);
}
}
}
}
return resultArr.join(',');
}
module.exports = stringifyField;
'use strict';
var CronExpression = require('./expression');
function CronParser() {}
/**
* Parse crontab entry
*
* @private
* @param {String} entry Crontab file entry/line
*/
CronParser._parseEntry = function _parseEntry (entry) {
var atoms = entry.split(' ');
if (atoms.length === 6) {
return {
interval: CronExpression.parse(entry)
};
} else if (atoms.length > 6) {
return {
interval: CronExpression.parse(
atoms.slice(0, 6).join(' ')
),
command: atoms.slice(6, atoms.length)
};
} else {
throw new Error('Invalid entry: ' + entry);
}
};
/**
* Wrapper for CronExpression.parser method
*
* @public
* @param {String} expression Input expression
* @param {Object} [options] Parsing options
* @return {Object}
*/
CronParser.parseExpression = function parseExpression (expression, options) {
return CronExpression.parse(expression, options);
};
/**
* Wrapper for CronExpression.fieldsToExpression method
*
* @public
* @param {Object} fields Input fields
* @param {Object} [options] Parsing options
* @return {Object}
*/
CronParser.fieldsToExpression = function fieldsToExpression (fields, options) {
return CronExpression.fieldsToExpression(fields, options);
};
/**
* Parse content string
*
* @public
* @param {String} data Crontab content
* @return {Object}
*/
CronParser.parseString = function parseString (data) {
var blocks = data.split('\n');
var response = {
variables: {},
expressions: [],
errors: {}
};
for (var i = 0, c = blocks.length; i < c; i++) {
var block = blocks[i];
var matches = null;
var entry = block.trim(); // Remove surrounding spaces
if (entry.length > 0) {
if (entry.match(/^#/)) { // Comment
continue;
} else if ((matches = entry.match(/^(.*)=(.*)$/))) { // Variable
response.variables[matches[1]] = matches[2];
} else { // Expression?
var result = null;
try {
result = CronParser._parseEntry('0 ' + entry);
response.expressions.push(result.interval);
} catch (err) {
response.errors[entry] = err;
}
}
}
}
return response;
};
/**
* Parse crontab file
*
* @public
* @param {String} filePath Path to file
* @param {Function} callback
*/
CronParser.parseFile = function parseFile (filePath, callback) {
require('fs').readFile(filePath, function(err, data) {
if (err) {
callback(err);
return;
}
return callback(null, CronParser.parseString(data.toString()));
});
};
module.exports = CronParser;
{
"name": "cron-parser",
"version": "3.5.0",
"description": "Node.js library for parsing crontab instructions",
"main": "lib/parser.js",
"types": "index.d.ts",
"typesVersions": {
"<4.1": {
"*": [
"types/ts3/*"
]
}
},
"directories": {
"test": "test"
},
"scripts": {
"test:tsd": "tsd",
"test:unit": "TZ=UTC tap ./test/*.js",
"test:cover": "TZ=UTC tap --coverage-report=html ./test/*.js",
"lint": "eslint .",
"lint:fix": "eslint --fix .",
"test": "npm run lint && npm run test:unit && npm run test:tsd"
},
"repository": {
"type": "git",
"url": "https://github.com/harrisiirak/cron-parser.git"
},
"keywords": [
"cron",
"crontab",
"parser"
],
"author": "Harri Siirak",
"contributors": [
"Nicholas Clawson",
"Daniel Prentis <daniel@salsitasoft.com>",
"Renault John Lecoultre",
"Richard Astbury <richard.astbury@gmail.com>",
"Meaglin Wasabi <Meaglin.wasabi@gmail.com>",
"Mike Kusold <hello@mikekusold.com>",
"Alex Kit <alex.kit@atmajs.com>",
"Santiago Gimeno <santiago.gimeno@gmail.com>",
"Daniel <darc.tec@gmail.com>",
"Christian Steininger <christian.steininger.cs@gmail.com>",
"Mykola Piskovyi <m.piskovyi@gmail.com>",
"Brian Vaughn <brian.david.vaughn@gmail.com>",
"Nicholas Clawson <nickclaw@gmail.com>",
"Yasuhiroki <yasuhiroki.duck@gmail.com>",
"Nicholas Clawson <nickclaw@gmail.com>",
"Brendan Warkentin <faazshift@gmail.com>",
"Charlie Fish <fishcharlie.code@gmail.com>",
"Ian Graves <ian+diskimage@iangrav.es>",
"Andy Thompson <me@andytson.com>",
"Regev Brody <regevbr@gmail.com>"
],
"license": "MIT",
"dependencies": {
"is-nan": "^1.3.2",
"luxon": "^1.26.0"
},
"devDependencies": {
"eslint": "^7.24.0",
"sinon": "^10.0.0",
"tap": "^15.0.3",
"tsd": "^0.14.0"
},
"engines": {
"node": ">=0.8"
},
"browser": {
"fs": false
},
"tap": {
"check-coverage": false
},
"tsd": {
"directory": "test",
"compilerOptions": {
"lib": [
"es2017",
"dom"
]
}
}
}
var util = require('util');
var test = require('tap').test;
var expression = require('../lib/expression');
test('expression 31 of month', function(t) {
try {
var interval = expression.parse('0 0 31 * *');
var i;
var d;
for (i = 0; i < 20; ++i) {
d = interval.next();
}
t.end();
} catch (err) {
t.error(err, 'Interval parse error');
}
});
var util = require('util');
var test = require('tap').test;
var CronExpression = require('../lib/expression');
var CronDate = require('../lib/date');
test('parse expression as UTC', function(t) {
try {
var options = {
utc: true
};
var interval = CronExpression.parse('0 0 10 * * *', options);
var date = interval.next();
t.equal(date.getUTCHours(), 10, 'Correct UTC hour value');
interval = CronExpression.parse('0 */5 * * * *', options);
var date = interval.next(), now = new Date();
now.setMinutes(now.getMinutes() + 5 - (now.getMinutes() % 5));
t.equal(date.getHours(), now.getUTCHours(), 'Correct local time for 5 minute interval');
} catch (err) {
t.error(err, 'UTC parse error');
}
t.end();
});
# Comment line (ignore)
ENV1="test1"
ENV2="test2"
*/10 * * * * /path/to/exe
*/10 * * * * /path/to/exe
0 09-18 * * 1-5 /path/to/exe
\ No newline at end of file
// empty around comma
var test = require('tap').test;
var CronExpression = require('../lib/expression');
const options = {
utc: true
};
test('both empty around comma', function (t) {
t.throws(function () {
CronExpression.parse('*/10 * * * * ,', options);
}, new Error('Invalid list value format'));
t.end();
});
test('one side empty around comma', function (t) {
t.throws(function () {
CronExpression.parse('*/10 * * * * ,2', options);
}, new Error('Invalid list value format'));
t.end();
});
var test = require('tap').test;
var CronExpression = require('../lib/expression');
var CronDate = require('../lib/date');
test('empty expression test', function(t) {
try {
var interval = CronExpression.parse('');
t.ok(interval, 'Interval parsed');
var date = new CronDate();
date.addMinute();
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getMinutes(), date.getMinutes(), 'Schedule matches');
t.end();
} catch (err) {
t.error(err, 'Interval parse error');
}
});
test('default expression test', function(t) {
try {
var interval = CronExpression.parse('* * * * *');
t.ok(interval, 'Interval parsed');
var date = new CronDate();
date.addMinute();
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getMinutes(), date.getMinutes(), 'Schedule matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('default expression (tab separate) test', function(t) {
try {
var interval = CronExpression.parse('* * * * *');
t.ok(interval, 'Interval parsed');
var date = new CronDate();
date.addMinute();
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getMinutes(), date.getMinutes(), 'Schedule matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('default expression (multi-space separated) test 1', function(t) {
try {
var interval = CronExpression.parse('* \t*\t\t *\t * \t\t*');
t.ok(interval, 'Interval parsed');
var date = new CronDate();
date.addMinute();
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getMinutes(), date.getMinutes(), 'Schedule matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('default expression (multi-space separated) test 1', function(t) {
try {
var interval = CronExpression.parse('* \t *\t \t * * \t \t *');
t.ok(interval, 'Interval parsed');
var date = new CronDate();
date.addMinute();
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getMinutes(), date.getMinutes(), 'Schedule matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('value out of the range', function(t) {
t.throws(function() {
CronExpression.parse('61 * * * * *');
}, new Error('Constraint error, got value 61 expected range 0-59'));
t.end();
});
test('second value out of the range', function(t) {
t.throws(function() {
CronExpression.parse('-1 * * * * *');
}, new Error('Constraint error, got value -1 expected range 0-59'));
t.end();
});
test('invalid range', function(t) {
t.throws(function() {
CronExpression.parse('- * * * * *');
}, new Error('Invalid range: -'));
t.end();
});
test('minute value out of the range', function(t) {
t.throws(function() {
CronExpression.parse('* 32,72 * * * *');
}, new Error('Constraint error, got value 72 expected range 0-59'));
t.end();
});
test('hour value out of the range', function(t) {
t.throws(function() {
CronExpression.parse('* * 12-36 * * *');
}, new Error('Constraint error, got range 12-36 expected range 0-23'));
t.end();
});
test('day of the month value out of the range', function(t) {
t.throws(function() {
CronExpression.parse('* * * 10-15,40 * *');
}, ('Constraint error, got value 40 expected range 1-31'));
t.end();
});
test('month value out of the range', function(t) {
t.throws(function() {
CronExpression.parse('* * * * */10,12-13 *');
}, new Error('Constraint error, got range 12-13 expected range 1-12'));
t.end();
});
test('day of the week value out of the range', function(t) {
t.throws(function() {
CronExpression.parse('* * * * * 9');
}, new Error('Constraint error, got value 9 expected range 0-7'));
t.end();
});
test('invalid expression that contains too many fields', function (t) {
t.throws(function() {
CronExpression.parse('* * * * * * * *ASD');
}, new Error('Invalid cron expression'));
t.end();
});
test('invalid explicit day of month definition', function(t) {
t.throws(function() {
const iter = CronExpression.parse('0 0 31 4 *');
iter.next();
}, new Error('Invalid explicit day of month definition'));
t.end();
});
test('incremental minutes expression test', function(t) {
try {
var interval = CronExpression.parse('*/3 * * * *');
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getMinutes() % 3, 0, 'Schedule matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('fixed expression test', function(t) {
try {
var interval = CronExpression.parse('10 2 12 8 0');
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of Month matches');
t.equal(next.getMonth(), 7, 'Month matches');
t.equal(next.getHours(), 2, 'Hour matches');
t.equal(next.getMinutes(), 10, 'Minute matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('invalid characters test - symbol', function(t) {
t.throws(function() {
CronExpression.parse('10 ! 12 8 0');
}, new Error('Invalid characters, got value: !'));
t.end();
});
test('invalid characters test - letter', function(t) {
t.throws(function() {
CronExpression.parse('10 x 12 8 0');
}, new Error('Invalid characters, got value: x'));
t.end();
});
test('invalid characters test - parentheses', function(t) {
t.throws(function() {
CronExpression.parse('10 ) 12 8 0');
}, new Error('Invalid characters, got value: )'));
t.end();
});
test('interval with invalid characters test', function(t) {
t.throws(function() {
CronExpression.parse('10 */A 12 8 0');
}, new Error('Invalid characters, got value: */A'));
t.end();
});
test('range with invalid characters test', function(t) {
t.throws(function() {
CronExpression.parse('10 0-z 12 8 0');
}, new Error('Invalid characters, got value: 0-z'));
t.end();
});
test('group with invalid characters test', function(t) {
t.throws(function() {
CronExpression.parse('10 0,1,z 12 8 0');
}, new Error('Invalid characters, got value: 0,1,z'));
t.end();
});
test('invalid expression which has repeat 0 times', function(t) {
t.throws(function() {
CronExpression.parse('0 */0 * * *');
}, new Error('Constraint error, cannot repeat at every 0 time.'));
t.end();
});
test('invalid expression which has repeat negative number times', function(t) {
t.throws(function() {
CronExpression.parse('0 */-5 * * *');
}, new Error('Constraint error, cannot repeat at every -5 time.'));
t.end();
});
test('range test with value and repeat (second)', function(t) {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53')
};
var interval = CronExpression.parse('0/30 * * * * ?', options);
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.equal(next.getSeconds(), 0);
next = interval.next();
t.equal(next.getSeconds(), 30);
next = interval.next();
t.equal(next.getSeconds(), 0);
t.end();
});
test('range test with value and repeat (minute)', function(t) {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53')
};
var interval = CronExpression.parse('6/23 * * * *', options);
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.equal(next.getMinutes(), 52);
next = interval.next();
t.equal(next.getMinutes(), 6);
next = interval.next();
t.equal(next.getMinutes(), 29);
next = interval.next();
t.equal(next.getMinutes(), 52);
t.end();
});
test('range test with iterator', function(t) {
try {
var interval = CronExpression.parse('10-30 2 12 8 0');
t.ok(interval, 'Interval parsed');
var intervals = interval.iterate(20);
t.ok(intervals, 'Found intervals');
for (var i = 0, c = intervals.length; i < c; i++) {
var next = intervals[i];
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
t.equal(next.getHours(), 2, 'Hour matches');
t.equal(next.getMinutes(), 10 + i, 'Minute matches');
}
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('incremental range test with iterator', function(t) {
try {
var interval = CronExpression.parse('10-30/2 2 12 8 0');
t.ok(interval, 'Interval parsed');
var intervals = interval.iterate(10);
t.ok(intervals, 'Found intervals');
for (var i = 0, c = intervals.length; i < c; i++) {
var next = intervals[i];
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
t.equal(next.getHours(), 2, 'Hour matches');
t.equal(next.getMinutes(), 10 + (i * 2), 'Minute matches');
}
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('predefined expression', function(t) {
try {
var interval = CronExpression.parse('@yearly');
t.ok(interval, 'Interval parsed');
var date = new CronDate();
date.addYear();
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getFullYear(), date.getFullYear(), 'Year matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('expression limited with start and end date', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53'),
startDate: new CronDate('Wed, 26 Dec 2012 12:40:00'),
endDate: new CronDate('Wed, 26 Dec 2012 16:40:00')
};
var interval = CronExpression.parse('*/20 * * * *', options);
t.ok(interval, 'Interval parsed');
var dates = interval.iterate(10);
t.equal(dates.length, 7, 'Dates count matches for positive iteration');
interval.reset();
var dates = interval.iterate(-10);
t.equal(dates.length, 6, 'Dates count matches for negative iteration');
interval.reset();
// Forward iteration
var next = interval.next();
t.equal(next.getHours(), 14, 'Hour matches');
t.equal(next.getMinutes(), 40, 'Minute matches');
next = interval.next();
t.equal(next.getHours(), 15, 'Hour matches');
t.equal(next.getMinutes(), 0, 'Minute matches');
next = interval.next();
t.equal(next.getHours(), 15, 'Hour matches');
t.equal(next.getMinutes(), 20, 'Minute matches');
next = interval.next();
t.equal(next.getHours(), 15, 'Hour matches');
t.equal(next.getMinutes(), 40, 'Minute matches');
next = interval.next();
t.equal(next.getHours(), 16, 'Hour matches');
t.equal(next.getMinutes(), 0, 'Minute matches');
next = interval.next();
t.equal(next.getHours(), 16, 'Hour matches');
t.equal(next.getMinutes(), 20, 'Minute matches');
next = interval.next();
t.equal(next.getHours(), 16, 'Hour matches');
t.equal(next.getMinutes(), 40, 'Minute matches');
try {
interval.next();
t.ok(false, 'Should fail');
} catch (e) {
t.ok(true, 'Failed as expected');
}
next = interval.prev();
t.equal(next.getHours(), 16, 'Hour matches');
t.equal(next.getMinutes(), 20, 'Minute matches');
interval.reset();
// Backward iteration
var prev = interval.prev();
t.equal(prev.getHours(), 14, 'Hour matches');
t.equal(prev.getMinutes(), 20, 'Minute matches');
prev = interval.prev();
t.equal(prev.getHours(), 14, 'Hour matches');
t.equal(prev.getMinutes(), 0, 'Minute matches');
prev = interval.prev();
t.equal(prev.getHours(), 13, 'Hour matches');
t.equal(prev.getMinutes(), 40, 'Minute matches');
prev = interval.prev();
t.equal(prev.getHours(), 13, 'Hour matches');
t.equal(prev.getMinutes(), 20, 'Minute matches');
prev = interval.prev();
t.equal(prev.getHours(), 13, 'Hour matches');
t.equal(prev.getMinutes(), 0, 'Minute matches');
prev = interval.prev();
t.equal(prev.getHours(), 12, 'Hour matches');
t.equal(prev.getMinutes(), 40, 'Minute matches');
try {
interval.prev();
t.ok(false, 'Should fail');
} catch (e) {
t.ok(true, 'Failed as expected');
}
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('reset to given date', function(t){
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53')
};
var interval = CronExpression.parse('*/20 * * * *', options);
t.ok(interval, 'Interval parsed');
// Forward iteration
var next = interval.next();
t.equal(next.getHours(), 14, 'Hour matches');
t.equal(next.getMinutes(), 40, 'Minute matches');
interval.reset(); // defaults to initial currentDate
next = interval.next();
t.equal(next.getHours(), 14, 'Hour matches');
t.equal(next.getMinutes(), 40, 'Minute matches');
interval.reset(new CronDate('Wed, 26 Dec 2012 17:23:53'));
next = interval.next();
t.equal(next.getHours(), 17, 'Hour matches');
t.equal(next.getMinutes(), 40, 'Minute matches');
next = interval.next();
t.equal(next.getHours(), 18, 'Hour matches');
t.equal(next.getMinutes(), 0, 'Minute matches');
interval.reset(new Date('2019-06-18T08:18:36.000'));
next = interval.prev();
t.equal(next.getDate(), 18, 'Date matches');
t.equal(next.getHours(), 8, 'Hour matches');
t.equal(next.getMinutes(), 0, 'Minute matches');
next = interval.prev();
t.equal(next.getDate(), 18, 'Date matches');
t.equal(next.getHours(), 7, 'Hour matches');
t.equal(next.getMinutes(), 40, 'Minute matches');
t.end();
} catch (err) {
t.error(err, 'Reset error');
}
});
test('parse expression as UTC', function(t) {
try {
var options = {
utc: true
};
var interval = CronExpression.parse('0 0 10 * * *', options);
var date = interval.next();
t.equal(date.getUTCHours(), 10, 'Correct UTC hour value');
t.equal(date.getHours(), 10, 'Correct UTC hour value');
interval = CronExpression.parse('0 */5 * * * *', options);
var date = interval.next(), now = new Date();
now.setMinutes(now.getMinutes() + 5 - (now.getMinutes() % 5));
t.equal(date.getHours(), now.getUTCHours(), 'Correct local time for 5 minute interval');
} catch (err) {
t.error(err, 'UTC parse error');
}
t.end();
});
test('expression using days of week strings', function(t) {
try {
var interval = CronExpression.parse('15 10 * * MON-TUE');
t.ok(interval, 'Interval parsed');
var intervals = interval.iterate(8);
t.ok(intervals, 'Found intervals');
for (var i = 0, c = intervals.length; i < c; i++) {
var next = intervals[i];
var day = next.getDay();
t.ok(next, 'Found next scheduled interval');
t.ok(day == 1 || day == 2, 'Day matches');
t.equal(next.getHours(), 10, 'Hour matches');
t.equal(next.getMinutes(), 15, 'Minute matches');
}
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('expression using days of week strings - wrong alias', function(t) {
t.throws(function () {
CronExpression.parse('15 10 * * MON-TUR');
}, new Error('Validation error, cannot resolve alias "tur"'));
t.end();
});
test('expression using mixed days of week strings', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53')
};
var interval = CronExpression.parse('15 10 * jAn-FeB mOn-tUE', options);
t.ok(interval, 'Interval parsed');
var intervals = interval.iterate(8);
t.ok(intervals, 'Found intervals');
for (var i = 0, c = intervals.length; i < c; i++) {
var next = intervals[i];
var day = next.getDay();
var month = next.getMonth();
t.ok(next, 'Found next scheduled interval');
t.ok(month == 0 || month == 2, 'Month Matches');
t.ok(day == 1 || day == 2, 'Day matches');
t.equal(next.getHours(), 10, 'Hour matches');
t.equal(next.getMinutes(), 15, 'Minute matches');
}
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('expression using non-standard second field (wildcard)', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:00'),
endDate: new CronDate('Wed, 26 Dec 2012 15:40:00')
};
var interval = CronExpression.parse('* * * * * *', options);
t.ok(interval, 'Interval parsed');
var intervals = interval.iterate(10);
t.ok(intervals, 'Found intervals');
for (var i = 0, c = intervals.length; i < c; i++) {
var next = intervals[i];
t.ok(next, 'Found next scheduled interval');
t.equal(next.getSeconds(), i + 1, 'Second matches');
}
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('expression using non-standard second field (step)', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:00'),
endDate: new CronDate('Wed, 26 Dec 2012 15:40:00')
};
var interval = CronExpression.parse('*/20 * * * * *', options);
t.ok(interval, 'Interval parsed');
var intervals = interval.iterate(3);
t.ok(intervals, 'Found intervals');
t.equal(intervals[0].getSeconds(), 20, 'Second matches');
t.equal(intervals[1].getSeconds(), 40, 'Second matches');
t.equal(intervals[2].getSeconds(), 0, 'Second matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('expression using non-standard second field (range)', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:00'),
endDate: new CronDate('Wed, 26 Dec 2012 15:40:00')
};
var interval = CronExpression.parse('20-40/10 * * * * *', options);
t.ok(interval, 'Interval parsed');
var intervals = interval.iterate(3);
t.ok(intervals, 'Found intervals');
for (var i = 0, c = intervals.length; i < c; i++) {
var next = intervals[i];
t.ok(next, 'Found next scheduled interval');
t.equal(next.getSeconds(), 20 + (i * 10), 'Second matches');
}
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('expression using explicit month definition and */5 day of month step', function(t) {
var firstIterator = CronExpression.parse('0 12 */5 6 *', {
currentDate: '2019-06-01T11:00:00.000'
});
var firstExpectedDates = [
new CronDate('2019-06-01T12:00:00.000'),
new CronDate('2019-06-06T12:00:00.000'),
new CronDate('2019-06-11T12:00:00.000'),
new CronDate('2019-06-16T12:00:00.000'),
new CronDate('2019-06-21T12:00:00.000'),
new CronDate('2019-06-26T12:00:00.000'),
new CronDate('2020-06-01T12:00:00.000')
];
firstExpectedDates.forEach(function(expectedDate) {
t.equal(expectedDate.toISOString(), firstIterator.next().toISOString());
});
var secondIterator = CronExpression.parse('0 15 */5 5 *', {
currentDate: '2019-05-01T11:00:00.000'
});
var secondExpectedDates = [
new CronDate('2019-05-01T15:00:00.000'),
new CronDate('2019-05-06T15:00:00.000'),
new CronDate('2019-05-11T15:00:00.000'),
new CronDate('2019-05-16T15:00:00.000'),
new CronDate('2019-05-21T15:00:00.000'),
new CronDate('2019-05-26T15:00:00.000'),
new CronDate('2019-05-31T15:00:00.000'),
new CronDate('2020-05-01T15:00:00.000')
];
secondExpectedDates.forEach(function(expectedDate) {
t.equal(expectedDate.toISOString(), secondIterator.next().toISOString());
});
t.end();
});
test('day of month and week are both set', function(t) {
try {
var interval = CronExpression.parse('10 2 12 8 0');
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('day of month is unspecified', function(t) {
try {
var interval = CronExpression.parse('10 2 ? * 3');
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interal');
t.ok(next.getDay() === 3, 'day of week matches');
next = interval.next();
t.ok(next, 'Found next scheduled interal');
t.ok(next.getDay() === 3, 'day of week matches');
next = interval.next();
t.ok(next, 'Found next scheduled interal');
t.ok(next.getDay() === 3, 'day of week matches');
next = interval.next();
t.ok(next, 'Found next scheduled interal');
t.ok(next.getDay() === 3, 'day of week matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('day of week is unspecified', function(t) {
try {
var interval = CronExpression.parse('10 2 3,6 * ?');
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interal');
t.ok(next.getDate() === 3 || next.getDate() === 6, 'date matches');
var prevDate = next.getDate();
next = interval.next();
t.ok(next, 'Found next scheduled interal');
t.ok((next.getDate() === 3 || next.getDate() === 6) &&
next.getDate() !== prevDate, 'date matches and is not previous date');
prevDate = next.getDate();
next = interval.next();
t.ok(next, 'Found next scheduled interal');
t.ok((next.getDate() === 3 || next.getDate() === 6) &&
next.getDate() !== prevDate, 'date matches and is not previous date');
prevDate = next.getDate();
next = interval.next();
t.ok(next, 'Found next scheduled interal');
t.ok((next.getDate() === 3 || next.getDate() === 6) &&
next.getDate() !== prevDate, 'date matches and is not previous date');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('Summertime bug test', function(t) {
try {
var month = new CronDate().getMonth() + 1;
var interval = CronExpression.parse('0 0 0 1 '+month+' *');
t.ok(interval, 'Interval parsed');
var next = interval.next();
// Before fix the bug it was getting a timeout error if you are
// in a timezone that changes the DST to ST in the hour 00:00h.
t.ok(next, 'Found next scheduled interval');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('day of month and week are both set and dow is 7', function(t) {
try {
var interval = CronExpression.parse('10 2 12 8 7');
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('day of month is wildcard, month and day of week are both set', function(t) {
try {
var options = {
currentDate: new CronDate('Mon, 31 May 2021 12:00:00')
};
var interval = CronExpression.parse('0 0 * 6 2', options);
t.ok(interval, 'Interval parsed');
var expectedDayMatches = [1, 8, 15, 22, 29];
expectedDayMatches.forEach(function(dayOfMonth) {
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getDay(), 2, 'Day of week matches');
t.equal(next.getDate(), dayOfMonth, 'Day of month matches');
t.equal(next.getMonth(), 5, 'Month matches');
});
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('day of month and week are both set and dow is 6,0', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53')
};
var interval = CronExpression.parse('10 2 12 8 6,0', options);
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 6 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 6 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 0 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('day of month and week are both set and dow is 6-7', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53')
};
var interval = CronExpression.parse('10 2 12 8 6-7', options);
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 6 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 6 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 6 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
// next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.ok(next.getDay() === 6 || next.getDate() === 12, 'Day or day of month matches');
t.equal(next.getMonth(), 7, 'Month matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('day of month validation should be ignored when day of month is wildcard and month is set', function (t) {
try {
var options = {
currentDate: new CronDate('2020-05-01T15:00:00.000')
};
var interval = CronExpression.parse('* * * * 2 *', options);
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getHours(), 0, 'Hours matches');
t.equal(next.getDate(), 1, 'Day of month matches');
t.equal(next.getMonth() + 1, 2, 'Month matches');
t.ok(next, 'Found next scheduled interval');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('day and date in week should matches', function(t){
try {
var interval = CronExpression.parse('0 1 1 1 * 1');
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getHours(), 1, 'Hours matches');
t.ok(next.getDay() === 1 || next.getDate() === 1, 'Day or day of month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getHours(), 1, 'Hours matches');
t.ok(next.getDay() === 1 || next.getDate() === 1, 'Day or day of month matches');
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getHours(), 1, 'Hours matches');
t.ok(next.getDay() === 1 || next.getDate() === 1, 'Day or day of month matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('should sort ranges and values in ascending order', function(t) {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53')
};
var interval = CronExpression.parse('0 12,13,10,1-3 * * *', options);
t.ok(interval, 'Interval parsed');
var hours = [ 1, 2, 3, 10, 12, 13 ];
for (var i in hours) {
next = interval.next();
t.ok(next, 'Found next scheduled interval');
t.equal(next.getHours(), hours[i], 'Hours matches');
}
t.end();
});
test('valid ES6 iterator should be returned if iterator options is set to true', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53'),
endDate: new CronDate('Wed, 26 Dec 2012 15:40:00'),
iterator: true
};
var val = null;
var interval = CronExpression.parse('*/25 * * * *', options);
t.ok(interval, 'Interval parsed');
val = interval.next();
t.ok(val, 'Next iteration resolved');
t.ok(val.value, 'Iterator value is set');
t.notOk(val.done, 'Iterator is not finished');
val = interval.next();
t.ok(val, 'Next iteration resolved');
t.ok(val.value, 'Iterator value is set');
t.notOk(val.done, 'Iterator is not finished');
val = interval.next();
t.ok(val, 'Next iteration resolved');
t.ok(val.value, 'Iterator value is set');
t.ok(val.done, 'Iterator is finished');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('dow 6,7 6,0 0,6 7,6 should be equivalent', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53'),
};
var expressions = [
'30 16 * * 6,7',
'30 16 * * 6,0',
'30 16 * * 0,6',
'30 16 * * 7,6'
];
expressions.forEach(function(expression) {
var interval = CronExpression.parse(expression, options);
t.ok(interval, 'Interval parsed');
var val = interval.next();
t.equal(val.getDay(), 6, 'Day matches');
val = interval.next();
t.equal(val.getDay(), 0, 'Day matches');
val = interval.next();
t.equal(val.getDay(), 6, 'Day matches');
});
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('hour 0 9,11,1 * * * and 0 1,9,11 * * * should be equivalent', function(t) {
try {
var options = {
currentDate: new CronDate('Wed, 26 Dec 2012 00:00:00'),
};
var expressions = [
'0 9,11,1 * * *',
'0 1,9,11 * * *'
];
expressions.forEach(function(expression) {
var interval = CronExpression.parse(expression, options);
t.ok(interval, 'Interval parsed');
var val = interval.next();
t.equal(val.getHours(), 1, 'Hour matches');
val = interval.next();
t.equal(val.getHours(), 9, 'Hour matches');
val = interval.next();
t.equal(val.getHours(), 11, 'Hour matches');
val = interval.next();
t.equal(val.getHours(), 1, 'Hour matches');
val = interval.next();
t.equal(val.getHours(), 9, 'Hour matches');
val = interval.next();
t.equal(val.getHours(), 11, 'Hour matches');
});
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('it will work with #139 issue case', function(t) {
var options = {
currentDate : new Date('2018-11-15T16:15:33.522Z'),
tz: 'Europe/Madrid'
};
var interval = CronExpression.parse('0 0 0 1,2 * *', options);
var date = interval.next();
t.equal(date.getFullYear(), 2018);
t.equal(date.getDate(), 1);
t.equal(date.getMonth(), 11);
t.end();
});
test('should work for valid first/second/third/fourth/fifth occurence dayOfWeek (# char)', function(t) {
try {
var options = {
currentDate: new CronDate('2019-04-30')
};
var expectedFirstDates = [
new CronDate('2019-05-05'),
new CronDate('2019-06-02'),
new CronDate('2019-07-07'),
new CronDate('2019-08-04')
];
var expectedSecondDates = [
new CronDate('2019-05-12'),
new CronDate('2019-06-09'),
new CronDate('2019-07-14'),
new CronDate('2019-08-11')
];
var expectedThirdDates = [
new CronDate('2019-05-19'),
new CronDate('2019-06-16'),
new CronDate('2019-07-21'),
new CronDate('2019-08-18')
];
var expectedFourthDates = [
new CronDate('2019-05-26'),
new CronDate('2019-06-23'),
new CronDate('2019-07-28'),
new CronDate('2019-08-25')
];
var expectedFifthDates = [
new CronDate('2019-06-30'),
new CronDate('2019-09-29'),
new CronDate('2019-12-29'),
new CronDate('2020-03-29')
];
var allExpectedDates = [
expectedFirstDates,
expectedSecondDates,
expectedThirdDates,
expectedFourthDates,
expectedFifthDates
];
var expressions = [
'0 0 0 ? * 0#1',
'0 0 0 ? * 0#2',
'0 0 0 ? * 0#3',
'0 0 0 ? * 0#4',
'0 0 0 ? * 0#5'
];
expressions.forEach(function(expression, index) {
var interval = CronExpression.parse(expression, options);
var expectedDates = allExpectedDates[index];
expectedDates.forEach(function(expected) {
var date = interval.next();
t.equal(
date.toISOString(),
expected.toISOString(),
'Expression "' + expression + '" has next() that matches expected: ' + expected.toISOString()
);
});
expectedDates
.slice(0, expectedDates.length - 1)
.reverse()
.forEach(function(expected) {
var date = interval.prev();
t.equal(
date.toISOString(),
expected.toISOString(),
'Expression "' + expression + '" has prev() that matches expected: ' + expected.toISOString()
);
});
});
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('should work for valid second sunday in may', function(t) {
try {
var options = {
currentDate: new CronDate('2019-01-30')
};
var expectedDates = [
new CronDate('2019-05-12'),
new CronDate('2020-05-10'),
new CronDate('2021-05-09'),
new CronDate('2022-05-08')
];
var interval = CronExpression.parse('0 0 0 ? MAY 0#2', options);
expectedDates.forEach(function(expected) {
var date = interval.next();
t.equal(
date.toISOString(),
expected.toISOString(),
'Expression "0 0 0 ? MAY 0#2" has next() that matches expected: ' + expected.toISOString()
);
});
expectedDates
.slice(0, expectedDates.length - 1)
.reverse()
.forEach(function(expected) {
var date = interval.prev();
t.equal(
date.toISOString(),
expected.toISOString(),
'Expression "0 0 0 ? MAY 0#2" has prev() that matches expected: ' + expected.toISOString()
);
});
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('should work for valid second sunday at noon in may', function(t) {
try {
var options = {
currentDate: new CronDate('2019-05-12T11:59:00.000')
};
var expected = new CronDate('2019-05-12T12:00:00.000');
var interval = CronExpression.parse('0 0 12 ? MAY 0#2', options);
var date = interval.next();
t.equal(
date.toISOString(),
expected.toISOString(),
'Expression "0 0 12 ? MAY 0#2" has next() that matches expected: ' + expected.toISOString()
);
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('should work for valid second sunday at noon in may (UTC+3)', function(t) {
try {
var options = {
currentDate: new CronDate('2019-05-12T11:59:00.000', 'Europe/Sofia')
};
var expected = new CronDate('2019-05-12T12:00:00.000', 'Europe/Sofia');
var interval = CronExpression.parse('0 0 12 ? MAY 0#2', options);
var date = interval.next();
t.equal(
date.toISOString(),
expected.toISOString(),
'Expression "0 0 12 ? MAY 0#2" has next() that matches expected: ' + expected.toISOString()
);
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('should work with both dayOfMonth and nth occurence of dayOfWeek', function(t) {
try {
var options = {
currentDate: new CronDate('2019-04-01')
};
var expectedDates = [
new CronDate('2019-04-16'),
new CronDate('2019-04-17'),
new CronDate('2019-04-18'),
new CronDate('2019-05-15'),
new CronDate('2019-05-16'),
new CronDate('2019-05-18'),
];
var interval = CronExpression.parse('0 0 0 16,18 * 3#3', options);
expectedDates.forEach(function(expected) {
var date = interval.next();
t.equal(
date.toISOString(),
expected.toISOString(),
'Expression "0 0 0 16,18 * 3#3" has next() that matches expected: ' + expected.toISOString()
);
});
expectedDates
.slice(0, expectedDates.length - 1)
.reverse()
.forEach(function(expected) {
var date = interval.prev();
t.equal(
date.toISOString(),
expected.toISOString(),
'Expression "0 0 0 16,18 * 3#3" has prev() that matches expected: ' + expected.toISOString()
);
});
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('should error when passed invalid occurence value', function(t) {
var expressions = [
'0 0 0 ? * 1#',
'0 0 0 ? * 1#0',
'0 0 0 ? * 4#6',
'0 0 0 ? * 0##4',
];
expressions.forEach(function(expression) {
t.throws(function() {
CronExpression.parse(expression);
}, new Error('Constraint error, invalid dayOfWeek occurrence number (#)'), expression);
});
t.end();
});
// The Quartz documentation says that if the # character is used then no other expression can be used in the dayOfWeek term: http://www.quartz-scheduler.org/api/2.3.0/index.html
test('cannot combine `-` range and # occurrence special characters', function(t) {
var expression = '0 0 0 ? * 2-4#2';
t.throws(function() {
CronExpression.parse(expression);
}, new Error('Constraint error, invalid dayOfWeek `#` and `-` special characters are incompatible'));
t.end();
});
test('cannot combine `/` repeat interval and # occurrence special characters', function(t) {
var expression = '0 0 0 ? * 1/2#3';
t.throws(function() {
CronExpression.parse(expression);
}, new Error('Constraint error, invalid dayOfWeek `#` and `/` special characters are incompatible'));
t.end();
});
test('cannot combine `,` list and # occurrence special characters', function(t) {
var expression = '0 0 0 ? * 0,6#4';
t.throws(function() {
CronExpression.parse(expression);
}, new Error('Constraint error, invalid dayOfWeek `#` and `,` special characters are incompatible'));
t.end();
});
'use strict';
var test = require('tap').test;
var compactField = require('../lib/field_compactor');
test('compact field - empty array', function(t) {
try {
var result = compactField([]);
t.same(result, []);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - single element array', function(t) {
try {
var result = compactField([1]);
t.same(result, [{
start: 1,
count: 1
}]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - 2 elements array', function(t) {
try {
var result = compactField([1, 2]);
t.same(result, [
{
start: 1,
count: 1
},
{
start: 2,
count: 1
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - 2 elements array big step', function(t) {
try {
var result = compactField([1, 5]);
t.same(result, [
{
start: 1,
count: 1
},
{
start: 5,
count: 1
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - 3 elements array 1 step', function(t) {
try {
var result = compactField([1, 2, 3]);
t.same(result, [
{
start: 1,
end: 3,
count: 3,
step: 1
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - 3 elements array 1 step, dangling extra at end', function(t) {
try {
var result = compactField([1, 2, 3, 5]);
t.same(result, [
{
start: 1,
end: 3,
count: 3,
step: 1
},
{
start: 5,
count: 1
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - 3 elements array 1 step, dangling extra at end and beginning', function(t) {
try {
var result = compactField([1, 4, 5, 6, 9]);
t.same(result, [
{
start: 1,
count: 1
},
{
start: 4,
end: 6,
count: 3,
step: 1
},
{
start: 9,
count: 1
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - 2 ranges with dangling in the middle', function(t) {
try {
var result = compactField([1, 2, 3, 6, 9, 11, 13]);
t.same(result, [
{
start: 1,
end: 3,
count: 3,
step: 1
},
{
start: 6,
count: 1
},
{
start: 9,
end: 13,
count: 3,
step: 2
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - with chars', function(t) {
try {
var result = compactField(['L', 'W']);
t.same(result, [
{
start: 'L',
count: 1
},
{
start: 'W',
count: 1
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - with chars and range', function(t) {
try {
var result = compactField([1, 'L', 'W']);
t.same(result, [
{
start: 1,
count: 1,
},
{
start: 'L',
count: 1
},
{
start: 'W',
count: 1
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - with chars and range (v2)', function(t) {
try {
var result = compactField([1, 2, 'L', 'W']);
t.same(result, [
{
start: 1,
count: 1,
},
{
start: 2,
count: 1,
},
{
start: 'L',
count: 1
},
{
start: 'W',
count: 1
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
test('compact field - with chars and range (v3)', function(t) {
try {
var result = compactField([1, 2, 3, 'L', 'W']);
t.same(result, [
{
start: 1,
end: 3,
count: 3,
step: 1
},
{
start: 'L',
count: 1
},
{
start: 'W',
count: 1
}
]);
} catch (err) {
t.error(err, 'compact field error');
}
t.end();
});
'use strict';
var test = require('tap').test;
var stringifyField = require('../lib/field_stringify');
test('stringify astrix', function (t) {
try {
var str = stringifyField([1, 2, 3, 4], 1, 4);
t.equal(str, '*');
} catch (err) {
t.error(err, 'stringify field error');
}
t.end();
});
test('stringify astrix step', function (t) {
try {
var str = stringifyField([0, 2, 4, 6], 0, 7);
t.equal(str, '*/2');
} catch (err) {
t.error(err, 'stringify field error');
}
t.end();
});
test('stringify single value', function (t) {
try {
var str = stringifyField([2], 0, 7);
t.equal(str, '2');
} catch (err) {
t.error(err, 'stringify field error');
}
t.end();
});
test('stringify multiple single values', function (t) {
try {
var str = stringifyField([2, 5, 9], 0, 7);
t.equal(str, '2,5,9');
} catch (err) {
t.error(err, 'stringify field error');
}
t.end();
});
test('stringify range', function (t) {
try {
var str = stringifyField([2, 3, 4], 0, 7);
t.equal(str, '2-4');
} catch (err) {
t.error(err, 'stringify field error');
}
t.end();
});
test('stringify range step', function (t) {
try {
var str = stringifyField([2, 4, 6], 0, 8);
t.equal(str, '2-6/2');
} catch (err) {
t.error(err, 'stringify field error');
}
t.end();
});
test('stringify semi range step', function (t) {
try {
var str = stringifyField([4, 6, 8], 0, 9);
t.equal(str, '4/2');
} catch (err) {
t.error(err, 'stringify field error');
}
t.end();
});
test('stringify multi types', function (t) {
try {
var str = stringifyField([1, 2, 4, 5, 6, 7, 8, 9, 10, 20, 25, 30, 35, 57], 0, 59);
t.equal(str, '1,2,4-10,20-35/5,57');
} catch (err) {
t.error(err, 'stringify field error');
}
t.end();
});
var test = require('tap').test;
var CronExpression = require('../lib/expression');
test('Fields are exposed', function(t){
try {
var interval = CronExpression.parse('0 1 2 3 * 1-3,5');
t.ok(interval, 'Interval parsed');
CronExpression.map.forEach(function(field) {
interval.fields[field] = [];
t.throws(function() {
interval.fields[field].push(-1);
}, /Cannot add property .*?, object is not extensible/, field + ' is frozen');
delete interval.fields[field];
});
interval.fields.dummy = [];
t.same(interval.fields.dummy, undefined, 'Fields is frozen');
t.same(interval.fields.second, [0], 'Second matches');
t.same(interval.fields.minute, [1], 'Minute matches');
t.same(interval.fields.hour, [2], 'Hour matches');
t.same(interval.fields.dayOfMonth, [3], 'Day of month matches');
t.same(interval.fields.month, [1,2,3,4,5,6,7,8,9,10,11,12], 'Month matches');
t.same(interval.fields.dayOfWeek, [1,2,3,5], 'Day of week matches');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
var util = require('util');
var sinon = require('sinon');
var test = require('tap').test;
var CronExpression = require('../lib/expression');
test('increment_on_first_itereation', function(t) {
try {
var clock = sinon.useFakeTimers();
var fake_now = new Date('Tue Feb 21 2017 16:45:00');
clock.tick(fake_now.getTime());
var interval = CronExpression.parse('* * * * *');
t.ok(interval, 'Interval parsed');
var next = interval.next();
t.ok(next, 'Found next scheduled interval');
// Make sure next has incremented in 1 minute
t.equal(fake_now.getTime() + 60000, next.getTime());
clock.restore();
t.end();
} catch (err) {
t.error(err, 'Interval parse error');
}
});
import {expectAssignable, expectError, expectNotAssignable, expectType} from 'tsd';
import {
CronDate,
CronExpression,
CronFields, DateType,
parseExpression,
parseFile, ParserOptions,
parseString,
fieldsToExpression,
StringResult
} from '../types/ts3';
const interval = parseExpression('0 1 2 3 * 1-3,5');
const intervalIterator = parseExpression('0 1 2 3 * 1-3,5', {iterator: true});
expectType<readonly number[]>(interval.fields.second);
expectType<readonly number[]>(interval.fields.minute);
expectType<readonly number[]>(interval.fields.hour);
expectType<readonly (number | 'L')[]>(interval.fields.dayOfMonth);
expectType<readonly number[]>(interval.fields.month);
expectType<readonly number[]>(interval.fields.dayOfWeek);
expectError(interval.fields = interval.fields);
expectError(interval.fields.second = []);
expectError(interval.fields.second.push(1));
expectError(interval.fields.minute = []);
expectError(interval.fields.minute.push(1));
expectError(interval.fields.hour = []);
expectError(interval.fields.hour.push(1));
expectError(interval.fields.dayOfMonth = []);
expectError(interval.fields.dayOfMonth.push(1));
expectError(interval.fields.month = []);
expectError(interval.fields.month.push(1));
expectError(interval.fields.dayOfWeek = []);
expectError(interval.fields.dayOfWeek.push(1));
expectAssignable<typeof interval.fields.second[0]>(0);
expectAssignable<typeof interval.fields.second[0]>(59);
expectAssignable<typeof interval.fields.minute[0]>(0);
expectAssignable<typeof interval.fields.minute[0]>(59);
expectAssignable<typeof interval.fields.hour[0]>(0);
expectAssignable<typeof interval.fields.hour[0]>(23);
expectAssignable<typeof interval.fields.dayOfMonth[0]>(1);
expectAssignable<typeof interval.fields.dayOfMonth[0]>(31);
expectAssignable<typeof interval.fields.dayOfMonth[0]>('L');
expectAssignable<typeof interval.fields.month[0]>(1);
expectAssignable<typeof interval.fields.month[0]>(12);
expectAssignable<typeof interval.fields.dayOfWeek[0]>(0);
expectAssignable<typeof interval.fields.dayOfWeek[0]>(7);
const parseOptions: ParserOptions<true> = {
currentDate: 'f',
startDate: 4,
endDate: new Date(),
iterator: true,
utc: true,
tz: 'f',
nthDayOfWeek: 5,
}
expectAssignable<{
currentDate?: string | number | Date
startDate?: string | number | Date
endDate?: string | number | Date
iterator?: boolean
utc?: boolean
tz?: string
nthDayOfWeek?: number
}>(parseOptions)
expectType<CronExpression>(parseExpression('0 1 2 3 * 1-3,5'))
expectType<CronExpression<true>>(parseExpression('0 1 2 3 * 1-3,5', parseOptions))
const fields: CronFields = {
second: [1, 1],
minute: [1],
hour: [1],
dayOfMonth: [1],
month: [1],
dayOfWeek: [1],
}
expectType<CronExpression>(fieldsToExpression(fields))
expectType<CronExpression<true>>(fieldsToExpression(fields, parseOptions))
expectType<string>(fieldsToExpression(fields).stringify())
expectType<string>(fieldsToExpression(fields, parseOptions).stringify())
expectType<string>(fieldsToExpression(fields, parseOptions).stringify(true))
expectType<void>(parseFile('path', (err: any, data: StringResult) => console.log(data)))
expectType<StringResult>(parseString('path'))
const stringResult = parseString('path');
expectType<{
variables: Record<string, string>,
expressions: CronExpression[],
errors: Record<string, any>,
}>(stringResult)
expectType<CronFields>(interval.fields)
expectType<CronDate>(interval.next())
expectType<CronDate>(interval.prev())
expectType<boolean>(interval.hasNext())
expectType<boolean>(interval.hasPrev())
expectType<string>(interval.stringify())
expectType<string>(interval.stringify(true))
expectType<void>(interval.reset())
expectType<void>(interval.reset("Sdf"))
expectType<void>(interval.reset(5))
expectType<void>(interval.reset(new Date()))
expectType<CronDate[]>(interval.iterate(5))
expectType<CronDate[]>(interval.iterate(5, (item: CronDate, i: number) => {}))
expectAssignable<DateType>(new Date())
expectAssignable<DateType>(5)
expectAssignable<DateType>("SDf")
expectType<IteratorResult<CronDate, CronDate>>(intervalIterator.next())
expectType<IteratorResult<CronDate, CronDate>>(intervalIterator.prev())
expectType<IteratorResult<CronDate, CronDate>[]>(intervalIterator.iterate(5))
expectType<IteratorResult<CronDate, CronDate>[]>(intervalIterator.iterate(5, (item: IteratorResult<CronDate, CronDate>, i: number) => {}))
import {expectAssignable, expectError, expectNotAssignable, expectType} from 'tsd';
import {
CronDate,
CronExpression,
CronFields, DateType,
parseExpression,
parseFile, ParserOptions,
parseString,
fieldsToExpression,
StringResult
} from '../index';
const interval = parseExpression('0 1 2 3 * 1-3,5');
const intervalIterator = parseExpression('0 1 2 3 * 1-3,5', {iterator: true});
expectError(interval.fields = interval.fields);
expectError(interval.fields.second = []);
expectError(interval.fields.second.push(1));
expectError(interval.fields.minute = []);
expectError(interval.fields.minute.push(1));
expectError(interval.fields.hour = []);
expectError(interval.fields.hour.push(1));
expectError(interval.fields.dayOfMonth = []);
expectError(interval.fields.dayOfMonth.push(1));
expectError(interval.fields.month = []);
expectError(interval.fields.month.push(1));
expectError(interval.fields.dayOfWeek = []);
expectError(interval.fields.dayOfWeek.push(1));
expectAssignable<typeof interval.fields.second[0]>(0);
expectAssignable<typeof interval.fields.second[0]>(59);
expectNotAssignable<typeof interval.fields.second[0]>(-1);
expectNotAssignable<typeof interval.fields.second[0]>(60);
expectAssignable<typeof interval.fields.minute[0]>(0);
expectAssignable<typeof interval.fields.minute[0]>(59);
expectNotAssignable<typeof interval.fields.minute[0]>(-1);
expectNotAssignable<typeof interval.fields.minute[0]>(60);
expectAssignable<typeof interval.fields.hour[0]>(0);
expectAssignable<typeof interval.fields.hour[0]>(23);
expectNotAssignable<typeof interval.fields.hour[0]>(-1);
expectNotAssignable<typeof interval.fields.hour[0]>(24);
expectAssignable<typeof interval.fields.dayOfMonth[0]>(1);
expectAssignable<typeof interval.fields.dayOfMonth[0]>(31);
expectAssignable<typeof interval.fields.dayOfMonth[0]>('L');
expectNotAssignable<typeof interval.fields.dayOfMonth[0]>(0);
expectNotAssignable<typeof interval.fields.dayOfMonth[0]>(32);
expectAssignable<typeof interval.fields.month[0]>(1);
expectAssignable<typeof interval.fields.month[0]>(12);
expectNotAssignable<typeof interval.fields.month[0]>(0);
expectNotAssignable<typeof interval.fields.month[0]>(13);
expectAssignable<typeof interval.fields.dayOfWeek[0]>(0);
expectAssignable<typeof interval.fields.dayOfWeek[0]>(7);
expectNotAssignable<typeof interval.fields.dayOfWeek[0]>(-1);
expectNotAssignable<typeof interval.fields.dayOfWeek[0]>(8);
const parseOptions: ParserOptions<true> = {
currentDate: 'f',
startDate: 4,
endDate: new Date(),
iterator: true,
utc: true,
tz: 'f',
nthDayOfWeek: 5,
}
expectAssignable<{
currentDate?: string | number | Date
startDate?: string | number | Date
endDate?: string | number | Date
iterator?: boolean
utc?: boolean
tz?: string
nthDayOfWeek?: number
}>(parseOptions)
expectType<CronExpression>(parseExpression('0 1 2 3 * 1-3,5'))
expectType<CronExpression<true>>(parseExpression('0 1 2 3 * 1-3,5', parseOptions))
const fields: CronFields = {
second: [1, 1],
minute: [1],
hour: [1],
dayOfMonth: [1],
month: [1],
dayOfWeek: [1],
}
expectType<CronExpression>(fieldsToExpression(fields))
expectType<CronExpression<true>>(fieldsToExpression(fields, parseOptions))
expectType<string>(fieldsToExpression(fields).stringify())
expectType<string>(fieldsToExpression(fields, parseOptions).stringify())
expectType<string>(fieldsToExpression(fields, parseOptions).stringify(true))
expectType<void>(parseFile('path', (err: any, data: StringResult) => console.log(data)))
expectType<StringResult>(parseString('path'))
const stringResult = parseString('path');
expectType<{
variables: Record<string, string>,
expressions: CronExpression[],
errors: Record<string, any>,
}>(stringResult)
expectType<CronFields>(interval.fields)
expectType<CronDate>(interval.next())
expectType<CronDate>(interval.prev())
expectType<boolean>(interval.hasNext())
expectType<boolean>(interval.hasPrev())
expectType<string>(interval.stringify())
expectType<string>(interval.stringify(true))
expectType<void>(interval.reset())
expectType<void>(interval.reset("Sdf"))
expectType<void>(interval.reset(5))
expectType<void>(interval.reset(new Date()))
expectType<CronDate[]>(interval.iterate(5))
expectType<CronDate[]>(interval.iterate(5, (item: CronDate, i: number) => {}))
expectAssignable<DateType>(new Date())
expectAssignable<DateType>(5)
expectAssignable<DateType>("SDf")
expectType<IteratorResult<CronDate, CronDate>>(intervalIterator.next())
expectType<IteratorResult<CronDate, CronDate>>(intervalIterator.prev())
expectType<IteratorResult<CronDate, CronDate>[]>(intervalIterator.iterate(5))
expectType<IteratorResult<CronDate, CronDate>[]>(intervalIterator.iterate(5, (item: IteratorResult<CronDate, CronDate>, i: number) => {}))
var util = require('util');
var test = require('tap').test;
var expression = require('../lib/expression');
test('leap year', function(t) {
try {
var interval = expression.parse('0 0 29 2 *');
var i;
var d;
for (i = 0; i < 20; ++i) {
d = interval.next();
}
t.end();
} catch (err) {
t.error(err, 'Interval parse error');
}
});
var test = require('tap').test;
var CronParser = require('../lib/parser');
// Globals
test('load crontab file', function(t) {
CronParser.parseFile(__dirname + '/crontab.example', function(err, result) {
t.error(err, 'File read error');
t.ok(result, 'Crontab parsed parsed');
t.equal(Object.keys(result.variables).length, 2, 'variables length matches');
t.equal(Object.keys(result.errors).length, 0, 'errors length matches');
t.equal(result.expressions.length, 3, 'expressions length matches');
// Parse expressions
var next = null;
t.equal(result.expressions[0].hasNext(), true);
next = result.expressions[0].next();
t.ok(next, 'first date');
next = result.expressions[1].next();
t.ok(next, 'second date');
next = result.expressions[2].next();
t.ok(next, 'third date');
t.end();
});
});
test('no next date', function(t) {
var options = {
currentDate: new Date(2014, 0, 1),
endDate: new Date(2014, 0, 1)
};
try {
var interval = CronParser.parseExpression('* * 2 * *', options);
t.equal(interval.hasNext(), false);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
var luxon = require('luxon');
var test = require('tap').test;
var CronDate = require('../lib/date');
test('parse cron date formats with local timezone', (t) => {
// Some tests need the local offset to be compatible without invoking timezone management.
// Local offset is dependent on what the system being tested on is
var offset = new Date().getTimezoneOffset();
var offsetHours = Math.abs(Math.floor(offset/60));
var offsetMinutes = offset % 60;
var offsetSign = offset < 0 ? '-' : '+';
var expectedTime = new Date(2021, 0, 4, 10, 0, 0).toString();
test('undefined date', (t) => {
const realDate = new Date();
var d = new CronDate();
t.equal(d.toDate().toString(), realDate.toString());
t.end();
});
test('JS Date', (t) => {
var d = new CronDate(new Date(2021, 0, 4, 10, 0, 0));
t.equal(d.toDate().toString(), expectedTime);
t.end();
});
test('ISO 8601', (t) => {
var d = new CronDate('2021-01-04T10:00:00');
t.equal(d.toDate().toString(), expectedTime);
t.end();
});
test('ISO 8601 date', (t) => {
var d = new CronDate('2021-01-04');
var expectedTime = new Date(2021, 0, 4, 0, 0, 0).toString();
t.equal(d.toDate().toString(), expectedTime);
t.end();
});
test('RFC2822', (t) => {
var offsetString = offsetSign + String(offsetHours).padStart(2, 0) + String(offsetMinutes).padStart(2, 0);
var d = new CronDate('Mon, 4 Jan 2021 10:00:00 ' + offsetString);
t.equal(d.toDate().toString(), expectedTime);
t.end();
});
test('RFC2822-like without timezone offset', (t) => {
var d = new CronDate('Mon, 4 Jan 2021 10:00:00');
t.equal(d.toDate().toString(), expectedTime);
t.end();
});
test('SQL', (t) => {
var d = new CronDate('2021-01-04 10:00:00');
t.equal(d.toDate().toString(), expectedTime);
t.end();
});
test('milliseconds', (t) => {
var d = new CronDate(new Date('2021-01-04 10:00:00').valueOf());
t.equal(d.toDate().toString(), expectedTime);
t.end();
});
test('CronDate', (t) => {
var date = new CronDate('Mon, 4 Jan 2021 10:00:00');
var d = new CronDate(date);
t.equal(d.toDate().toString(), expectedTime);
t.end();
});
test('invalid', (t) => {
t.throws(() => {
var d = new CronDate('2021-01-4 10:00:00');
});
t.end();
});
t.end();
});
test('parse cron date formats with another timezone', (t) => {
test('ISO 8601 without offset', (t) => {
// implies format already in timezone
var d = new CronDate('2021-01-04T10:00:00', 'Europe/Athens');
t.equal(d.toISOString(), '2021-01-04T08:00:00.000Z');
t.end();
});
test('ISO 8601 with non-local offset', (t) => {
var d = new CronDate('2021-01-04T10:00:00+01:00', 'Europe/Athens');
t.equal(d.toISOString(), '2021-01-04T09:00:00.000Z');
t.end();
});
test('RFC2822 with non-local offset', (t) => {
var d = new CronDate('Mon, 4 Jan 2021 10:00:00 +0100', 'Europe/Athens');
t.equal(d.toISOString(), '2021-01-04T09:00:00.000Z');
t.end();
});
test('milliseconds', (t) => {
var date = luxon.DateTime.fromISO('2021-01-04T11:00:00.000+02:00').valueOf();
var d = new CronDate(date, 'Europe/Athens');
t.equal(d.toISOString(), '2021-01-04T09:00:00.000Z');
t.end();
});
test('CronDate with same timezone', (t) => {
var date = new CronDate('Mon, 4 Jan 2021 10:00:00', 'Europe/Athens');
var d = new CronDate(date);
t.equal(d.toISOString(), '2021-01-04T08:00:00.000Z');
t.end();
});
test('CronDate with different timezone', (t) => {
var date = new CronDate('Mon, 4 Jan 2021 10:00:00', 'America/New_York');
var d = new CronDate(date, 'Europe/Athens');
t.equal(d.toISOString(), '2021-01-04T15:00:00.000Z');
t.end();
});
t.end('crondate input should');
});
var util = require('util');
var test = require('tap').test;
var CronParser = require('../lib/parser');
test('parse cron with last day in a month', function(t) {
var options = {
currentDate: new Date(2014, 0, 1),
endDate: new Date(2014, 10, 1)
};
try {
var interval = CronParser.parseExpression('0 0 L * *', options);
t.equal(interval.hasNext(), true);
for (i = 0; i < 10; ++i) {
var next = interval.next();
t.ok(next, 'has a date');
}
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('parse cron with last day in feb', function(t) {
var options = {
currentDate: new Date(2016, 0, 1),
endDate: new Date(2016, 10, 1)
};
try {
var interval = CronParser.parseExpression('0 0 6-20/2,L 2 *', options);
t.equal(interval.hasNext(), true);
var next = null;
var items = 9;
var i = 0;
while(interval.hasNext()) {
next = interval.next();
i += 1;
t.ok(next, 'has a date');
}
//leap year
t.equal(next.getDate(), 29);
t.equal(i, items);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('parse cron with last day in feb', function(t) {
var options = {
currentDate: new Date(2014, 0, 1),
endDate: new Date(2014, 10, 1)
};
try {
var interval = CronParser.parseExpression('0 0 1,3,6-10,L 2 *', options);
t.equal(interval.hasNext(), true);
var next = null;
while(interval.hasNext()) {
next = interval.next();
t.ok(next, 'has a date');
}
//common year
t.equal(next.getDate(), 28);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
var test = require('tap').test;
var CronExpression = require('../lib/expression');
test('prev should match correctly (issue #98) when milliseconds are greater than 0', function(t) {
var options = {
currentDate: new Date('2017-06-13T18:21:25.002Z')
};
var interval = CronExpression.parse('*/5 * * * * *', options);
var prev = interval.prev();
t.equal(prev.getSeconds(), 25);
t.end();
});
test('prev should match correctly (issue #98) when milliseconds are equal to 0', function(t) {
var interval = CronExpression.parse('59 59 23 * * *',{
currentDate : new Date('2012-12-26 14:38:53')
});
[25, 24, 23, 22].forEach(function(date) {
var prev = interval.prev();
t.equal(prev.getFullYear(), 2012);
t.equal(prev.getMonth(), 11);
t.equal(prev.getDate(), date);
t.equal(prev.getHours(), 23);
t.equal(prev.getMinutes(), 59);
t.equal(prev.getSeconds(), 59);
});
t.end();
});
'use strict';
var test = require('tap').test;
var CronParser = require('../lib/parser');
test('stringify cron expression all stars no seconds', function (t) {
try {
var expected = '0 * * * * *';
var interval = CronParser.parseExpression('* * * * *', {});
var str = interval.stringify(true);
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify(true);
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression all stars no seconds (discard seconds)', function (t) {
try {
var expected = '* * * * *';
var interval = CronParser.parseExpression('* * * * *', {});
var str = interval.stringify();
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify();
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression all stars with seconds', function (t) {
try {
var expected = '* * * * * *';
var interval = CronParser.parseExpression('* * * * * *', {});
var str = interval.stringify(true);
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify(true);
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression all stars with seconds (discard seconds)', function (t) {
try {
var expected = '* * * * *';
var interval = CronParser.parseExpression('* * * * * *', {});
var str = interval.stringify();
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify();
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression', function (t) {
try {
var expected = '0 1,2,4-10,20-35/5,57 * * * *';
var interval = CronParser.parseExpression('1,2,4-10,20-35/5,57 * * * *', {});
var str = interval.stringify(true);
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify(true);
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression (discard seconds)', function (t) {
try {
var expected = '1,2,4-10,20-35/5,57 * * * *';
var interval = CronParser.parseExpression('1,2,4-10,20-35/5,57 * * * *', {});
var str = interval.stringify();
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify();
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression with star range step', function (t) {
try {
var expected = '0 */5 */2 * * *';
var interval = CronParser.parseExpression('*/5 */2 */1 * *', {});
var str = interval.stringify(true);
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify(true);
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression with star range step (discard seconds)', function (t) {
try {
var expected = '*/5 */2 * * *';
var interval = CronParser.parseExpression('*/5 */2 */1 * *', {});
var str = interval.stringify();
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify();
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression with semi range step', function (t) {
try {
var expected = '0 5/5 * * * *';
var interval = CronParser.parseExpression('5/5 * * * *', {});
var str = interval.stringify(true);
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify(true);
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression with semi range step (discard seconds)', function (t) {
try {
var expected = '5/5 * * * *';
var interval = CronParser.parseExpression('5/5 * * * *', {});
var str = interval.stringify();
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify();
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression with L', function (t) {
try {
var expected = '0 * * 1,4-10,L * *';
var interval = CronParser.parseExpression('* * 1,4-10,L * *', {});
var str = interval.stringify(true);
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify(true);
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify cron expression with L (discard seconds)', function (t) {
try {
var expected = '* * 1,4-10,L * *';
var interval = CronParser.parseExpression('* * 1,4-10,L * *', {});
var str = interval.stringify();
t.equal(str, expected);
str = CronParser.fieldsToExpression(interval.fields).stringify();
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify from fields out of order', function (t) {
try {
var expected = '1-5 1 1 1 1 1';
var str = CronParser.fieldsToExpression({
second: [5,2,1,4,3],
minute: [1],
hour: [1],
month: [1],
dayOfMonth: [1],
dayOfWeek: [1],
}).stringify(true);
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('stringify from fields out of order (discard seconds)', function (t) {
try {
var expected = '1 1 1 1 1';
var str = CronParser.fieldsToExpression({
second: [5,2,1,4,3],
minute: [1],
hour: [1],
month: [1],
dayOfMonth: [1],
dayOfWeek: [1],
}).stringify();
t.equal(str, expected);
} catch (err) {
t.error(err, 'Parse read error');
}
t.end();
});
test('validation error - missing seconds', function (t) {
t.throws(function () {
CronParser.fieldsToExpression({
minute: [1],
hour: [1],
dayOfMonth: [1],
month: [1],
dayOfWeek: [1],
});
}, new Error('Validation error, Field second is missing'));
t.end();
});
test('validation error - empty seconds', function (t) {
t.throws(function () {
CronParser.fieldsToExpression({
second: [],
minute: [1],
hour: [1],
dayOfMonth: [1],
month: [1],
dayOfWeek: [1],
});
}, new Error('Validation error, Field second contains no values'));
t.end();
});
test('validation error - missing values - empty array', function (t) {
t.throws(function () {
CronParser.fieldsToExpression({
second: [1],
minute: [],
hour: [1],
dayOfMonth: [1],
month: [1],
dayOfWeek: [1],
});
}, new Error('Validation error, Field minute contains no values'));
t.end();
});
test('validation error - missing values', function (t) {
t.throws(function () {
CronParser.fieldsToExpression({
second: [1],
hour: [1],
dayOfMonth: [1],
month: [1],
dayOfWeek: [1],
});
}, new Error('Validation error, Field minute is missing'));
t.end();
});
test('validation error - range error', function (t) {
t.throws(function () {
CronParser.fieldsToExpression({
second: [-1, 1, 0],
minute: [1],
hour: [1],
dayOfMonth: [1],
month: [1],
dayOfWeek: [1],
});
}, new Error('Constraint error, got value -1 expected range 0-59'));
t.end();
});
test('validation error - bad chars error', function (t) {
t.throws(function () {
CronParser.fieldsToExpression({
second: [0, 'R'],
minute: [1],
hour: [1],
dayOfMonth: [1],
month: [1],
dayOfWeek: [1],
});
}, new Error('Constraint error, got value R expected range 0-59'));
t.end();
});
test('validation error - duplicates', function (t) {
t.throws(function () {
CronParser.fieldsToExpression({
second: [1, 1],
minute: [1],
hour: [1],
dayOfMonth: [1],
month: [1],
dayOfWeek: [1],
});
}, new Error('Validation error, Field second contains duplicate values'));
t.end();
});
var test = require('tap').test;
var CronExpression = require('../lib/expression');
test('It works on DST start', function(t) {
try {
var options = {
currentDate: '2016-03-27 02:00:01',
tz: 'Europe/Athens'
};
var interval, date;
interval = CronExpression.parse('0 * * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 4, 'Due to DST start in Athens, 3 is skipped');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 5, '5 AM');
t.equal(date.getDate(), 27, 'on the 27th');
interval = CronExpression.parse('30 2 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getMinutes(), 30, '30 Minutes');
t.equal(date.getHours(), 2, '2 AM');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 30, '30 Minutes');
t.equal(date.getHours(), 2, '2 AM');
t.equal(date.getDate(), 28, 'on the 28th');
interval = CronExpression.parse('0 3 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 4, 'Due to DST start in Athens, 3 is skipped');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 3, '3 on the 28th');
t.equal(date.getDate(), 28, 'on the 28th');
interval = CronExpression.parse('*/20 3 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 4, 'Due to DST start in Athens, 3 is skipped');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 20, '20 Minutes');
t.equal(date.getHours(), 4, 'Due to DST start in Athens, 3 is skipped');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 40, '20 Minutes');
t.equal(date.getHours(), 4, 'Due to DST start in Athens, 3 is skipped');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 28, 'on the 28th');
options.currentDate = '2016-03-27 00:00:01';
interval = CronExpression.parse('0 * 27 * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 1, '1 AM');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 2, '2 AM');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 4, '4 AM');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 5, '5 AM');
t.equal(date.getDate(), 27, 'on the 27th');
options.currentDate = '2016-03-27 00:00:01';
options.endDate = '2016-03-27 03:00:01';
interval = CronExpression.parse('0 * * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 1, '1 AM');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 2, '2 AM');
t.equal(date.getDate(), 27, 'on the 27th');
date = interval.next();
t.equal(date.getMinutes(), 0, '0 Minutes');
t.equal(date.getHours(), 4, '4 AM');
t.equal(date.getDate(), 27, 'on the 27th');
// Out of the timespan range
t.throws(function() {
date = interval.next();
});
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('It works on DST end', function(t) {
try {
var options = {
currentDate: '2016-10-30 02:00:01',
tz: 'Europe/Athens'
};
var interval, date;
interval = CronExpression.parse('0 * * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 3, 'Due to DST end in Athens (4-->3)');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 4, '4 AM');
t.equal(date.getDate(), 30, '30th');
interval = CronExpression.parse('0 3 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 31, '31st');
interval = CronExpression.parse('*/20 3 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getMinutes(), 0, '0');
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getMinutes(), 20, '20');
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getMinutes(), 40, '40');
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getMinutes(), 0, '0');
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 31, '31st');
options.currentDate = '2016-10-30 00:00:01';
interval = CronExpression.parse('0 * 30 * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 1, '1 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 2, '2 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 4, '4 AM');
t.equal(date.getDate(), 30, '30th');
options.currentDate = '2016-10-30 00:00:01';
// specify the DST offset via ISO 8601 format, as 3am is repeated
options.endDate = '2016-10-30T03:00:01+03';
interval = CronExpression.parse('0 * * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 1, '1 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 2, '2 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
// Out of the timespan range
t.throws(function() {
date = interval.next();
});
options.endDate = '2016-10-30 04:00:01';
interval = CronExpression.parse('0 * * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 1, '1 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 2, '2 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 3, '3 AM');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 4, '4 AM');
t.equal(date.getDate(), 30, '30th');
// Out of the timespan range
t.throws(function() {
date = interval.next();
});
options = {
currentDate : new Date('Sun Oct 29 2016 01:00:00 GMT+0200')
};
interval = CronExpression.parse('0 12 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 29, '29th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 31, '31st');
options = {
currentDate : new Date('Sun Oct 29 2016 02:59:00 GMT+0200')
};
interval = CronExpression.parse('0 12 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 29, '29th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 31, '31st');
options = {
currentDate : new Date('Sun Oct 29 2016 02:59:59 GMT+0200')
};
interval = CronExpression.parse('0 12 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 29, '29th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 31, '31st');
options = {
currentDate : new Date('Sun Oct 30 2016 01:00:00 GMT+0200')
};
interval = CronExpression.parse('0 12 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 31, '31st');
options = {
currentDate : new Date('Sun Oct 30 2016 01:59:00 GMT+0200')
};
interval = CronExpression.parse('0 12 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 31, '31st');
options = {
currentDate : new Date('Sun Oct 30 2016 01:59:59 GMT+0200')
};
interval = CronExpression.parse('0 12 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 31, '31st');
options = {
currentDate : new Date('Sun Oct 30 2016 02:59:00 GMT+0200')
};
interval = CronExpression.parse('0 12 * * *', options);
t.ok(interval, 'Interval parsed');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 30, '30th');
date = interval.next();
t.equal(date.getHours(), 12, '12');
t.equal(date.getDate(), 31, '31st');
} catch (err) {
t.error(err, 'Interval parse error');
}
t.end();
});
test('it will work with #131 issue case', function(t) {
var options = {
tz: 'America/Sao_Paulo',
currentDate : new Date('Sun Oct 30 2018 02:59:00 GMT+0200')
};
var interval = CronExpression.parse('0 9 1 1 *', options);
var date = interval.next();
t.equal(date.getFullYear(), 2019);
t.equal(date.getDate(), 1);
t.equal(date.getMonth(), 0);
date = interval.prev();
t.equal(date.getFullYear(), 2018);
t.equal(date.getDate(), 1);
t.equal(date.getMonth(), 0);
date = interval.prev();
t.equal(date.getFullYear(), 2017);
t.equal(date.getDate(), 1);
t.equal(date.getMonth(), 0);
t.end();
});
test('it will work with #137 issue case', function(t) {
var options = {
tz: 'America/New_York',
currentDate : new Date('10/28/2018')
};
var interval = CronExpression.parse('0 12 * * 3', options);
var date = interval.next();
t.equal(date.getFullYear(), 2018);
t.equal(date.getDate(), 31);
t.equal(date.getMonth(), 9);
t.end();
});
export type DateType = Date | number | string
export interface CronDate {
addYear(): void
addMonth(): void
addDay(): void
addHour(): void
addMinute(): void
addSecond(): void
subtractYear(): void
subtractMonth(): void
subtractDay(): void
subtractHour(): void
subtractMinute(): void
subtractSecond(): void
getDate(): number
getFullYear(): number
getDay(): number
getMonth(): number
getHours(): number
getMinutes(): number
getSeconds(): number
getMilliseconds(): number
getTime(): number
getUTCDate(): number
getUTCFullYear(): number
getUTCDay(): number
getUTCMonth(): number
getUTCHours(): number
getUTCMinutes(): number
getUTCSeconds(): number
toISOString(): string
toJSON(): string
setDate(d: number): void
setFullYear(y: number): void
setDay(d: number): void
setMonth(m: number): void
setHours(h: number): void
setMinutes(m: number): void
setSeconds(s: number): void
setMilliseconds(s: number): void
getTime(): number
toString(): string
toDate(): Date
isLastDayOfMonth(): boolean
}
export interface ParserOptions<IsIterable extends boolean = false> {
currentDate?: DateType
startDate?: DateType
endDate?: DateType
utc?: boolean
tz?: string
nthDayOfWeek?: number
iterator?: IsIterable
}
type IteratorResultOrCronDate<IsIterable extends boolean> = IsIterable extends true
? IteratorResult<CronDate, CronDate>
: CronDate;
export interface ICronExpression<CronFields, IsIterable extends boolean> {
readonly fields: CronFields;
/** Find next suitable date */
next(): IteratorResultOrCronDate<IsIterable>
/** Find previous suitable date */
prev(): IteratorResultOrCronDate<IsIterable>
/** Check if next suitable date exists */
hasNext(): boolean
/** Check if previous suitable date exists */
hasPrev(): boolean
/** Iterate over expression iterator */
iterate(steps: number, callback?: (item: IteratorResultOrCronDate<IsIterable>, i: number) => void): IteratorResultOrCronDate<IsIterable>[]
/** Reset expression iterator state */
reset(resetDate?: string | number | Date): void
stringify(includeSeconds?: boolean): string
}
export interface IStringResult<CronFields> {
variables: Record<string, string>,
expressions: ICronExpression<CronFields, false>[],
errors: Record<string, any>,
}
import {
CronDate,
DateType,
ICronExpression,
IStringResult,
ParserOptions,
} from './common';
type BuildRangeTuple<Current extends [...number[]], Count extends number> =
Current["length"] extends Count
? Current
: BuildRangeTuple<[number, ...Current], Count>
type RangeTuple<Count extends number> = BuildRangeTuple<[], Count>
type BuildRange<Current extends number, End extends number, Accu extends [...number[]]> =
Accu["length"] extends End
? Current
: BuildRange<Current | Accu["length"], End, [number, ...Accu]>
type Range<StartInclusive extends number, EndExclusive extends number> = BuildRange<StartInclusive, EndExclusive, RangeTuple<StartInclusive>>
export type SixtyRange = Range<0, 30> | Range<30, 60>; // Typescript restriction on recursion depth
export type HourRange = Range<0, 24>;
export type DayOfTheMonthRange = Range<1, 32> | 'L';
export type MonthRange = Range<1, 13>;
export type DayOfTheWeekRange = Range<0, 8>;
export type CronFields = {
readonly second: readonly SixtyRange[];
readonly minute: readonly SixtyRange[];
readonly hour: readonly HourRange[];
readonly dayOfMonth: readonly DayOfTheMonthRange[];
readonly month: readonly MonthRange[];
readonly dayOfWeek: readonly DayOfTheWeekRange[];
}
export {ParserOptions, CronDate, DateType}
export type CronExpression<IsIterable extends boolean = false> = ICronExpression<CronFields, IsIterable>
export type StringResult = IStringResult<CronFields>
export function parseExpression<IsIterable extends boolean = false>(expression: string, options?: ParserOptions<IsIterable>): CronExpression<IsIterable>;
export function fieldsToExpression<IsIterable extends boolean = false>(fields: CronFields, options?: ParserOptions<IsIterable>): CronExpression<IsIterable>;
export function parseFile(filePath: string, callback: (err: any, data: StringResult) => any): void;
export function parseString(data: string): StringResult;
import {
CronDate,
DateType,
ICronExpression,
IStringResult,
ParserOptions,
} from '../common';
export type CronFields = {
readonly second: readonly number[];
readonly minute: readonly number[];
readonly hour: readonly number[];
readonly dayOfMonth: readonly (number | 'L')[];
readonly month: readonly number[];
readonly dayOfWeek: readonly number[];
}
export {ParserOptions, CronDate, DateType}
export type CronExpression<IsIterable extends boolean = false> = ICronExpression<CronFields, IsIterable>
export type StringResult = IStringResult<CronFields>
export function parseExpression<IsIterable extends boolean = false>(expression: string, options?: ParserOptions<IsIterable>): CronExpression<IsIterable>;
export function fieldsToExpression<IsIterable extends boolean = false>(fields: CronFields, options?: ParserOptions<IsIterable>): CronExpression<IsIterable>;
export function parseFile(filePath: string, callback: (err: any, data: StringResult) => any): void;
export function parseString(data: string): StringResult;
root = true
[*]
indent_style = tab;
insert_final_newline = true;
quote_type = auto;
space_after_anonymous_functions = true;
space_after_control_statements = true;
spaces_around_operators = true;
trim_trailing_whitespace = true;
spaces_in_brackets = false;
end_of_line = lf;
{
"root": true,
"extends": "@ljharb",
"rules": {
"id-length": [2, { "min": 1, "max": 35 }],
"max-lines-per-function": [2, 100],
"max-params": [2, 4],
"max-statements": [2, 13]
}
}
{
"es3": true,
"additionalRules": [],
"requireSemicolons": true,
"disallowMultipleSpaces": true,
"disallowIdentifierNames": [],
"requireCurlyBraces": {
"allExcept": [],
"keywords": ["if", "else", "for", "while", "do", "try", "catch"]
},
"requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"],
"disallowSpaceAfterKeywords": [],
"disallowSpaceBeforeComma": true,
"disallowSpaceAfterComma": false,
"disallowSpaceBeforeSemicolon": true,
"disallowNodeTypes": [
"DebuggerStatement",
"LabeledStatement",
"SwitchCase",
"SwitchStatement",
"WithStatement"
],
"requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] },
"requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true },
"requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true },
"disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true },
"requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true },
"disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true },
"requireSpaceBetweenArguments": true,
"disallowSpacesInsideParentheses": true,
"disallowSpacesInsideArrayBrackets": true,
"disallowQuotedKeysInObjects": { "allExcept": ["reserved"] },
"disallowSpaceAfterObjectKeys": true,
"requireCommaBeforeLineBreak": true,
"disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
"requireSpaceAfterPrefixUnaryOperators": [],
"disallowSpaceBeforePostfixUnaryOperators": ["++", "--"],
"requireSpaceBeforePostfixUnaryOperators": [],
"disallowSpaceBeforeBinaryOperators": [],
"requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
"requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
"disallowSpaceAfterBinaryOperators": [],
"disallowImplicitTypeConversion": ["binary", "string"],
"disallowKeywords": ["with", "eval"],
"requireKeywordsOnNewLine": [],
"disallowKeywordsOnNewLine": ["else"],
"requireLineFeedAtFileEnd": true,
"disallowTrailingWhitespace": true,
"disallowTrailingComma": true,
"excludeFiles": ["node_modules/**", "vendor/**"],
"disallowMultipleLineStrings": true,
"requireDotNotation": { "allExcept": ["keywords"] },
"requireParenthesesAroundIIFE": true,
"validateLineBreaks": "LF",
"validateQuoteMarks": {
"escape": true,
"mark": "'"
},
"disallowOperatorBeforeLineBreak": [],
"requireSpaceBeforeKeywords": [
"do",
"for",
"if",
"else",
"switch",
"case",
"try",
"catch",
"finally",
"while",
"with",
"return"
],
"validateAlignedFunctionParameters": {
"lineBreakAfterOpeningBraces": true,
"lineBreakBeforeClosingBraces": true
},
"requirePaddingNewLinesBeforeExport": true,
"validateNewlineAfterArrayElements": {
"maximum": 3
},
"requirePaddingNewLinesAfterUseStrict": true,
"disallowArrowFunctions": true,
"disallowMultiLineTernary": true,
"validateOrderInObjectKeys": "asc-insensitive",
"disallowIdenticalDestructuringNames": true,
"disallowNestedTernaries": { "maxLevel": 1 },
"requireSpaceAfterComma": { "allExcept": ["trailing"] },
"requireAlignedMultilineParams": false,
"requireSpacesInGenerator": {
"afterStar": true
},
"disallowSpacesInGenerator": {
"beforeStar": true
},
"disallowVar": false,
"requireArrayDestructuring": false,
"requireEnhancedObjectLiterals": false,
"requireObjectDestructuring": false,
"requireEarlyReturn": false,
"requireCapitalizedConstructorsNew": {
"allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"]
},
"requireImportAlphabetized": false,
"requireSpaceBeforeObjectValues": true,
"requireSpaceBeforeDestructuredValues": true,
"disallowSpacesInsideTemplateStringPlaceholders": true,
"disallowArrayDestructuringReturn": false,
"requireNewlineBeforeSingleStatementsInIf": false,
"disallowUnusedVariables": true,
"requireSpacesInsideImportedObjectBraces": true,
"requireUseStrict": true
}
language: node_js
os:
- linux
node_js:
- "10.8"
- "9.11"
- "8.11"
- "7.10"
- "6.14"
- "5.12"
- "4.9"
- "iojs-v3.3"
- "iojs-v2.5"
- "iojs-v1.8"
- "0.12"
- "0.10"
- "0.8"
before_install:
- 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac'
- 'nvm install-latest-npm'
install:
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;'
script:
- 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi'
- 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi'
- 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi'
- 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi'
sudo: false
env:
- TEST=true
matrix:
fast_finish: true
include:
- node_js: "lts/*"
env: PRETEST=true
- node_js: "lts/*"
env: POSTTEST=true
- node_js: "4"
env: COVERAGE=true
- node_js: "10.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.13"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.12"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.4"
env: TEST=true ALLOW_FAILURE=true
allow_failures:
- os: osx
- env: TEST=true ALLOW_FAILURE=true
- env: COVERAGE=true
1.1.3 / 2018-08-14
=================
* [Refactor] use a for loop instead of `foreach` to make for smaller bundle sizes
* [Robustness] cache `Array.prototype.concat` and `Object.defineProperty`
* [Deps] update `object-keys`
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `tape`, `jscs`; remove unused eccheck script + dep
* [Tests] use pretest/posttest for linting/security
* [Tests] fix npm upgrades on older nodes
1.1.2 / 2015-10-14
=================
* [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG
* [Deps] Update `object-keys`
* [Dev Deps] update `jscs`, `tape`, `eslint`, `@ljharb/eslint-config`, `nsp`
* [Tests] up to `io.js` `v3.3`, `node` `v4.2`
1.1.1 / 2015-07-21
=================
* [Deps] Update `object-keys`
* [Dev Deps] Update `tape`, `eslint`
* [Tests] Test on `io.js` `v2.4`
1.1.0 / 2015-07-01
=================
* [New] Add support for symbol-valued properties.
* [Dev Deps] Update `nsp`, `eslint`
* [Tests] Test up to `io.js` `v2.3`
1.0.3 / 2015-05-30
=================
* Using a more reliable check for supported property descriptors.
1.0.2 / 2015-05-23
=================
* Test up to `io.js` `v2.0`
* Update `tape`, `jscs`, `nsp`, `eslint`, `object-keys`, `editorconfig-tools`, `covert`
1.0.1 / 2015-01-06
=================
* Update `object-keys` to fix ES3 support
1.0.0 / 2015-01-04
=================
* v1.0.0
The MIT License (MIT)
Copyright (C) 2015 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
#define-properties <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![Build Status][travis-svg]][travis-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
[![browser support][testling-svg]][testling-url]
Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines.
Existing properties are not overridden. Accepts a map of property names to a predicate that, when true, force-overrides.
## Example
```js
var define = require('define-properties');
var assert = require('assert');
var obj = define({ a: 1, b: 2 }, {
a: 10,
b: 20,
c: 30
});
assert(obj.a === 1);
assert(obj.b === 2);
assert(obj.c === 30);
if (define.supportsDescriptors) {
assert.deepEqual(Object.keys(obj), ['a', 'b']);
assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'c'), {
configurable: true,
enumerable: false,
value: 30,
writable: false
});
}
```
Then, with predicates:
```js
var define = require('define-properties');
var assert = require('assert');
var obj = define({ a: 1, b: 2, c: 3 }, {
a: 10,
b: 20,
c: 30
}, {
a: function () { return false; },
b: function () { return true; }
});
assert(obj.a === 1);
assert(obj.b === 20);
assert(obj.c === 3);
if (define.supportsDescriptors) {
assert.deepEqual(Object.keys(obj), ['a', 'c']);
assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'b'), {
configurable: true,
enumerable: false,
value: 20,
writable: false
});
}
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[package-url]: https://npmjs.org/package/define-properties
[npm-version-svg]: http://versionbadg.es/ljharb/define-properties.svg
[travis-svg]: https://travis-ci.org/ljharb/define-properties.svg
[travis-url]: https://travis-ci.org/ljharb/define-properties
[deps-svg]: https://david-dm.org/ljharb/define-properties.svg
[deps-url]: https://david-dm.org/ljharb/define-properties
[dev-deps-svg]: https://david-dm.org/ljharb/define-properties/dev-status.svg
[dev-deps-url]: https://david-dm.org/ljharb/define-properties#info=devDependencies
[testling-svg]: https://ci.testling.com/ljharb/define-properties.png
[testling-url]: https://ci.testling.com/ljharb/define-properties
[npm-badge-png]: https://nodei.co/npm/define-properties.png?downloads=true&stars=true
[license-image]: http://img.shields.io/npm/l/define-properties.svg
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/define-properties.svg
[downloads-url]: http://npm-stat.com/charts.html?package=define-properties
'use strict';
var keys = require('object-keys');
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};
var arePropertyDescriptorsSupported = function () {
var obj = {};
try {
origDefineProperty(obj, 'x', { enumerable: false, value: obj });
// eslint-disable-next-line no-unused-vars, no-restricted-syntax
for (var _ in obj) { // jscs:ignore disallowUnusedVariables
return false;
}
return obj.x === obj;
} catch (e) { /* this is IE 8. */
return false;
}
};
var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
var defineProperty = function (object, name, value, predicate) {
if (name in object && (!isFunction(predicate) || !predicate())) {
return;
}
if (supportsDescriptors) {
origDefineProperty(object, name, {
configurable: true,
enumerable: false,
value: value,
writable: true
});
} else {
object[name] = value;
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = keys(map);
if (hasSymbols) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
{
"name": "define-properties",
"version": "1.1.3",
"author": "Jordan Harband",
"description": "Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines.",
"license": "MIT",
"main": "index.js",
"scripts": {
"pretest": "npm run --silent lint",
"test": "npm run --silent tests-only",
"posttest": "npm run --silent security",
"tests-only": "node test/index.js",
"coverage": "covert test/*.js",
"coverage-quiet": "covert test/*.js --quiet",
"lint": "npm run --silent jscs && npm run --silent eslint",
"jscs": "jscs test/*.js *.js",
"eslint": "eslint test/*.js *.js",
"security": "nsp check"
},
"repository": {
"type": "git",
"url": "git://github.com/ljharb/define-properties.git"
},
"keywords": [
"Object.defineProperty",
"Object.defineProperties",
"object",
"property descriptor",
"descriptor",
"define",
"ES5"
],
"dependencies": {
"object-keys": "^1.0.12"
},
"devDependencies": {
"@ljharb/eslint-config": "^13.0.0",
"covert": "^1.1.0",
"eslint": "^5.3.0",
"jscs": "^3.0.7",
"nsp": "^3.2.1",
"tape": "^4.9.0"
},
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
}
}
'use strict';
var define = require('../');
var test = require('tape');
var keys = require('object-keys');
var arePropertyDescriptorsSupported = function () {
var obj = { a: 1 };
try {
Object.defineProperty(obj, 'x', { value: obj });
return obj.x === obj;
} catch (e) { /* this is IE 8. */
return false;
}
};
var descriptorsSupported = !!Object.defineProperty && arePropertyDescriptorsSupported();
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
test('defineProperties', function (dt) {
dt.test('with descriptor support', { skip: !descriptorsSupported }, function (t) {
var getDescriptor = function (value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
};
var obj = {
a: 1,
b: 2,
c: 3
};
t.deepEqual(keys(obj), ['a', 'b', 'c'], 'all literal-set keys start enumerable');
define(obj, {
b: 3,
c: 4,
d: 5
});
t.deepEqual(obj, {
a: 1,
b: 2,
c: 3
}, 'existing properties were not overridden');
t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'd'), getDescriptor(5), 'new property "d" was added and is not enumerable');
t.deepEqual(['a', 'b', 'c'], keys(obj), 'new keys are not enumerable');
define(obj, {
a: 2,
b: 3,
c: 4
}, {
a: function () { return true; },
b: function () { return false; }
});
t.deepEqual(obj, {
b: 2,
c: 3
}, 'properties only overriden when predicate exists and returns true');
t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'd'), getDescriptor(5), 'existing property "d" remained and is not enumerable');
t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'a'), getDescriptor(2), 'existing property "a" was overridden and is not enumerable');
t.deepEqual(['b', 'c'], keys(obj), 'overridden keys are not enumerable');
t.end();
});
dt.test('without descriptor support', { skip: descriptorsSupported }, function (t) {
var obj = {
a: 1,
b: 2,
c: 3
};
define(obj, {
b: 3,
c: 4,
d: 5
});
t.deepEqual(obj, {
a: 1,
b: 2,
c: 3,
d: 5
}, 'existing properties were not overridden, new properties were added');
define(obj, {
a: 2,
b: 3,
c: 4
}, {
a: function () { return true; },
b: function () { return false; }
});
t.deepEqual(obj, {
a: 2,
b: 2,
c: 3,
d: 5
}, 'properties only overriden when predicate exists and returns true');
t.end();
});
dt.end();
});
test('symbols', { skip: !hasSymbols }, function (t) {
var sym = Symbol('foo');
var obj = {};
var aValue = {};
var bValue = {};
var properties = { a: aValue };
properties[sym] = bValue;
define(obj, properties);
t.deepEqual(Object.keys(obj), [], 'object has no enumerable keys');
t.deepEqual(Object.getOwnPropertyNames(obj), ['a'], 'object has non-enumerable "a" key');
t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'object has non-enumerable symbol key');
t.equal(obj.a, aValue, 'string keyed value is defined');
t.equal(obj[sym], bValue, 'symbol keyed value is defined');
t.end();
});
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 120
[CHANGELOG.md]
indent_style = space
indent_size = 2
[*.json]
max_line_length = off
[Makefile]
max_line_length = off
{
"root": true,
"extends": "@ljharb",
"rules": {
"func-name-matching": 0,
"indent": [2, 4],
"max-nested-callbacks": [2, 3],
"max-params": [2, 3],
"max-statements": [2, 20],
"no-new-func": [1],
"strict": [0]
}
}
{
"es3": true,
"additionalRules": [],
"requireSemicolons": true,
"disallowMultipleSpaces": true,
"disallowIdentifierNames": [],
"requireCurlyBraces": {
"allExcept": [],
"keywords": ["if", "else", "for", "while", "do", "try", "catch"]
},
"requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"],
"disallowSpaceAfterKeywords": [],
"disallowSpaceBeforeComma": true,
"disallowSpaceAfterComma": false,
"disallowSpaceBeforeSemicolon": true,
"disallowNodeTypes": [
"DebuggerStatement",
"ForInStatement",
"LabeledStatement",
"SwitchCase",
"SwitchStatement",
"WithStatement"
],
"requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] },
"requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true },
"requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true },
"disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true },
"requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true },
"disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true },
"requireSpaceBetweenArguments": true,
"disallowSpacesInsideParentheses": true,
"disallowSpacesInsideArrayBrackets": true,
"disallowQuotedKeysInObjects": { "allExcept": ["reserved"] },
"disallowSpaceAfterObjectKeys": true,
"requireCommaBeforeLineBreak": true,
"disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
"requireSpaceAfterPrefixUnaryOperators": [],
"disallowSpaceBeforePostfixUnaryOperators": ["++", "--"],
"requireSpaceBeforePostfixUnaryOperators": [],
"disallowSpaceBeforeBinaryOperators": [],
"requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
"requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
"disallowSpaceAfterBinaryOperators": [],
"disallowImplicitTypeConversion": ["binary", "string"],
"disallowKeywords": ["with", "eval"],
"requireKeywordsOnNewLine": [],
"disallowKeywordsOnNewLine": ["else"],
"requireLineFeedAtFileEnd": true,
"disallowTrailingWhitespace": true,
"disallowTrailingComma": true,
"excludeFiles": ["node_modules/**", "vendor/**"],
"disallowMultipleLineStrings": true,
"requireDotNotation": { "allExcept": ["keywords"] },
"requireParenthesesAroundIIFE": true,
"validateLineBreaks": "LF",
"validateQuoteMarks": {
"escape": true,
"mark": "'"
},
"disallowOperatorBeforeLineBreak": [],
"requireSpaceBeforeKeywords": [
"do",
"for",
"if",
"else",
"switch",
"case",
"try",
"catch",
"finally",
"while",
"with",
"return"
],
"validateAlignedFunctionParameters": {
"lineBreakAfterOpeningBraces": true,
"lineBreakBeforeClosingBraces": true
},
"requirePaddingNewLinesBeforeExport": true,
"validateNewlineAfterArrayElements": {
"maximum": 8
},
"requirePaddingNewLinesAfterUseStrict": true,
"disallowArrowFunctions": true,
"disallowMultiLineTernary": true,
"validateOrderInObjectKeys": "asc-insensitive",
"disallowIdenticalDestructuringNames": true,
"disallowNestedTernaries": { "maxLevel": 1 },
"requireSpaceAfterComma": { "allExcept": ["trailing"] },
"requireAlignedMultilineParams": false,
"requireSpacesInGenerator": {
"afterStar": true
},
"disallowSpacesInGenerator": {
"beforeStar": true
},
"disallowVar": false,
"requireArrayDestructuring": false,
"requireEnhancedObjectLiterals": false,
"requireObjectDestructuring": false,
"requireEarlyReturn": false,
"requireCapitalizedConstructorsNew": {
"allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"]
},
"requireImportAlphabetized": false,
"requireSpaceBeforeObjectValues": true,
"requireSpaceBeforeDestructuredValues": true,
"disallowSpacesInsideTemplateStringPlaceholders": true,
"disallowArrayDestructuringReturn": false,
"requireNewlineBeforeSingleStatementsInIf": false,
"disallowUnusedVariables": true,
"requireSpacesInsideImportedObjectBraces": true,
"requireUseStrict": true
}
# gitignore
.DS_Store
.monitor
.*.swp
.nodemonignore
releases
*.log
*.err
fleet.json
public/browserify
bin/*.json
.bin
build
compile
.lock-wscript
coverage
node_modules
# Only apps should have lockfiles
npm-shrinkwrap.json
package-lock.json
yarn.lock
language: node_js
os:
- linux
node_js:
- "8.4"
- "7.10"
- "6.11"
- "5.12"
- "4.8"
- "iojs-v3.3"
- "iojs-v2.5"
- "iojs-v1.8"
- "0.12"
- "0.10"
- "0.8"
before_install:
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi'
- 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then if [ "${TRAVIS_NODE_VERSION%${TRAVIS_NODE_VERSION#[0-9]}}" = "0" ] || [ "${TRAVIS_NODE_VERSION:0:4}" = "iojs" ]; then npm install -g npm@4.5 ; else npm install -g npm; fi; fi'
install:
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then nvm install 0.8 && npm install -g npm@1.3 && npm install -g npm@1.4.28 && npm install -g npm@2 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;'
script:
- 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi'
- 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi'
- 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi'
- 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi'
sudo: false
env:
- TEST=true
matrix:
fast_finish: true
include:
- node_js: "node"
env: PRETEST=true
- node_js: "4"
env: COVERAGE=true
- node_js: "8.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.4"
env: TEST=true ALLOW_FAILURE=true
allow_failures:
- os: osx
- env: TEST=true ALLOW_FAILURE=true
Copyright (c) 2013 Raynos.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# function-bind
<!--
[![build status][travis-svg]][travis-url]
[![NPM version][npm-badge-svg]][npm-url]
[![Coverage Status][5]][6]
[![gemnasium Dependency Status][7]][8]
[![Dependency status][deps-svg]][deps-url]
[![Dev Dependency status][dev-deps-svg]][dev-deps-url]
-->
<!-- [![browser support][11]][12] -->
Implementation of function.prototype.bind
## Example
I mainly do this for unit tests I run on phantomjs.
PhantomJS does not have Function.prototype.bind :(
```js
Function.prototype.bind = require("function-bind")
```
## Installation
`npm install function-bind`
## Contributors
- Raynos
## MIT Licenced
[travis-svg]: https://travis-ci.org/Raynos/function-bind.svg
[travis-url]: https://travis-ci.org/Raynos/function-bind
[npm-badge-svg]: https://badge.fury.io/js/function-bind.svg
[npm-url]: https://npmjs.org/package/function-bind
[5]: https://coveralls.io/repos/Raynos/function-bind/badge.png
[6]: https://coveralls.io/r/Raynos/function-bind
[7]: https://gemnasium.com/Raynos/function-bind.png
[8]: https://gemnasium.com/Raynos/function-bind
[deps-svg]: https://david-dm.org/Raynos/function-bind.svg
[deps-url]: https://david-dm.org/Raynos/function-bind
[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg
[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies
[11]: https://ci.testling.com/Raynos/function-bind.png
[12]: https://ci.testling.com/Raynos/function-bind
'use strict';
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
'use strict';
var implementation = require('./implementation');
module.exports = Function.prototype.bind || implementation;
{
"name": "function-bind",
"version": "1.1.1",
"description": "Implementation of Function.prototype.bind",
"keywords": [
"function",
"bind",
"shim",
"es5"
],
"author": "Raynos <raynos2@gmail.com>",
"repository": "git://github.com/Raynos/function-bind.git",
"main": "index",
"homepage": "https://github.com/Raynos/function-bind",
"contributors": [
{
"name": "Raynos"
},
{
"name": "Jordan Harband",
"url": "https://github.com/ljharb"
}
],
"bugs": {
"url": "https://github.com/Raynos/function-bind/issues",
"email": "raynos2@gmail.com"
},
"dependencies": {},
"devDependencies": {
"@ljharb/eslint-config": "^12.2.1",
"covert": "^1.1.0",
"eslint": "^4.5.0",
"jscs": "^3.0.7",
"tape": "^4.8.0"
},
"license": "MIT",
"scripts": {
"pretest": "npm run lint",
"test": "npm run tests-only",
"posttest": "npm run coverage -- --quiet",
"tests-only": "node test",
"coverage": "covert test/*.js",
"lint": "npm run jscs && npm run eslint",
"jscs": "jscs *.js */*.js",
"eslint": "eslint *.js */*.js"
},
"testling": {
"files": "test/index.js",
"browsers": [
"ie/8..latest",
"firefox/16..latest",
"firefox/nightly",
"chrome/22..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
}
}
{
"rules": {
"array-bracket-newline": 0,
"array-element-newline": 0,
"max-statements-per-line": [2, { "max": 2 }],
"no-invalid-this": 0,
"no-magic-numbers": 0,
}
}
// jscs:disable requireUseStrict
var test = require('tape');
var functionBind = require('../implementation');
var getCurrentContext = function () { return this; };
test('functionBind is a function', function (t) {
t.equal(typeof functionBind, 'function');
t.end();
});
test('non-functions', function (t) {
var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g];
t.plan(nonFunctions.length);
for (var i = 0; i < nonFunctions.length; ++i) {
try { functionBind.call(nonFunctions[i]); } catch (ex) {
t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i]));
}
}
t.end();
});
test('without a context', function (t) {
t.test('binds properly', function (st) {
var args, context;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
context = this;
})
};
namespace.func(1, 2, 3);
st.deepEqual(args, [1, 2, 3]);
st.equal(context, getCurrentContext.call());
st.end();
});
t.test('binds properly, and still supplies bound arguments', function (st) {
var args, context;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
context = this;
}, undefined, 1, 2, 3)
};
namespace.func(4, 5, 6);
st.deepEqual(args, [1, 2, 3, 4, 5, 6]);
st.equal(context, getCurrentContext.call());
st.end();
});
t.test('returns properly', function (st) {
var args;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
return this;
}, null)
};
var context = namespace.func(1, 2, 3);
st.equal(context, getCurrentContext.call(), 'returned context is namespaced context');
st.deepEqual(args, [1, 2, 3], 'passed arguments are correct');
st.end();
});
t.test('returns properly with bound arguments', function (st) {
var args;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
return this;
}, null, 1, 2, 3)
};
var context = namespace.func(4, 5, 6);
st.equal(context, getCurrentContext.call(), 'returned context is namespaced context');
st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct');
st.end();
});
t.test('called as a constructor', function (st) {
var thunkify = function (value) {
return function () { return value; };
};
st.test('returns object value', function (sst) {
var expectedReturnValue = [1, 2, 3];
var Constructor = functionBind.call(thunkify(expectedReturnValue), null);
var result = new Constructor();
sst.equal(result, expectedReturnValue);
sst.end();
});
st.test('does not return primitive value', function (sst) {
var Constructor = functionBind.call(thunkify(42), null);
var result = new Constructor();
sst.notEqual(result, 42);
sst.end();
});
st.test('object from bound constructor is instance of original and bound constructor', function (sst) {
var A = function (x) {
this.name = x || 'A';
};
var B = functionBind.call(A, null, 'B');
var result = new B();
sst.ok(result instanceof B, 'result is instance of bound constructor');
sst.ok(result instanceof A, 'result is instance of original constructor');
sst.end();
});
st.end();
});
t.end();
});
test('with a context', function (t) {
t.test('with no bound arguments', function (st) {
var args, context;
var boundContext = {};
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
context = this;
}, boundContext)
};
namespace.func(1, 2, 3);
st.equal(context, boundContext, 'binds a context properly');
st.deepEqual(args, [1, 2, 3], 'supplies passed arguments');
st.end();
});
t.test('with bound arguments', function (st) {
var args, context;
var boundContext = {};
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
context = this;
}, boundContext, 1, 2, 3)
};
namespace.func(4, 5, 6);
st.equal(context, boundContext, 'binds a context properly');
st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments');
st.end();
});
t.test('returns properly', function (st) {
var boundContext = {};
var args;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
return this;
}, boundContext)
};
var context = namespace.func(1, 2, 3);
st.equal(context, boundContext, 'returned context is bound context');
st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context');
st.deepEqual(args, [1, 2, 3], 'passed arguments are correct');
st.end();
});
t.test('returns properly with bound arguments', function (st) {
var boundContext = {};
var args;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
return this;
}, boundContext, 1, 2, 3)
};
var context = namespace.func(4, 5, 6);
st.equal(context, boundContext, 'returned context is bound context');
st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context');
st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct');
st.end();
});
t.test('passes the correct arguments when called as a constructor', function (st) {
var expected = { name: 'Correct' };
var namespace = {
Func: functionBind.call(function (arg) {
return arg;
}, { name: 'Incorrect' })
};
var returned = new namespace.Func(expected);
st.equal(returned, expected, 'returns the right arg when called as a constructor');
st.end();
});
t.test('has the new instance\'s context when called as a constructor', function (st) {
var actualContext;
var expectedContext = { foo: 'bar' };
var namespace = {
Func: functionBind.call(function () {
actualContext = this;
}, expectedContext)
};
var result = new namespace.Func();
st.equal(result instanceof namespace.Func, true);
st.notEqual(actualContext, expectedContext);
st.end();
});
t.end();
});
test('bound function length', function (t) {
t.test('sets a correct length without thisArg', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; });
st.equal(subject.length, 3);
st.equal(subject(1, 2, 3), 6);
st.end();
});
t.test('sets a correct length with thisArg', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {});
st.equal(subject.length, 3);
st.equal(subject(1, 2, 3), 6);
st.end();
});
t.test('sets a correct length without thisArg and first argument', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1);
st.equal(subject.length, 2);
st.equal(subject(2, 3), 6);
st.end();
});
t.test('sets a correct length with thisArg and first argument', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1);
st.equal(subject.length, 2);
st.equal(subject(2, 3), 6);
st.end();
});
t.test('sets a correct length without thisArg and too many arguments', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4);
st.equal(subject.length, 0);
st.equal(subject(), 6);
st.end();
});
t.test('sets a correct length with thisArg and too many arguments', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4);
st.equal(subject.length, 0);
st.equal(subject(), 6);
st.end();
});
});
{
"root": true,
"extends": "@ljharb",
"env": {
"es6": true,
"es2017": true,
"es2020": true,
"es2021": true,
},
"globals": {
"AggregateError": false,
},
"rules": {
"array-bracket-newline": 0,
"array-element-newline": 0,
"complexity": 0,
"eqeqeq": [2, "allow-null"],
"func-name-matching": 0,
"id-length": 0,
"max-lines-per-function": [2, 80],
"max-params": [2, 4],
"max-statements": 0,
"max-statements-per-line": [2, { "max": 2 }],
"multiline-comment-style": 0,
"no-magic-numbers": 0,
"operator-linebreak": [2, "before"],
"sort-keys": 0,
},
"overrides": [
{
"files": "test/**",
"rules": {
"max-lines-per-function": 0,
"new-cap": 0,
},
},
],
}
# These are supported funding model platforms
github: [ljharb]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: npm/get-intrinsic
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"lines": 86,
"statements": 85.93,
"functions": 82.43,
"branches": 76.06,
"exclude": [
"coverage",
"test"
]
}
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.1.1](https://github.com/ljharb/get-intrinsic/compare/v1.1.0...v1.1.1) - 2021-02-03
### Fixed
- [meta] export `./package.json` [`#9`](https://github.com/ljharb/get-intrinsic/issues/9)
### Commits
- [readme] flesh out the readme; use `evalmd` [`d12f12c`](https://github.com/ljharb/get-intrinsic/commit/d12f12c15345a0a0772cc65a7c64369529abd614)
- [eslint] set up proper globals config [`5a8c098`](https://github.com/ljharb/get-intrinsic/commit/5a8c0984e3319d1ac0e64b102f8ec18b64e79f36)
- [Dev Deps] update `eslint` [`7b9a5c0`](https://github.com/ljharb/get-intrinsic/commit/7b9a5c0d31a90ca1a1234181c74988fb046701cd)
## [v1.1.0](https://github.com/ljharb/get-intrinsic/compare/v1.0.2...v1.1.0) - 2021-01-25
### Fixed
- [Refactor] delay `Function` eval until syntax-derived values are requested [`#3`](https://github.com/ljharb/get-intrinsic/issues/3)
### Commits
- [Tests] migrate tests to Github Actions [`2ab762b`](https://github.com/ljharb/get-intrinsic/commit/2ab762b48164aea8af37a40ba105bbc8246ab8c4)
- [meta] do not publish github action workflow files [`5e7108e`](https://github.com/ljharb/get-intrinsic/commit/5e7108e4768b244d48d9567ba4f8a6cab9c65b8e)
- [Tests] add some coverage [`01ac7a8`](https://github.com/ljharb/get-intrinsic/commit/01ac7a87ac29738567e8524cd8c9e026b1fa8cb3)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `call-bind`, `es-abstract`, `tape`; add `call-bind` [`911b672`](https://github.com/ljharb/get-intrinsic/commit/911b672fbffae433a96924c6ce013585e425f4b7)
- [Refactor] rearrange evalled constructors a bit [`7e7e4bf`](https://github.com/ljharb/get-intrinsic/commit/7e7e4bf583f3799c8ac1c6c5e10d2cb553957347)
- [meta] add Automatic Rebase and Require Allow Edits workflows [`0199968`](https://github.com/ljharb/get-intrinsic/commit/01999687a263ffce0a3cb011dfbcb761754aedbc)
## [v1.0.2](https://github.com/ljharb/get-intrinsic/compare/v1.0.1...v1.0.2) - 2020-12-17
### Commits
- [Fix] Throw for non‑existent intrinsics [`68f873b`](https://github.com/ljharb/get-intrinsic/commit/68f873b013c732a05ad6f5fc54f697e55515461b)
- [Fix] Throw for non‑existent segments in the intrinsic path [`8325dee`](https://github.com/ljharb/get-intrinsic/commit/8325deee43128f3654d3399aa9591741ebe17b21)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-bigints`, `object-inspect` [`0c227a7`](https://github.com/ljharb/get-intrinsic/commit/0c227a7d8b629166f25715fd242553892e458525)
- [meta] do not lint coverage output [`70d2419`](https://github.com/ljharb/get-intrinsic/commit/70d24199b620043cd9110fc5f426d214ebe21dc9)
## [v1.0.1](https://github.com/ljharb/get-intrinsic/compare/v1.0.0...v1.0.1) - 2020-10-30
### Commits
- [Tests] gather coverage data on every job [`d1d280d`](https://github.com/ljharb/get-intrinsic/commit/d1d280dec714e3f0519cc877dbcb193057d9cac6)
- [Fix] add missing dependencies [`5031771`](https://github.com/ljharb/get-intrinsic/commit/5031771bb1095b38be88ce7c41d5de88718e432e)
- [Tests] use `es-value-fixtures` [`af48765`](https://github.com/ljharb/get-intrinsic/commit/af48765a23c5323fb0b6b38dbf00eb5099c7bebc)
## v1.0.0 - 2020-10-29
### Commits
- Implementation [`bbce57c`](https://github.com/ljharb/get-intrinsic/commit/bbce57c6f33d05b2d8d3efa273ceeb3ee01127bb)
- Tests [`17b4f0d`](https://github.com/ljharb/get-intrinsic/commit/17b4f0d56dea6b4059b56fc30ef3ee4d9500ebc2)
- Initial commit [`3153294`](https://github.com/ljharb/get-intrinsic/commit/31532948de363b0a27dd9fd4649e7b7028ec4b44)
- npm init [`fb326c4`](https://github.com/ljharb/get-intrinsic/commit/fb326c4d2817c8419ec31de1295f06bb268a7902)
- [meta] add Automatic Rebase and Require Allow Edits workflows [`48862fb`](https://github.com/ljharb/get-intrinsic/commit/48862fb2508c8f6a57968e6d08b7c883afc9d550)
- [meta] add `auto-changelog` [`5f28ad0`](https://github.com/ljharb/get-intrinsic/commit/5f28ad019e060a353d8028f9f2591a9cc93074a1)
- [meta] add "funding"; create `FUNDING.yml` [`c2bbdde`](https://github.com/ljharb/get-intrinsic/commit/c2bbddeba73a875be61484ee4680b129a6d4e0a1)
- [Tests] add `npm run lint` [`0a84b98`](https://github.com/ljharb/get-intrinsic/commit/0a84b98b22b7cf7a748666f705b0003a493c35fd)
- Only apps should have lockfiles [`9586c75`](https://github.com/ljharb/get-intrinsic/commit/9586c75866c1ee678e4d5d4dbbdef6997e511b05)
MIT License
Copyright (c) 2020 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# get-intrinsic <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
Get and robustly cache all JS language-level intrinsics at first require time.
See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference.
## Example
```js
var GetIntrinsic = require('get-intrinsic');
var assert = require('assert');
// static methods
assert.equal(GetIntrinsic('%Math.pow%'), Math.pow);
assert.equal(Math.pow(2, 3), 8);
assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8);
delete Math.pow;
assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8);
// instance methods
var arr = [1];
assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push);
assert.deepEqual(arr, [1]);
arr.push(2);
assert.deepEqual(arr, [1, 2]);
GetIntrinsic('%Array.prototype.push%').call(arr, 3);
assert.deepEqual(arr, [1, 2, 3]);
delete Array.prototype.push;
GetIntrinsic('%Array.prototype.push%').call(arr, 4);
assert.deepEqual(arr, [1, 2, 3, 4]);
// missing features
delete JSON.parse; // to simulate a real intrinsic that is missing in the environment
assert.throws(() => GetIntrinsic('%JSON.parse%'));
assert.equal(undefined, GetIntrinsic('%JSON.parse%', true));
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
## Security
Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report.
[package-url]: https://npmjs.org/package/get-intrinsic
[npm-version-svg]: http://versionbadg.es/ljharb/get-intrinsic.svg
[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg
[deps-url]: https://david-dm.org/ljharb/get-intrinsic
[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg
[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg
[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic
'use strict';
var undefined;
var $SyntaxError = SyntaxError;
var $Function = Function;
var $TypeError = TypeError;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = require('has-symbols')();
var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
var INTRINSICS = {
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': RangeError,
'%ReferenceError%': ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = require('function-bind');
var hasOwn = require('has');
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
{
"name": "get-intrinsic",
"version": "1.1.1",
"description": "Get and robustly cache all JS language-level intrinsics at first require time",
"main": "index.js",
"exports": {
".": [
{
"default": "./index.js"
},
"./index.js"
],
"./package.json": "./package.json"
},
"scripts": {
"prelint": "evalmd README.md",
"lint": "eslint --ext=.js,.mjs .",
"pretest": "npm run lint",
"tests-only": "nyc tape 'test/**/*.js'",
"test": "npm run tests-only",
"posttest": "aud --production",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/ljharb/get-intrinsic.git"
},
"keywords": [
"javascript",
"ecmascript",
"es",
"js",
"intrinsic",
"getintrinsic",
"es-abstract"
],
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/ljharb/get-intrinsic/issues"
},
"homepage": "https://github.com/ljharb/get-intrinsic#readme",
"devDependencies": {
"@ljharb/eslint-config": "^17.5.0",
"aud": "^1.1.3",
"auto-changelog": "^2.2.1",
"call-bind": "^1.0.2",
"es-abstract": "^1.18.0-next.2",
"es-value-fixtures": "^1.0.0",
"eslint": "^7.19.0",
"evalmd": "^0.0.19",
"foreach": "^2.0.5",
"has-bigints": "^1.0.1",
"make-async-function": "^1.0.0",
"make-async-generator-function": "^1.0.0",
"make-generator-function": "^2.0.0",
"nyc": "^10.3.2",
"object-inspect": "^1.9.0",
"tape": "^5.1.1"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"dependencies": {
"function-bind": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.1"
}
}
'use strict';
var GetIntrinsic = require('../');
var test = require('tape');
var forEach = require('foreach');
var debug = require('object-inspect');
var generatorFns = require('make-generator-function')();
var asyncFns = require('make-async-function').list();
var asyncGenFns = require('make-async-generator-function')();
var callBound = require('call-bind/callBound');
var v = require('es-value-fixtures');
var $gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor');
var defineProperty = require('es-abstract/test/helpers/defineProperty');
var $isProto = callBound('%Object.prototype.isPrototypeOf%');
test('export', function (t) {
t.equal(typeof GetIntrinsic, 'function', 'it is a function');
t.equal(GetIntrinsic.length, 2, 'function has length of 2');
t.end();
});
test('throws', function (t) {
t['throws'](
function () { GetIntrinsic('not an intrinsic'); },
SyntaxError,
'nonexistent intrinsic throws a syntax error'
);
t['throws'](
function () { GetIntrinsic(''); },
TypeError,
'empty string intrinsic throws a type error'
);
t['throws'](
function () { GetIntrinsic('.'); },
SyntaxError,
'"just a dot" intrinsic throws a syntax error'
);
t['throws'](
function () { GetIntrinsic('%String'); },
SyntaxError,
'Leading % without trailing % throws a syntax error'
);
t['throws'](
function () { GetIntrinsic('String%'); },
SyntaxError,
'Trailing % without leading % throws a syntax error'
);
t['throws'](
function () { GetIntrinsic("String['prototype]"); },
SyntaxError,
'Dynamic property access is disallowed for intrinsics (unterminated string)'
);
t['throws'](
function () { GetIntrinsic('%Proxy.prototype.undefined%'); },
TypeError,
"Throws when middle part doesn't exist (%Proxy.prototype.undefined%)"
);
forEach(v.nonStrings, function (nonString) {
t['throws'](
function () { GetIntrinsic(nonString); },
TypeError,
debug(nonString) + ' is not a String'
);
});
forEach(v.nonBooleans, function (nonBoolean) {
t['throws'](
function () { GetIntrinsic('%', nonBoolean); },
TypeError,
debug(nonBoolean) + ' is not a Boolean'
);
});
forEach([
'toString',
'propertyIsEnumerable',
'hasOwnProperty'
], function (objectProtoMember) {
t['throws'](
function () { GetIntrinsic(objectProtoMember); },
SyntaxError,
debug(objectProtoMember) + ' is not an intrinsic'
);
});
t.end();
});
test('base intrinsics', function (t) {
t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object');
t.equal(GetIntrinsic('Object'), Object, 'Object yields Object');
t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array');
t.equal(GetIntrinsic('Array'), Array, 'Array yields Array');
t.end();
});
test('dotted paths', function (t) {
t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString');
t.equal(GetIntrinsic('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString yields Object.prototype.toString');
t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push');
t.equal(GetIntrinsic('Array.prototype.push'), Array.prototype.push, 'Array.prototype.push yields Array.prototype.push');
test('underscore paths are aliases for dotted paths', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) {
var original = GetIntrinsic('%ObjProto_toString%');
forEach([
'%Object.prototype.toString%',
'Object.prototype.toString',
'%ObjectPrototype.toString%',
'ObjectPrototype.toString',
'%ObjProto_toString%',
'ObjProto_toString'
], function (name) {
defineProperty(Object.prototype, 'toString', {
value: function toString() {
return original.apply(this, arguments);
}
});
st.equal(GetIntrinsic(name), original, name + ' yields original Object.prototype.toString');
});
defineProperty(Object.prototype, 'toString', { value: original });
st.end();
});
test('dotted paths cache', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) {
var original = GetIntrinsic('%Object.prototype.propertyIsEnumerable%');
forEach([
'%Object.prototype.propertyIsEnumerable%',
'Object.prototype.propertyIsEnumerable',
'%ObjectPrototype.propertyIsEnumerable%',
'ObjectPrototype.propertyIsEnumerable'
], function (name) {
// eslint-disable-next-line no-extend-native
Object.prototype.propertyIsEnumerable = function propertyIsEnumerable() {
return original.apply(this, arguments);
};
st.equal(GetIntrinsic(name), original, name + ' yields cached Object.prototype.propertyIsEnumerable');
});
// eslint-disable-next-line no-extend-native
Object.prototype.propertyIsEnumerable = original;
st.end();
});
test('dotted path reports correct error', function (st) {
st['throws'](function () {
GetIntrinsic('%NonExistentIntrinsic.prototype.property%');
}, /%NonExistentIntrinsic%/, 'The base intrinsic of %NonExistentIntrinsic.prototype.property% is %NonExistentIntrinsic%');
st['throws'](function () {
GetIntrinsic('%NonExistentIntrinsicPrototype.property%');
}, /%NonExistentIntrinsicPrototype%/, 'The base intrinsic of %NonExistentIntrinsicPrototype.property% is %NonExistentIntrinsicPrototype%');
st.end();
});
t.end();
});
test('accessors', { skip: !$gOPD || typeof Map !== 'function' }, function (t) {
var actual = $gOPD(Map.prototype, 'size');
t.ok(actual, 'Map.prototype.size has a descriptor');
t.equal(typeof actual.get, 'function', 'Map.prototype.size has a getter function');
t.equal(GetIntrinsic('%Map.prototype.size%'), actual.get, '%Map.prototype.size% yields the getter for it');
t.equal(GetIntrinsic('Map.prototype.size'), actual.get, 'Map.prototype.size yields the getter for it');
t.end();
});
test('generator functions', { skip: !generatorFns.length }, function (t) {
var $GeneratorFunction = GetIntrinsic('%GeneratorFunction%');
var $GeneratorFunctionPrototype = GetIntrinsic('%Generator%');
var $GeneratorPrototype = GetIntrinsic('%GeneratorPrototype%');
forEach(generatorFns, function (genFn) {
var fnName = genFn.name;
fnName = fnName ? "'" + fnName + "'" : 'genFn';
t.ok(genFn instanceof $GeneratorFunction, fnName + ' instanceof %GeneratorFunction%');
t.ok($isProto($GeneratorFunctionPrototype, genFn), '%Generator% is prototype of ' + fnName);
t.ok($isProto($GeneratorPrototype, genFn.prototype), '%GeneratorPrototype% is prototype of ' + fnName + '.prototype');
});
t.end();
});
test('async functions', { skip: !asyncFns.length }, function (t) {
var $AsyncFunction = GetIntrinsic('%AsyncFunction%');
var $AsyncFunctionPrototype = GetIntrinsic('%AsyncFunctionPrototype%');
forEach(asyncFns, function (asyncFn) {
var fnName = asyncFn.name;
fnName = fnName ? "'" + fnName + "'" : 'asyncFn';
t.ok(asyncFn instanceof $AsyncFunction, fnName + ' instanceof %AsyncFunction%');
t.ok($isProto($AsyncFunctionPrototype, asyncFn), '%AsyncFunctionPrototype% is prototype of ' + fnName);
});
t.end();
});
test('async generator functions', { skip: asyncGenFns.length === 0 }, function (t) {
var $AsyncGeneratorFunction = GetIntrinsic('%AsyncGeneratorFunction%');
var $AsyncGeneratorFunctionPrototype = GetIntrinsic('%AsyncGenerator%');
var $AsyncGeneratorPrototype = GetIntrinsic('%AsyncGeneratorPrototype%');
forEach(asyncGenFns, function (asyncGenFn) {
var fnName = asyncGenFn.name;
fnName = fnName ? "'" + fnName + "'" : 'asyncGenFn';
t.ok(asyncGenFn instanceof $AsyncGeneratorFunction, fnName + ' instanceof %AsyncGeneratorFunction%');
t.ok($isProto($AsyncGeneratorFunctionPrototype, asyncGenFn), '%AsyncGenerator% is prototype of ' + fnName);
t.ok($isProto($AsyncGeneratorPrototype, asyncGenFn.prototype), '%AsyncGeneratorPrototype% is prototype of ' + fnName + '.prototype');
});
t.end();
});
test('%ThrowTypeError%', function (t) {
var $ThrowTypeError = GetIntrinsic('%ThrowTypeError%');
t.equal(typeof $ThrowTypeError, 'function', 'is a function');
t['throws'](
$ThrowTypeError,
TypeError,
'%ThrowTypeError% throws a TypeError'
);
t.end();
});
test('allowMissing', { skip: asyncGenFns.length > 0 }, function (t) {
t['throws'](
function () { GetIntrinsic('%AsyncGeneratorPrototype%'); },
TypeError,
'throws when missing'
);
t.equal(
GetIntrinsic('%AsyncGeneratorPrototype%', true),
undefined,
'does not throw when allowMissing'
);
t.end();
});
{
"root": true,
"extends": "@ljharb",
"rules": {
"max-statements-per-line": [2, { "max": 2 }],
"no-magic-numbers": 0,
"multiline-comment-style": 0,
}
}
# These are supported funding model platforms
github: [ljharb]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: npm/has-symbols
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"lines": 86,
"statements": 85.93,
"functions": 82.43,
"branches": 76.06,
"exclude": [
"coverage",
"test"
]
}
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.0.2](https://github.com/inspect-js/has-symbols/compare/v1.0.1...v1.0.2) - 2021-02-27
### Fixed
- [Fix] use a universal way to get the original Symbol [`#11`](https://github.com/inspect-js/has-symbols/issues/11)
### Commits
- [Tests] migrate tests to Github Actions [`90ae798`](https://github.com/inspect-js/has-symbols/commit/90ae79820bdfe7bc703d67f5f3c5e205f98556d3)
- [meta] do not publish github action workflow files [`29e60a1`](https://github.com/inspect-js/has-symbols/commit/29e60a1b7c25c7f1acf7acff4a9320d0d10c49b4)
- [Tests] run `nyc` on all tests [`8476b91`](https://github.com/inspect-js/has-symbols/commit/8476b915650d360915abe2522505abf4b0e8f0ae)
- [readme] fix repo URLs, remove defunct badges [`126288e`](https://github.com/inspect-js/has-symbols/commit/126288ecc1797c0a40247a6b78bcb2e0bc5d7036)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `core-js`, `get-own-property-symbols` [`d84bdfa`](https://github.com/inspect-js/has-symbols/commit/d84bdfa48ac5188abbb4904b42614cd6c030940a)
- [Tests] fix linting errors [`0df3070`](https://github.com/inspect-js/has-symbols/commit/0df3070b981b6c9f2ee530c09189a7f5c6def839)
- [actions] add "Allow Edits" workflow [`1e6bc29`](https://github.com/inspect-js/has-symbols/commit/1e6bc29b188f32b9648657b07eda08504be5aa9c)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`36cea2a`](https://github.com/inspect-js/has-symbols/commit/36cea2addd4e6ec435f35a2656b4e9ef82498e9b)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1278338`](https://github.com/inspect-js/has-symbols/commit/127833801865fbc2cc8979beb9ca869c7bfe8222)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1493254`](https://github.com/inspect-js/has-symbols/commit/1493254eda13db5fb8fc5e4a3e8324b3d196029d)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js` [`b090bf2`](https://github.com/inspect-js/has-symbols/commit/b090bf214d3679a30edc1e2d729d466ab5183e1d)
- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`4addb7a`](https://github.com/inspect-js/has-symbols/commit/4addb7ab4dc73f927ae99928d68817554fc21dc0)
- [Dev Deps] update `auto-changelog`, `tape` [`81d0baf`](https://github.com/inspect-js/has-symbols/commit/81d0baf3816096a89a8558e8043895f7a7d10d8b)
- [Dev Deps] update `auto-changelog`; add `aud` [`1a4e561`](https://github.com/inspect-js/has-symbols/commit/1a4e5612c25d91c3a03d509721d02630bc4fe3da)
- [readme] remove unused testling URLs [`3000941`](https://github.com/inspect-js/has-symbols/commit/3000941f958046e923ed8152edb1ef4a599e6fcc)
- [Tests] only audit prod deps [`692e974`](https://github.com/inspect-js/has-symbols/commit/692e9743c912410e9440207631a643a34b4741a1)
- [Dev Deps] update `@ljharb/eslint-config` [`51c946c`](https://github.com/inspect-js/has-symbols/commit/51c946c7f6baa793ec5390bb5a45cdce16b4ba76)
## [v1.0.1](https://github.com/inspect-js/has-symbols/compare/v1.0.0...v1.0.1) - 2019-11-16
### Commits
- [Tests] use shared travis-ci configs [`ce396c9`](https://github.com/inspect-js/has-symbols/commit/ce396c9419ff11c43d0da5d05cdbb79f7fb42229)
- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v4.9`; use `nvm install-latest-npm` [`0690732`](https://github.com/inspect-js/has-symbols/commit/0690732801f47ab429f39ba1962f522d5c462d6b)
- [meta] add `auto-changelog` [`2163d0b`](https://github.com/inspect-js/has-symbols/commit/2163d0b7f36343076b8f947cd1667dd1750f26fc)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`8e0951f`](https://github.com/inspect-js/has-symbols/commit/8e0951f1a7a2e52068222b7bb73511761e6e4d9c)
- [actions] add automatic rebasing / merge commit blocking [`b09cdb7`](https://github.com/inspect-js/has-symbols/commit/b09cdb7cd7ee39e7a769878f56e2d6066f5ccd1d)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `core-js`, `get-own-property-symbols`, `tape` [`1dd42cd`](https://github.com/inspect-js/has-symbols/commit/1dd42cd86183ed0c50f99b1062345c458babca91)
- [meta] create FUNDING.yml [`aa57a17`](https://github.com/inspect-js/has-symbols/commit/aa57a17b19708906d1927f821ea8e73394d84ca4)
- Only apps should have lockfiles [`a2d8bea`](https://github.com/inspect-js/has-symbols/commit/a2d8bea23a97d15c09eaf60f5b107fcf9a4d57aa)
- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`9e96cb7`](https://github.com/inspect-js/has-symbols/commit/9e96cb783746cbed0c10ef78e599a8eaa7ebe193)
- [meta] add `funding` field [`a0b32cf`](https://github.com/inspect-js/has-symbols/commit/a0b32cf68e803f963c1639b6d47b0a9d6440bab0)
- [Dev Deps] update `safe-publish-latest` [`cb9f0a5`](https://github.com/inspect-js/has-symbols/commit/cb9f0a521a3a1790f1064d437edd33bb6c3d6af0)
## v1.0.0 - 2016-09-19
### Commits
- Tests. [`ecb6eb9`](https://github.com/inspect-js/has-symbols/commit/ecb6eb934e4883137f3f93b965ba5e0a98df430d)
- package.json [`88a337c`](https://github.com/inspect-js/has-symbols/commit/88a337cee0864a0da35f5d19e69ff0ef0150e46a)
- Initial commit [`42e1e55`](https://github.com/inspect-js/has-symbols/commit/42e1e5502536a2b8ac529c9443984acd14836b1c)
- Initial implementation. [`33f5cc6`](https://github.com/inspect-js/has-symbols/commit/33f5cc6cdff86e2194b081ee842bfdc63caf43fb)
- read me [`01f1170`](https://github.com/inspect-js/has-symbols/commit/01f1170188ff7cb1558aa297f6ba5b516c6d7b0c)
MIT License
Copyright (c) 2016 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# has-symbols <sup>[![Version Badge][2]][1]</sup>
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][11]][1]
Determine if the JS environment has Symbol support. Supports spec, or shams.
## Example
```js
var hasSymbols = require('has-symbols');
hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable.
var hasSymbolsKinda = require('has-symbols/shams');
hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec.
```
## Supported Symbol shams
- get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols)
- core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js)
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[1]: https://npmjs.org/package/has-symbols
[2]: https://versionbadg.es/inspect-js/has-symbols.svg
[5]: https://david-dm.org/inspect-js/has-symbols.svg
[6]: https://david-dm.org/inspect-js/has-symbols
[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg
[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies
[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/has-symbols.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg
[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols
'use strict';
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = require('./shams');
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
{
"name": "has-symbols",
"version": "1.0.2",
"author": {
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"contributors": [
{
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
}
],
"description": "Determine if the JS environment has Symbol support. Supports spec, or shams.",
"license": "MIT",
"main": "index.js",
"scripts": {
"prepublish": "safe-publish-latest",
"pretest": "npm run --silent lint",
"test": "npm run tests-only",
"posttest": "aud --production",
"tests-only": "npm run test:stock && npm run test:staging && npm run test:shams",
"test:stock": "nyc node test",
"test:staging": "nyc node --harmony --es-staging test",
"test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs",
"test:shams:corejs": "nyc node test/shams/core-js.js",
"test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js",
"lint": "eslint --ext=js,mjs .",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git://github.com/inspect-js/has-symbols.git"
},
"keywords": [
"Symbol",
"symbols",
"typeof",
"sham",
"polyfill",
"native",
"core-js",
"ES6"
],
"devDependencies": {
"@ljharb/eslint-config": "^17.5.1",
"aud": "^1.1.4",
"auto-changelog": "^2.2.1",
"core-js": "^2.6.12",
"eslint": "^7.20.0",
"get-own-property-symbols": "^0.9.5",
"nyc": "^10.3.2",
"safe-publish-latest": "^1.1.4",
"tape": "^5.2.0"
},
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"greenkeeper": {
"ignore": [
"core-js"
]
}
}
'use strict';
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
'use strict';
var test = require('tape');
var hasSymbols = require('../');
var runSymbolTests = require('./tests');
test('interface', function (t) {
t.equal(typeof hasSymbols, 'function', 'is a function');
t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean');
t.end();
});
test('Symbols are supported', { skip: !hasSymbols() }, function (t) {
runSymbolTests(t);
t.end();
});
test('Symbols are not supported', { skip: hasSymbols() }, function (t) {
t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined');
t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist');
t.end();
});
'use strict';
var test = require('tape');
if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') {
test('has native Symbol support', function (t) {
t.equal(typeof Symbol, 'function');
t.equal(typeof Symbol(), 'symbol');
t.end();
});
return;
}
var hasSymbols = require('../../shams');
test('polyfilled Symbols', function (t) {
/* eslint-disable global-require */
t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling');
require('core-js/fn/symbol');
require('core-js/fn/symbol/to-string-tag');
require('../tests')(t);
var hasSymbolsAfter = hasSymbols();
t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling');
/* eslint-enable global-require */
t.end();
});
'use strict';
var test = require('tape');
if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') {
test('has native Symbol support', function (t) {
t.equal(typeof Symbol, 'function');
t.equal(typeof Symbol(), 'symbol');
t.end();
});
return;
}
var hasSymbols = require('../../shams');
test('polyfilled Symbols', function (t) {
/* eslint-disable global-require */
t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling');
require('get-own-property-symbols');
require('../tests')(t);
var hasSymbolsAfter = hasSymbols();
t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling');
/* eslint-enable global-require */
t.end();
});
'use strict';
// eslint-disable-next-line consistent-return
module.exports = function runSymbolTests(t) {
t.equal(typeof Symbol, 'function', 'global Symbol is a function');
if (typeof Symbol !== 'function') { return false; }
t.notEqual(Symbol(), Symbol(), 'two symbols are not equal');
/*
t.equal(
Symbol.prototype.toString.call(Symbol('foo')),
Symbol.prototype.toString.call(Symbol('foo')),
'two symbols with the same description stringify the same'
);
*/
/*
var foo = Symbol('foo');
t.notEqual(
String(foo),
String(Symbol('bar')),
'two symbols with different descriptions do not stringify the same'
);
*/
t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function');
// t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol');
t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function');
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
t.notEqual(typeof sym, 'string', 'Symbol is not a string');
t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly');
t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly');
var symVal = 42;
obj[sym] = symVal;
// eslint-disable-next-line no-restricted-syntax
for (sym in obj) { t.fail('symbol property key was found in for..in of object'); }
t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object');
t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object');
t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object');
t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable');
t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), {
configurable: true,
enumerable: true,
value: 42,
writable: true
}, 'property descriptor is correct');
};
Copyright (c) 2013 Thiago de Arruda
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
# has
> Object.prototype.hasOwnProperty.call shortcut
## Installation
```sh
npm install --save has
```
## Usage
```js
var has = require('has');
has({}, 'hasOwnProperty'); // false
has(Object.prototype, 'hasOwnProperty'); // true
```
{
"name": "has",
"description": "Object.prototype.hasOwnProperty.call shortcut",
"version": "1.0.3",
"homepage": "https://github.com/tarruda/has",
"author": {
"name": "Thiago de Arruda",
"email": "tpadilha84@gmail.com"
},
"contributors": [
{
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
}
],
"repository": {
"type": "git",
"url": "git://github.com/tarruda/has.git"
},
"bugs": {
"url": "https://github.com/tarruda/has/issues"
},
"license": "MIT",
"licenses": [
{
"type": "MIT",
"url": "https://github.com/tarruda/has/blob/master/LICENSE-MIT"
}
],
"main": "./src",
"dependencies": {
"function-bind": "^1.1.1"
},
"devDependencies": {
"@ljharb/eslint-config": "^12.2.1",
"eslint": "^4.19.1",
"tape": "^4.9.0"
},
"engines": {
"node": ">= 0.4.0"
},
"scripts": {
"lint": "eslint .",
"pretest": "npm run lint",
"test": "tape test"
}
}
'use strict';
var bind = require('function-bind');
module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
'use strict';
var test = require('tape');
var has = require('../');
test('has', function (t) {
t.equal(has({}, 'hasOwnProperty'), false, 'object literal does not have own property "hasOwnProperty"');
t.equal(has(Object.prototype, 'hasOwnProperty'), true, 'Object.prototype has own property "hasOwnProperty"');
t.end();
});
{
"root": true,
"extends": "@ljharb",
}
# These are supported funding model platforms
github: [ljharb]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: npm/is-nan
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"lines": 86,
"statements": 85.93,
"functions": 82.43,
"branches": 76.06,
"exclude": [
"coverage",
"test"
]
}
1.3.2 / 2020-12-23
=================
* [meta] do not publish github action workflow files
1.3.1 / 2020-12-23
=================
* [Fix] avoid mutating `Number.isNaN` when present
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es5-shim`, `tape`, `functions-have-names`; add `safe-publish-latest`
* [readme] fix repo URLs, remove defunct badges
* [Tests] migrate tests to Github Actions
* [Tests] add `implementation` est; run `es-shim-api` in postlint; use `tape` runner
* [actions] add "Allow Edits" workflow
* [actions] switch Automatic Rebase workflow to `pull_request_target` event
1.3.0 / 2019-12-15
=================
* [New] add "auto" entry point
* [readme] fix repo URLs
* [docs] clean up README links/formatting
* [Deps] update `define-properties`
* [meta] add `funding` field; FUNDING.yml
* [meta] Only apps should have lockfiles
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `es5-shim`, `tape`, `@es-shims/api`
* [Tests] use shared travis-ci configs
* [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops
* [Tests] use `functions-have-names`
* [Tests] remove `jscs`
* [actions] add automatic rebasing / merge commit blocking
1.2.1 / 2015-08-16
=================
* [Docs] Update readme
1.2.0 / 2015-08-16
=================
* [New] Implement the [es-shim API](es-shims/api) interface
* [Dev Deps] update `eslint`, `tape`, `es5-shim`, `@ljharb/eslint-config`
* [Tests] up to `io.js` `v3.0`
* [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG
* [Security] Add `npm run security`
1.1.0 / 2015-06-24
=================
* Add a "shim" method
* Add `npm run eslint`
* Test latest `node` and `io.js` on `travis-ci`
* Add license and download badges to README
* Update `tape`, `covert`, `jscs`
1.0.1 / 2014-07-05
=================
* Oops, jscs should be a devDependency
1.0.0 / 2014-07-05
=================
* Initial release.
The MIT License (MIT)
Copyright (c) 2014 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# is-nan <sup>[![Version Badge][2]][1]</sup>
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][11]][1]
ES2015-compliant shim for Number.isNaN - the global isNaN returns false positives.
This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan).
## Example
```js
Number.isNaN = require('is-nan');
var assert = require('assert');
assert.notOk(Number.isNaN(undefined));
assert.notOk(Number.isNaN(null));
assert.notOk(Number.isNaN(false));
assert.notOk(Number.isNaN(true));
assert.notOk(Number.isNaN(0));
assert.notOk(Number.isNaN(42));
assert.notOk(Number.isNaN(Infinity));
assert.notOk(Number.isNaN(-Infinity));
assert.notOk(Number.isNaN('foo'));
assert.notOk(Number.isNaN(function () {}));
assert.notOk(Number.isNaN([]));
assert.notOk(Number.isNaN({}));
assert.ok(Number.isNaN(NaN));
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[1]: https://npmjs.org/package/is-nan
[2]: https://versionbadg.es/es-shims/is-nan.svg
[5]: https://david-dm.org/es-shims/is-nan.svg
[6]: https://david-dm.org/es-shims/is-nan
[7]: https://david-dm.org/es-shims/is-nan/dev-status.svg
[8]: https://david-dm.org/es-shims/is-nan#info=devDependencies
[11]: https://nodei.co/npm/is-nan.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/is-nan.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/is-nan.svg
[downloads-url]: https://npm-stat.com/charts.html?package=is-nan
'use strict';
require('./shim')();
'use strict';
/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */
module.exports = function isNaN(value) {
return value !== value;
};
'use strict';
var callBind = require('call-bind');
var define = require('define-properties');
var implementation = require('./implementation');
var getPolyfill = require('./polyfill');
var shim = require('./shim');
var polyfill = callBind(getPolyfill(), Number);
/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */
define(polyfill, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = polyfill;
{
"name": "is-nan",
"version": "1.3.2",
"description": "ES2015-compliant shim for Number.isNaN - the global isNaN returns false positives.",
"author": "Jordan Harband",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"main": "index.js",
"scripts": {
"prepublish": "safe-publish-latest",
"pretest": "npm run lint",
"test": "npm run tests-only",
"tests-only": "nyc tape 'test/**/*.js'",
"posttest": "npx aud --production",
"lint": "eslint .",
"postlint": "es-shim-api --bound"
},
"repository": {
"type": "git",
"url": "git://github.com/es-shims/is-nan.git"
},
"bugs": {
"url": "https://github.com/es-shims/is-nan/issues"
},
"homepage": "https://github.com/es-shims/is-nan",
"keywords": [
"is",
"NaN",
"not a number",
"number",
"isNaN",
"ES6",
"ES2015",
"shim",
"polyfill",
"es-shim API"
],
"dependencies": {
"call-bind": "^1.0.0",
"define-properties": "^1.1.3"
},
"devDependencies": {
"@es-shims/api": "^2.1.2",
"@ljharb/eslint-config": "^17.3.0",
"aud": "^1.1.3",
"es5-shim": "^4.5.14",
"eslint": "^7.16.0",
"functions-have-names": "^1.2.2",
"nyc": "^10.3.2",
"safe-publish-latest": "^1.1.4",
"tape": "^5.0.1"
},
"testling": {
"files": "test.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..12.0",
"opera/15.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
}
}
'use strict';
var implementation = require('./implementation');
module.exports = function getPolyfill() {
if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) {
return Number.isNaN;
}
return implementation;
};
'use strict';
var define = require('define-properties');
var getPolyfill = require('./polyfill');
/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */
module.exports = function shimNumberIsNaN() {
var polyfill = getPolyfill();
define(Number, { isNaN: polyfill }, {
isNaN: function testIsNaN() {
return Number.isNaN !== polyfill;
}
});
return polyfill;
};
'use strict';
var numberIsNaN = require('../');
var test = require('tape');
var runTests = require('./tests');
test('as a function', function (t) {
runTests(numberIsNaN, t);
t.end();
});
'use strict';
require('es5-shim');
var numberIsNaN = require('../');
numberIsNaN.shim();
var test = require('tape');
var defineProperties = require('define-properties');
var isEnumerable = Object.prototype.propertyIsEnumerable;
var functionsHaveNames = require('functions-have-names')();
var runTests = require('./tests');
test('shimmed', function (t) {
t.equal(Number.isNaN.length, 1, 'Number.isNaN has a length of 1');
t.test('Function name', { skip: !functionsHaveNames }, function (st) {
st.equal(Number.isNaN.name, 'isNaN', 'Number.isNaN has name "isNaN"');
st.end();
});
t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) {
et.equal(false, isEnumerable.call(Number, 'isNaN'), 'Number.isNaN is not enumerable');
et.end();
});
runTests(Number.isNaN, t);
t.end();
});
'use strict';
module.exports = function (numberIsNaN, t) {
t.test('not NaN', function (st) {
st.test('primitives', function (sst) {
sst.notOk(numberIsNaN(), 'undefined is not NaN');
sst.notOk(numberIsNaN(null), 'null is not NaN');
sst.notOk(numberIsNaN(false), 'false is not NaN');
sst.notOk(numberIsNaN(true), 'true is not NaN');
sst.notOk(numberIsNaN(0), 'positive zero is not NaN');
sst.notOk(numberIsNaN(Infinity), 'Infinity is not NaN');
sst.notOk(numberIsNaN(-Infinity), '-Infinity is not NaN');
sst.notOk(numberIsNaN('foo'), 'string is not NaN');
sst.notOk(numberIsNaN('NaN'), 'string NaN is not NaN');
sst.end();
});
st.notOk(numberIsNaN([]), 'array is not NaN');
st.notOk(numberIsNaN({}), 'object is not NaN');
st.notOk(numberIsNaN(function () {}), 'function is not NaN');
st.test('valueOf', function (vt) {
var obj = {
valueOf: function () {
return NaN;
}
};
vt.ok(numberIsNaN(Number(obj)), 'object with valueOf of NaN, converted to Number, is NaN');
vt.notOk(numberIsNaN(obj), 'object with valueOf of NaN is not NaN');
vt.end();
});
st.end();
});
t.test('NaN literal', function (st) {
st.ok(numberIsNaN(NaN), 'NaN is NaN');
st.end();
});
};
# Long timeouts
Long timeout makes it possible to have a timeout or interval that is longer than 24.8 days (2^31-1 milliseconds).
## Usage
```js
var lt = require('long-timeout')
var timeout = lt.setTimeout(function() {
console.log('in 30 days')
}, 1000 * 60 * 60 * 24 * 30)
var interval = lt.setInterval(function() {
console.log('every 30 days')
}, 1000 * 60 * 60 * 24 * 30)
// Clear them
lt.clearTimeout(timeout)
lt.clearInterval(interval)
```
## Install
npm install long-timeout
## Licence
MIT
var lt = require('./')
/*
Timeouts
*/
lt.setTimeout(function() {
console.log('in a long time')
}, Number.MAX_VALUE)
lt.setTimeout(function() {
console.log('2 seconds')
}, 2000)
/*
Intervals
*/
lt.setInterval(function() {
console.log('long interval')
}, Number.MAX_VALUE)
lt.setInterval(function() {
console.log("2 second interval")
}, 2000)
var TIMEOUT_MAX = 2147483647; // 2^31-1
exports.setTimeout = function(listener, after) {
return new Timeout(listener, after)
}
exports.setInterval = function(listener, after) {
return new Interval(listener, after)
}
exports.clearTimeout = function(timer) {
if (timer) timer.close()
}
exports.clearInterval = exports.clearTimeout
exports.Timeout = Timeout
exports.Interval = Interval
function Timeout(listener, after) {
this.listener = listener
this.after = after
this.unreffed = false
this.start()
}
Timeout.prototype.unref = function() {
if (!this.unreffed) {
this.unreffed = true
this.timeout.unref()
}
}
Timeout.prototype.ref = function() {
if (this.unreffed) {
this.unreffed = false
this.timeout.ref()
}
}
Timeout.prototype.start = function() {
if (this.after <= TIMEOUT_MAX) {
this.timeout = setTimeout(this.listener, this.after)
} else {
var self = this
this.timeout = setTimeout(function() {
self.after -= TIMEOUT_MAX
self.start()
}, TIMEOUT_MAX)
}
if (this.unreffed) {
this.timeout.unref()
}
}
Timeout.prototype.close = function() {
clearTimeout(this.timeout)
}
function Interval(listener, after) {
this.listener = listener
this.after = this.timeLeft = after
this.unreffed = false
this.start()
}
Interval.prototype.unref = function() {
if (!this.unreffed) {
this.unreffed = true
this.timeout.unref()
}
}
Interval.prototype.ref = function() {
if (this.unreffed) {
this.unreffed = false
this.timeout.ref()
}
}
Interval.prototype.start = function() {
var self = this
if (this.timeLeft <= TIMEOUT_MAX) {
this.timeout = setTimeout(function() {
self.listener()
self.timeLeft = self.after
self.start()
}, this.timeLeft)
} else {
this.timeout = setTimeout(function() {
self.timeLeft -= TIMEOUT_MAX
self.start()
}, TIMEOUT_MAX)
}
if (this.unreffed) {
this.timeout.unref()
}
}
Interval.prototype.close = function() {
Timeout.prototype.close.apply(this, arguments)
}
{
"name": "long-timeout",
"version": "0.1.1",
"description": "Long timeout makes it possible to have a timeout or interval that is longer than 24.8 days (2^31-1 milliseconds).",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git://github.com/tellnes/long-timeout.git"
},
"author": "Christian Tellnes <christian@tellnes.no> (http://christian.tellnes.com/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/tellnes/long-timeout/issues"
},
"homepage": "https://github.com/tellnes/long-timeout",
"publishConfig": {
"registry": "https://registry.npmjs.org/"
}
}
# Changelog
# 1.27.0 (2021-05-08)
* Fix GMT zone parsing for older versions of Node
* Support multiple units in `toRelative`
* Various documentation updates
## 1.26.0 (2021-02-13)
* Add fromISOTime, toISOTime and toMillis to Duration (#803)
* Fix padding of negative years in IsoDate (#871)
* Fix hasSame unit comparison (#798)
* Export VERSION information (#794)
* Durations are considered equal with extra zero units. Fixes #809 (#811)
## 1.25.0 (2020-08-23)
* fix fromFormat with Intl formats containing non-breaking spaces
* Support higher precision in ISO milliseconds
* Some fixes for 00:30 timezones
* Fix some throwOnInvalid for invalid Intervals
* Various doc fixes
* Fix Interval#isSame for empty intervals
* Mark package as side effect-free
* Add support for intervals with a large number of seconds
## 1.24.1 (2020-05-04)
* Remove erroneous `console.log` call
## 1.24.0 (2020-05-03)
* Update polyfills for pollyfilled build
## 1.23.0 (2020-04-02)
* Allow minus sign prefix when creating Duration from ISO
## 1.22.2 (2020-03-25)
* Added more details to error messages for type errors
## 1.22.1 (2020-03-19)
* Added support for ISO basic format to DateTime#toISO
## 1.22.0 (2020-01-26)
* Fix setZone's handling of pre-1970 dates with milisecond components
* Fix keepLocalTime for large jumps near the target zone's DST
* Fix cache perf for toRelative()
## 1.21.3 (2019-11-28)
* Fix parsing of meridiems in macro tokens in newer versions of v8
## 1.21.2 (2019-11-18)
* Fix bug in Chrome Canary that threw off time zone calculations
## 1.21.1 (2019-11-03)
* Fix for quarter parsing
* Some documentation updates
## 1.21.0 (2019-10-30)
* Added quarter support to the parser
* Fix some rounding issues in ISO formatting
## 1.20.0 (2019-10-29)
* Added Duration#mapUnits
* added Interval#toISODate and Interval#toISOTime
* Some documentation fixes
## 1.19.3
* Cache offset values
* Fix handling of negative sub 1-hour offsets
## 1.19.2
* Speculative fix for Node 6
## 1.19.1
* Fix Intl.DateTimeFormat usage for polyfills
## 1.19.0
* Interval#splitAt now ignores input dates outside the interval
* Don't allow decimals in DateTime creation
## 1.18.2
* Fix handling of decimals in DateTime#plus and #minus
## 1.18.1
* Fix validity when adding or subtracting time that exceeds Date max/min boundaries
## 1.18.0
* Add support for macro tokens in the parser
## 1.17.2
* Fix issue with `toRelative` using `style: short` with plural days
## 1.17.1
* Reject out-of-range numbers in DateTime.fromMillis
* Reject 0s in ISO date inputs
## 1.17.0
* DateTime.min and DateTime.max throw if they get the wrong kind of arguments
* Fixed throwOnInvalid logic for Interval
* Added `DATETIME_MED_WITH_WEEKDAY` preset
## 1.16.1
* Catch errors trying to use Intl in weird versions of IE 11
## 1.16.0
* Fixed locale default logic for `DateTime#toFormat("ZZZZ")
## 1.15.0
* Added `formatOffset` to Zones
## 1.14.0
* Allow the zone argument to Interval.fromISO with duration components
* Ignore the zone argument to Duration factory methods
## 1.13.3
* Fix keepLocalTime calculations that span offset changes
## 1.13.2
* Fixed ISO formatting for dates > 999
## 1.13.1
* Performance improvements for regex parsing
## 1.13.0
* Support numberSystem in fromFormat
* Fix validity for bad initial zone specifiers
## 1.12.1
* Fix cross-month diffs in some scenarios
* Fix time zone parsing when the time zone isn't at the end
* Memoize IANA zone creation
## 1.12.0
* Add some explicit CDN support to the NPM package
* Add week token to duration ISO support
* Lots of cleanup and test coverage changes
## 1.11.4
* `setZone("local")` now returns the defaultZone if it is set
* Fixes for the polyfilled build
## 1.11.3
* Allow 24:00 in ISO (and other) strings
* Fix some bugs with the typecheck functions like `DateTime.isDateTime()`
## 1.11.2
* Fixed handling of some characters in fromFormat literal sections
* Hanlde string values in object arguments to DateTime methods
* Fixed toRelativeCalendar's handling of zones in the base date
## 1.11.1
* Fix DateTime#plus() when spanning across AD 100
## 1.11.0
* Fix low-year handling for IANA zones
* `DateTime#toLocal()` now uses the default locale
* Fix zero duration formatting
* Many documentation fixes
## 1.10.0
- Fix endOf("day") during DSTs (#399)
- Add `Interval#mapEndpoints (#400)
- Add `DateTime#zone` and `Info.normalizeZone` (#404)
## 1.9.0
- Add `DateTime#toRelative` and `DateTime#toRelativeCalendar`
## 1.8.3
- Allow "UTC" in the zone position of `fromSQL`
- Force `isDateTime` and `isDuration` to return booleans in all cases
## 1.8.2
- Trim leading \u200e characters from offset names in Edge 16 and 17
## 1.8.1
- Add `DateTime.fromSeconds` and `DateTime#toSeconds`
## 1.7.1
- Floor the seconds instead of rounding them when outputting the 'X' format
- Change the options to toLocale to override the configuration (the previous options were essentially ignored)
## 1.6.2
- Fixing merge error that resulted in bad error messages
## 1.6.0
- **midly breaking** Rework negative durations
- Fix handling weekdays at the end of leap week years
- Add isDuration, isDateTime, and isInterval
- Fix handling of Luxon object arguments passed from other execution contexts
## 1.5.0
- Improved error message
- Added DateTime#invalidExplanation, Duration#invalidExplanation, Interval#invalidExplanation to provide more details on invalid objects
## 1.4.6
- Cache Intl objects for an 85x speed up on basic operations using non-en locales
## 1.4.5
- Fix minified builds
## 1.4.4
- Fix hour formatting in RFC822 strings
- Interval.fromISO accepts formats with durations
## 1.4.3
Removal accidentally-introduced runtime dependency
## 1.4.2
- Handle locale strings with BCP 47 extensions. Especially helpful for environments with funky default locales
- Support for [weekYear]-W[weekNumber] ISO 8601 strings
## 1.4.1
- Empty diffs now have all the asked-for units in them, set at 0
- Duration operations perserve the superset of units
## 1.4.0
- Add x and X to toFormat for formatting Epoch seconds and Epoch milliseconds
- Parser allows a wider range of IANA zone specifiers
- BREAKING: Etc/GMT+10 is now interpreted as UTC-10, per spec
## 1.3.3
Documentation fixes
## 1.3.2
- DateTime.fromMillis will throw if passed a non-number
- Fixes for type checking across JS contexts
## 1.3.1
- Include milliseconds in Duration#toISO
- Avoid deprecation warning from DateTime#inspect in Node 10
## 1.3.0
- **mildly breaking change** Duration.toFormat now floors its outputs instead of rounding them (see #224)
- Added 'floor' option to Duration.toFormat and deprecated the 'round' option
- Added `Dateime.toBSON`
- Fixed infinite loop when passing invalid or zero-length durations to Interval#splitBy
- Added better error handling to Duration.fromObject()
## 1.2.1
- 222x speed-up in DateTime creation for non-en locales
- Added `DateTime#toMillis` alias for `DateTime#valueOf`
- Fixed types on zone exports
## 1.2.0
- Export Zone classes
- Fix `endOf` and `startOf` for quarters
- Change `toFormat("Z")` to return a number for UTC
- Allow "GTM" as an argument to `setZone`
## 1.1.0
- Support for zone names with more than two components
- Fixed long-term-accurate conversions for months
- Added `weeksInWeekYear`
## 1.0.0
- The big one-oh. No changes from 0.5.8.
## 0.5.8
- Large perf improvements for `DateTime#toFormat()`, when using non-intl numbers
## 0.5.7
- Added AMD build to the NPM package
- Large performance improvements to technical formatting (e.g. `DateTime#toISO`)
## 0.5.6
- Refactor internals
- Added support for fractional seconds in `Duration.fromISO`
- Added browser global to the NPM package
## 0.5.5
- Best-we-can-do fix for `DateTime#toLocaleString()` for fixed-offset zones when showing the zone name in the output
- Fixed `Duration#shiftTo` for unormalized Durations that need a rollup cascade
## 0.5.4
- Fix default locales in Node
- Fix prototype to help with React inspection
- Improve REPL output for Durations in Node
## 0.5.3
- Remove errant ICU runtime dep (again)
## 0.5.2
- Remove comments from minified builds (introduced by 0.5.1)
## 0.5.1
- Fixed minified builds (oops)
- Fix computation of fractional parts of diffs
## 0.5.0
- `isBefore()` returns true for the end of the interval, consistent with being half-open
- `zoneName` now rturns `null` for invalid DateTimes
- Added quarter support
- Adding a month to Jan 31 gives Feb 28/29
## 0.4.0
- Always round down to the nearest millisecond when parsing
## 0.3.1
- Fixed `toLocaleString` for fixed-offset zones in the absence of Intl
- Added `Info.isValidIANAZone`
- Made malformed zone specifiers result in invalid DateTime instances
## 0.3.0
- Rename DateTime.fromString to DateTime.fromFormat (leaving deprecated DateTime.fromString)
- Rename DateTime.fromStringExplain to DateTime.fromFormatExplain (leaving deprecated DateTime.fromStringExplain)
- Support Etc/GMT IANA zones
- Perf fixes for zones
- Rework build infrastructure
## 0.2.12
- Fix DateTime.fromObject's handling of default zones
- Change `keepCalendarTime` to `keepLocalTime`
## 0.2.11
- Handle no arguments in `DateTime.min` and `DateTime.max`
- Documentation fixes
## 0.2.10
- Fix bug where Durations could sometimes mutate
## 0.2.9
- Fix `DateTime.fromMillis(0)` more thoroughly
## 0.2.8
- Fix sourcemaps
## 0.2.7
- Fix `DateTime.fromMillis(0)`
## 0.2.6
- Fix 'h' and 'hh' `toFormat` tokens for midnight
## 0.2.5
- Better `shiftTo` behavior for durations with floating point components
## 0.2.4
- Fix `toHTTP` to use 24-hour hours
- Tighten up regular expressions
- Various documentation fixes
## 0.2.3
- Fixes for `diff` with multiple units
## 0.2.2
- Fixes for `fromSQL`, `toSQL`, `toSQLTime`, and `toSQLDate`
- Add `includeOffset` option to `toISO` and `toISOTime`
## 0.2.1
- Add `module` field to package.json
## 0.2.0
- Remove polyfills from main builds
- Update compilation toolchain to target builds more exactly
- Fix IE in polyfill build
## 0.1.0
- Add `.fromSQL`, `#toSQL`, `#toSQLTime`, `#toSQLDate`
- Fix AM/PM parsing
- Major perf improvements
- Default to system locale when using macro formats in `#toFormat`
- `.fromISO` accepts standalone times
- See https://github.com/moment/luxon/issues/93 for important news concerning field accessibility
## 0.0.22
- Add 'u' formatting and parsing
- Add 'y', 'yyyyy', and 'yyyyyy' parsing tokens
- Add 'yyyyyy' formatting token
- Better error messages for missing arguments to `DateTime.fromString`
## 0.0.21
- Fix zones for Edge
## 0.0.20
- Fix `fromISO` to accept various levels of subsecond precision
## 0.0.19
- Fixed parsing for ordinals
- Made parsing stricter
## 0.0.18
- Fixed formatting for non-hour aligned fixed-offset zones
- Fixed longterm conversion accuracy option in diffs
- Fixed invalid handling in `Interval#set`
## 0.0.17
- Fixing formatting for fixed-offset zones
## 0.0.16
- Fixes for IE 9 & 10
## 0.0.15
- Fixing busted release 0.0.14
## 0.0.13
- toLocaleString() and others default to the system's locale
- support for ISO week durations in `Duration.fromISO`
## 0.0.12
- Improve non-Intl fallbacks for toLocaleString
- Fix `offsetNameShort` and `offsetNameLong` for non-Intl environments
- Added `weekdayShort`, `weekdayLong`, `monthShort`, `monthLong` DateTime getters
## 0.0.10
- Only include build dir in NPM module
## 0.0.9
- Move to Moment Github org
## 0.0.8
- The local zone can now report its IANA name
- Fixed parsing bug for `yy` and `kk`
- Improved test coverage
## 0.0.7
- Added `toLocaleParts`
- Slightly more friendly month/weekday parsing
- Default locale setting
## 0.0.6
- Stricter `toJSDate`
- `fromISO` now supports `year` and `year-month` formats
- More graceful degradation in the absence of platform features
## 0.0.5
Experimental, but now broadly useful.
# Luxon
[![MIT License][license-image]][license] [![Build Status][travis-image]][travis-url] [![NPM version][npm-version-image]][npm-url] [![Coverage Status][test-coverage-image]][test-coverage-url] [![Doc coverage][doc-coverage-image]][doc-url] [![PRs welcome][contributing-image]][contributing-url]
Luxon is a library for working with dates and times in JavaScript.
```js
DateTime.now().setZone("America/New_York").minus({ weeks: 1 }).endOf("day").toISO();
```
## Features
* DateTime, Duration, and Interval types.
* Immutable, chainable, unambiguous API.
* Parsing and formatting for common and custom formats.
* Native time zone and Intl support (no locale or tz files).
## Download/install
[Download/install instructions](https://moment.github.io/luxon/docs/manual/install.html)
## Documentation
* [General documentation][doc-url]
* [API docs](https://moment.github.io/luxon/docs/identifiers.html)
* [Quick tour](https://moment.github.io/luxon/docs/manual/tour.html)
* [For Moment users](https://moment.github.io/luxon/docs/manual/moment.html)
* [Why does Luxon exist?](https://moment.github.io/luxon/docs/manual/why.html)
* [A quick demo](https://moment.github.io/luxon/demo/global.html)
## Development
See [contributing](contributing.md).
![Phasers to stun][phasers-image]
[license-image]: http://img.shields.io/badge/license-MIT-blue.svg
[license]: license.md
[travis-url]: http://travis-ci.org/moment/luxon
[travis-image]: https://api.travis-ci.org/moment/luxon.svg?branch=master
[npm-url]: https://npmjs.org/package/luxon
[npm-version-image]: https://badge.fury.io/js/luxon.svg
[doc-url]: https://moment.github.io/luxon/docs/
[doc-coverage-image]: https://moment.github.io/luxon/docs/badge.svg
[test-coverage-url]: https://codecov.io/gh/moment/luxon
[test-coverage-image]: https://codecov.io/gh/moment/luxon/branch/master/graph/badge.svg
[contributing-url]: https://moment.github.io/luxon/docs/manual/contributing.html
[contributing-image]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg
[phasers-image]: https://img.shields.io/badge/phasers-stun-brightgreen.svg
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
var luxon=function(e){"use strict";function t(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function n(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function i(e){return(i=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function o(e,t){return(o=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function a(e,t,n){return(a=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&o(i,n.prototype),i}).apply(null,arguments)}function u(e){var t="function"==typeof Map?new Map:void 0;return(u=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return a(e,arguments,i(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),o(r,e)})(e)}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function c(e){var t=0;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(e=function(e,t){if(e){if("string"==typeof e)return s(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(e,t):void 0}}(e)))return function(){return t>=e.length?{done:!0}:{done:!1,value:e[t++]}};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(t=e[Symbol.iterator]()).next.bind(t)}var l=function(e){function t(){return e.apply(this,arguments)||this}return r(t,e),t}(u(Error)),f=function(e){function t(t){return e.call(this,"Invalid DateTime: "+t.toMessage())||this}return r(t,e),t}(l),d=function(e){function t(t){return e.call(this,"Invalid Interval: "+t.toMessage())||this}return r(t,e),t}(l),h=function(e){function t(t){return e.call(this,"Invalid Duration: "+t.toMessage())||this}return r(t,e),t}(l),m=function(e){function t(){return e.apply(this,arguments)||this}return r(t,e),t}(l),y=function(e){function t(t){return e.call(this,"Invalid unit "+t)||this}return r(t,e),t}(l),v=function(e){function t(){return e.apply(this,arguments)||this}return r(t,e),t}(l),g=function(e){function t(){return e.call(this,"Zone is an abstract class")||this}return r(t,e),t}(l),p="numeric",w="short",k="long",b={year:p,month:p,day:p},O={year:p,month:w,day:p},S={year:p,month:w,day:p,weekday:w},T={year:p,month:k,day:p},M={year:p,month:k,day:p,weekday:k},N={hour:p,minute:p},E={hour:p,minute:p,second:p},D={hour:p,minute:p,second:p,timeZoneName:w},I={hour:p,minute:p,second:p,timeZoneName:k},V={hour:p,minute:p,hour12:!1},L={hour:p,minute:p,second:p,hour12:!1},x={hour:p,minute:p,second:p,hour12:!1,timeZoneName:w},C={hour:p,minute:p,second:p,hour12:!1,timeZoneName:k},F={year:p,month:p,day:p,hour:p,minute:p},Z={year:p,month:p,day:p,hour:p,minute:p,second:p},j={year:p,month:w,day:p,hour:p,minute:p},A={year:p,month:w,day:p,hour:p,minute:p,second:p},z={year:p,month:w,day:p,weekday:w,hour:p,minute:p},_={year:p,month:k,day:p,hour:p,minute:p,timeZoneName:w},q={year:p,month:k,day:p,hour:p,minute:p,second:p,timeZoneName:w},H={year:p,month:k,day:p,weekday:k,hour:p,minute:p,timeZoneName:k},U={year:p,month:k,day:p,weekday:k,hour:p,minute:p,second:p,timeZoneName:k};function R(e){return void 0===e}function P(e){return"number"==typeof e}function W(e){return"number"==typeof e&&e%1==0}function J(){try{return"undefined"!=typeof Intl&&Intl.DateTimeFormat}catch(e){return!1}}function Y(){return!R(Intl.DateTimeFormat.prototype.formatToParts)}function G(){try{return"undefined"!=typeof Intl&&!!Intl.RelativeTimeFormat}catch(e){return!1}}function $(e,t,n){if(0!==e.length)return e.reduce(function(e,r){var i=[t(r),r];return e&&n(e[0],i[0])===e[0]?e:i},null)[1]}function B(e,t){return t.reduce(function(t,n){return t[n]=e[n],t},{})}function Q(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function K(e,t,n){return W(e)&&e>=t&&e<=n}function X(e,t){void 0===t&&(t=2);var n=e<0?"-":"",r=n?-1*e:e;return""+n+(r.toString().length<t?("0".repeat(t)+r).slice(-t):r.toString())}function ee(e){return R(e)||null===e||""===e?void 0:parseInt(e,10)}function te(e){if(!R(e)&&null!==e&&""!==e){var t=1e3*parseFloat("0."+e);return Math.floor(t)}}function ne(e,t,n){void 0===n&&(n=!1);var r=Math.pow(10,t);return(n?Math.trunc:Math.round)(e*r)/r}function re(e){return e%4==0&&(e%100!=0||e%400==0)}function ie(e){return re(e)?366:365}function oe(e,t){var n,r,i=(n=t-1)-(r=12)*Math.floor(n/r)+1;return 2===i?re(e+(t-i)/12)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][i-1]}function ae(e){var t=Date.UTC(e.year,e.month-1,e.day,e.hour,e.minute,e.second,e.millisecond);return e.year<100&&e.year>=0&&(t=new Date(t)).setUTCFullYear(t.getUTCFullYear()-1900),+t}function ue(e){var t=(e+Math.floor(e/4)-Math.floor(e/100)+Math.floor(e/400))%7,n=e-1,r=(n+Math.floor(n/4)-Math.floor(n/100)+Math.floor(n/400))%7;return 4===t||3===r?53:52}function se(e){return e>99?e:e>60?1900+e:2e3+e}function ce(e,t,n,r){void 0===r&&(r=null);var i=new Date(e),o={hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(o.timeZone=r);var a=Object.assign({timeZoneName:t},o),u=J();if(u&&Y()){var s=new Intl.DateTimeFormat(n,a).formatToParts(i).find(function(e){return"timezonename"===e.type.toLowerCase()});return s?s.value:null}if(u){var c=new Intl.DateTimeFormat(n,o).format(i);return new Intl.DateTimeFormat(n,a).format(i).substring(c.length).replace(/^[, \u200e]+/,"")}return null}function le(e,t){var n=parseInt(e,10);Number.isNaN(n)&&(n=0);var r=parseInt(t,10)||0;return 60*n+(n<0||Object.is(n,-0)?-r:r)}function fe(e){var t=Number(e);if("boolean"==typeof e||""===e||Number.isNaN(t))throw new v("Invalid unit value "+e);return t}function de(e,t,n){var r={};for(var i in e)if(Q(e,i)){if(n.indexOf(i)>=0)continue;var o=e[i];if(void 0===o||null===o)continue;r[t(i)]=fe(o)}return r}function he(e,t){var n=Math.trunc(Math.abs(e/60)),r=Math.trunc(Math.abs(e%60)),i=e>=0?"+":"-";switch(t){case"short":return""+i+X(n,2)+":"+X(r,2);case"narrow":return""+i+n+(r>0?":"+r:"");case"techie":return""+i+X(n,2)+X(r,2);default:throw new RangeError("Value format "+t+" is out of range for property format")}}function me(e){return B(e,["hour","minute","second","millisecond"])}var ye=/[A-Za-z_+-]{1,256}(:?\/[A-Za-z_+-]{1,256}(\/[A-Za-z_+-]{1,256})?)?/;function ve(e){return JSON.stringify(e,Object.keys(e).sort())}var ge=["January","February","March","April","May","June","July","August","September","October","November","December"],pe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],we=["J","F","M","A","M","J","J","A","S","O","N","D"];function ke(e){switch(e){case"narrow":return[].concat(we);case"short":return[].concat(pe);case"long":return[].concat(ge);case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var be=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Oe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Se=["M","T","W","T","F","S","S"];function Te(e){switch(e){case"narrow":return[].concat(Se);case"short":return[].concat(Oe);case"long":return[].concat(be);case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Me=["AM","PM"],Ne=["Before Christ","Anno Domini"],Ee=["BC","AD"],De=["B","A"];function Ie(e){switch(e){case"narrow":return[].concat(De);case"short":return[].concat(Ee);case"long":return[].concat(Ne);default:return null}}function Ve(e,t){for(var n,r="",i=c(e);!(n=i()).done;){var o=n.value;o.literal?r+=o.val:r+=t(o.val)}return r}var Le={D:b,DD:O,DDD:T,DDDD:M,t:N,tt:E,ttt:D,tttt:I,T:V,TT:L,TTT:x,TTTT:C,f:F,ff:j,fff:_,ffff:H,F:Z,FF:A,FFF:q,FFFF:U},xe=function(){function e(e,t){this.opts=t,this.loc=e,this.systemLoc=null}e.create=function(t,n){return void 0===n&&(n={}),new e(t,n)},e.parseFormat=function(e){for(var t=null,n="",r=!1,i=[],o=0;o<e.length;o++){var a=e.charAt(o);"'"===a?(n.length>0&&i.push({literal:r,val:n}),t=null,n="",r=!r):r?n+=a:a===t?n+=a:(n.length>0&&i.push({literal:!1,val:n}),n=a,t=a)}return n.length>0&&i.push({literal:r,val:n}),i},e.macroTokenToFormatOpts=function(e){return Le[e]};var t=e.prototype;return t.formatWithSystemDefault=function(e,t){return null===this.systemLoc&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,Object.assign({},this.opts,t)).format()},t.formatDateTime=function(e,t){return void 0===t&&(t={}),this.loc.dtFormatter(e,Object.assign({},this.opts,t)).format()},t.formatDateTimeParts=function(e,t){return void 0===t&&(t={}),this.loc.dtFormatter(e,Object.assign({},this.opts,t)).formatToParts()},t.resolvedOptions=function(e,t){return void 0===t&&(t={}),this.loc.dtFormatter(e,Object.assign({},this.opts,t)).resolvedOptions()},t.num=function(e,t){if(void 0===t&&(t=0),this.opts.forceSimple)return X(e,t);var n=Object.assign({},this.opts);return t>0&&(n.padTo=t),this.loc.numberFormatter(n).format(e)},t.formatDateTimeFromString=function(t,n){var r=this,i="en"===this.loc.listingMode(),o=this.loc.outputCalendar&&"gregory"!==this.loc.outputCalendar&&Y(),a=function(e,n){return r.loc.extract(t,e,n)},u=function(e){return t.isOffsetFixed&&0===t.offset&&e.allowZ?"Z":t.isValid?t.zone.formatOffset(t.ts,e.format):""},s=function(){return i?function(e){return Me[e.hour<12?0:1]}(t):a({hour:"numeric",hour12:!0},"dayperiod")},c=function(e,n){return i?function(e,t){return ke(t)[e.month-1]}(t,e):a(n?{month:e}:{month:e,day:"numeric"},"month")},l=function(e,n){return i?function(e,t){return Te(t)[e.weekday-1]}(t,e):a(n?{weekday:e}:{weekday:e,month:"long",day:"numeric"},"weekday")},f=function(e){return i?function(e,t){return Ie(t)[e.year<0?0:1]}(t,e):a({era:e},"era")};return Ve(e.parseFormat(n),function(n){switch(n){case"S":return r.num(t.millisecond);case"u":case"SSS":return r.num(t.millisecond,3);case"s":return r.num(t.second);case"ss":return r.num(t.second,2);case"m":return r.num(t.minute);case"mm":return r.num(t.minute,2);case"h":return r.num(t.hour%12==0?12:t.hour%12);case"hh":return r.num(t.hour%12==0?12:t.hour%12,2);case"H":return r.num(t.hour);case"HH":return r.num(t.hour,2);case"Z":return u({format:"narrow",allowZ:r.opts.allowZ});case"ZZ":return u({format:"short",allowZ:r.opts.allowZ});case"ZZZ":return u({format:"techie",allowZ:r.opts.allowZ});case"ZZZZ":return t.zone.offsetName(t.ts,{format:"short",locale:r.loc.locale});case"ZZZZZ":return t.zone.offsetName(t.ts,{format:"long",locale:r.loc.locale});case"z":return t.zoneName;case"a":return s();case"d":return o?a({day:"numeric"},"day"):r.num(t.day);case"dd":return o?a({day:"2-digit"},"day"):r.num(t.day,2);case"c":return r.num(t.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return r.num(t.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return o?a({month:"numeric",day:"numeric"},"month"):r.num(t.month);case"LL":return o?a({month:"2-digit",day:"numeric"},"month"):r.num(t.month,2);case"LLL":return c("short",!0);case"LLLL":return c("long",!0);case"LLLLL":return c("narrow",!0);case"M":return o?a({month:"numeric"},"month"):r.num(t.month);case"MM":return o?a({month:"2-digit"},"month"):r.num(t.month,2);case"MMM":return c("short",!1);case"MMMM":return c("long",!1);case"MMMMM":return c("narrow",!1);case"y":return o?a({year:"numeric"},"year"):r.num(t.year);case"yy":return o?a({year:"2-digit"},"year"):r.num(t.year.toString().slice(-2),2);case"yyyy":return o?a({year:"numeric"},"year"):r.num(t.year,4);case"yyyyyy":return o?a({year:"numeric"},"year"):r.num(t.year,6);case"G":return f("short");case"GG":return f("long");case"GGGGG":return f("narrow");case"kk":return r.num(t.weekYear.toString().slice(-2),2);case"kkkk":return r.num(t.weekYear,4);case"W":return r.num(t.weekNumber);case"WW":return r.num(t.weekNumber,2);case"o":return r.num(t.ordinal);case"ooo":return r.num(t.ordinal,3);case"q":return r.num(t.quarter);case"qq":return r.num(t.quarter,2);case"X":return r.num(Math.floor(t.ts/1e3));case"x":return r.num(t.ts);default:return function(n){var i=e.macroTokenToFormatOpts(n);return i?r.formatWithSystemDefault(t,i):n}(n)}})},t.formatDurationFromString=function(t,n){var r,i=this,o=function(e){switch(e[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"M":return"month";case"y":return"year";default:return null}},a=e.parseFormat(n),u=a.reduce(function(e,t){var n=t.literal,r=t.val;return n?e:e.concat(r)},[]),s=t.shiftTo.apply(t,u.map(o).filter(function(e){return e}));return Ve(a,(r=s,function(e){var t=o(e);return t?i.num(r.get(t),e.length):e}))},e}(),Ce=function(){function e(e,t){this.reason=e,this.explanation=t}return e.prototype.toMessage=function(){return this.explanation?this.reason+": "+this.explanation:this.reason},e}(),Fe=function(){function e(){}var t=e.prototype;return t.offsetName=function(e,t){throw new g},t.formatOffset=function(e,t){throw new g},t.offset=function(e){throw new g},t.equals=function(e){throw new g},n(e,[{key:"type",get:function(){throw new g}},{key:"name",get:function(){throw new g}},{key:"universal",get:function(){throw new g}},{key:"isValid",get:function(){throw new g}}]),e}(),Ze=null,je=function(e){function t(){return e.apply(this,arguments)||this}r(t,e);var i=t.prototype;return i.offsetName=function(e,t){return ce(e,t.format,t.locale)},i.formatOffset=function(e,t){return he(this.offset(e),t)},i.offset=function(e){return-new Date(e).getTimezoneOffset()},i.equals=function(e){return"local"===e.type},n(t,[{key:"type",get:function(){return"local"}},{key:"name",get:function(){return J()?(new Intl.DateTimeFormat).resolvedOptions().timeZone:"local"}},{key:"universal",get:function(){return!1}},{key:"isValid",get:function(){return!0}}],[{key:"instance",get:function(){return null===Ze&&(Ze=new t),Ze}}]),t}(Fe),Ae=RegExp("^"+ye.source+"$"),ze={};var _e={year:0,month:1,day:2,hour:3,minute:4,second:5};var qe={},He=function(e){function t(n){var r;return(r=e.call(this)||this).zoneName=n,r.valid=t.isValidZone(n),r}r(t,e),t.create=function(e){return qe[e]||(qe[e]=new t(e)),qe[e]},t.resetCache=function(){qe={},ze={}},t.isValidSpecifier=function(e){return!(!e||!e.match(Ae))},t.isValidZone=function(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch(e){return!1}},t.parseGMTOffset=function(e){if(e){var t=e.match(/^Etc\/GMT(0|[+-]\d{1,2})$/i);if(t)return-60*parseInt(t[1])}return null};var i=t.prototype;return i.offsetName=function(e,t){return ce(e,t.format,t.locale,this.name)},i.formatOffset=function(e,t){return he(this.offset(e),t)},i.offset=function(e){var t=new Date(e);if(isNaN(t))return NaN;var n,r=(n=this.name,ze[n]||(ze[n]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})),ze[n]),i=r.formatToParts?function(e,t){for(var n=e.formatToParts(t),r=[],i=0;i<n.length;i++){var o=n[i],a=o.type,u=o.value,s=_e[a];R(s)||(r[s]=parseInt(u,10))}return r}(r,t):function(e,t){var n=e.format(t).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(n),i=r[1],o=r[2];return[r[3],i,o,r[4],r[5],r[6]]}(r,t),o=i[0],a=i[1],u=i[2],s=i[3],c=i[4],l=i[5],f=+t,d=f%1e3;return(ae({year:o,month:a,day:u,hour:24===s?0:s,minute:c,second:l,millisecond:0})-(f-=d>=0?d:1e3+d))/6e4},i.equals=function(e){return"iana"===e.type&&e.name===this.name},n(t,[{key:"type",get:function(){return"iana"}},{key:"name",get:function(){return this.zoneName}},{key:"universal",get:function(){return!1}},{key:"isValid",get:function(){return this.valid}}]),t}(Fe),Ue=null,Re=function(e){function t(t){var n;return(n=e.call(this)||this).fixed=t,n}r(t,e),t.instance=function(e){return 0===e?t.utcInstance:new t(e)},t.parseSpecifier=function(e){if(e){var n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new t(le(n[1],n[2]))}return null},n(t,null,[{key:"utcInstance",get:function(){return null===Ue&&(Ue=new t(0)),Ue}}]);var i=t.prototype;return i.offsetName=function(){return this.name},i.formatOffset=function(e,t){return he(this.fixed,t)},i.offset=function(){return this.fixed},i.equals=function(e){return"fixed"===e.type&&e.fixed===this.fixed},n(t,[{key:"type",get:function(){return"fixed"}},{key:"name",get:function(){return 0===this.fixed?"UTC":"UTC"+he(this.fixed,"narrow")}},{key:"universal",get:function(){return!0}},{key:"isValid",get:function(){return!0}}]),t}(Fe),Pe=function(e){function t(t){var n;return(n=e.call(this)||this).zoneName=t,n}r(t,e);var i=t.prototype;return i.offsetName=function(){return null},i.formatOffset=function(){return""},i.offset=function(){return NaN},i.equals=function(){return!1},n(t,[{key:"type",get:function(){return"invalid"}},{key:"name",get:function(){return this.zoneName}},{key:"universal",get:function(){return!1}},{key:"isValid",get:function(){return!1}}]),t}(Fe);function We(e,t){var n;if(R(e)||null===e)return t;if(e instanceof Fe)return e;if("string"==typeof e){var r=e.toLowerCase();return"local"===r?t:"utc"===r||"gmt"===r?Re.utcInstance:null!=(n=He.parseGMTOffset(e))?Re.instance(n):He.isValidSpecifier(r)?He.create(e):Re.parseSpecifier(r)||new Pe(e)}return P(e)?Re.instance(e):"object"==typeof e&&e.offset&&"number"==typeof e.offset?e:new Pe(e)}var Je=function(){return Date.now()},Ye=null,Ge=null,$e=null,Be=null,Qe=!1,Ke=function(){function e(){}return e.resetCaches=function(){ct.resetCache(),He.resetCache()},n(e,null,[{key:"now",get:function(){return Je},set:function(e){Je=e}},{key:"defaultZoneName",get:function(){return e.defaultZone.name},set:function(e){Ye=e?We(e):null}},{key:"defaultZone",get:function(){return Ye||je.instance}},{key:"defaultLocale",get:function(){return Ge},set:function(e){Ge=e}},{key:"defaultNumberingSystem",get:function(){return $e},set:function(e){$e=e}},{key:"defaultOutputCalendar",get:function(){return Be},set:function(e){Be=e}},{key:"throwOnInvalid",get:function(){return Qe},set:function(e){Qe=e}}]),e}(),Xe={};function et(e,t){void 0===t&&(t={});var n=JSON.stringify([e,t]),r=Xe[n];return r||(r=new Intl.DateTimeFormat(e,t),Xe[n]=r),r}var tt={};var nt={};function rt(e,t){void 0===t&&(t={});var n=t,r=(n.base,function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}(n,["base"])),i=JSON.stringify([e,r]),o=nt[i];return o||(o=new Intl.RelativeTimeFormat(e,t),nt[i]=o),o}var it=null;function ot(e,t,n,r,i){var o=e.listingMode(n);return"error"===o?null:"en"===o?r(t):i(t)}var at=function(){function e(e,t,n){if(this.padTo=n.padTo||0,this.floor=n.floor||!1,!t&&J()){var r={useGrouping:!1};n.padTo>0&&(r.minimumIntegerDigits=n.padTo),this.inf=function(e,t){void 0===t&&(t={});var n=JSON.stringify([e,t]),r=tt[n];return r||(r=new Intl.NumberFormat(e,t),tt[n]=r),r}(e,r)}}return e.prototype.format=function(e){if(this.inf){var t=this.floor?Math.floor(e):e;return this.inf.format(t)}return X(this.floor?Math.floor(e):ne(e,3),this.padTo)},e}(),ut=function(){function e(e,t,n){var r;if(this.opts=n,this.hasIntl=J(),e.zone.universal&&this.hasIntl){var i=e.offset/60*-1,o=i>=0?"Etc/GMT+"+i:"Etc/GMT"+i,a=He.isValidZone(o);0!==e.offset&&a?(r=o,this.dt=e):(r="UTC",n.timeZoneName?this.dt=e:this.dt=0===e.offset?e:sr.fromMillis(e.ts+60*e.offset*1e3))}else"local"===e.zone.type?this.dt=e:(this.dt=e,r=e.zone.name);if(this.hasIntl){var u=Object.assign({},this.opts);r&&(u.timeZone=r),this.dtf=et(t,u)}}var t=e.prototype;return t.format=function(){if(this.hasIntl)return this.dtf.format(this.dt.toJSDate());var e=function(e){switch(ve(B(e,["weekday","era","year","month","day","hour","minute","second","timeZoneName","hour12"]))){case ve(b):return"M/d/yyyy";case ve(O):return"LLL d, yyyy";case ve(S):return"EEE, LLL d, yyyy";case ve(T):return"LLLL d, yyyy";case ve(M):return"EEEE, LLLL d, yyyy";case ve(N):return"h:mm a";case ve(E):return"h:mm:ss a";case ve(D):case ve(I):return"h:mm a";case ve(V):return"HH:mm";case ve(L):return"HH:mm:ss";case ve(x):case ve(C):return"HH:mm";case ve(F):return"M/d/yyyy, h:mm a";case ve(j):return"LLL d, yyyy, h:mm a";case ve(_):return"LLLL d, yyyy, h:mm a";case ve(H):return"EEEE, LLLL d, yyyy, h:mm a";case ve(Z):return"M/d/yyyy, h:mm:ss a";case ve(A):return"LLL d, yyyy, h:mm:ss a";case ve(z):return"EEE, d LLL yyyy, h:mm a";case ve(q):return"LLLL d, yyyy, h:mm:ss a";case ve(U):return"EEEE, LLLL d, yyyy, h:mm:ss a";default:return"EEEE, LLLL d, yyyy, h:mm a"}}(this.opts),t=ct.create("en-US");return xe.create(t).formatDateTimeFromString(this.dt,e)},t.formatToParts=function(){return this.hasIntl&&Y()?this.dtf.formatToParts(this.dt.toJSDate()):[]},t.resolvedOptions=function(){return this.hasIntl?this.dtf.resolvedOptions():{locale:"en-US",numberingSystem:"latn",outputCalendar:"gregory"}},e}(),st=function(){function e(e,t,n){this.opts=Object.assign({style:"long"},n),!t&&G()&&(this.rtf=rt(e,n))}var t=e.prototype;return t.format=function(e,t){return this.rtf?this.rtf.format(e,t):function(e,t,n,r){void 0===n&&(n="always"),void 0===r&&(r=!1);var i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},o=-1===["hours","minutes","seconds"].indexOf(e);if("auto"===n&&o){var a="days"===e;switch(t){case 1:return a?"tomorrow":"next "+i[e][0];case-1:return a?"yesterday":"last "+i[e][0];case 0:return a?"today":"this "+i[e][0]}}var u=Object.is(t,-0)||t<0,s=Math.abs(t),c=1===s,l=i[e],f=r?c?l[1]:l[2]||l[1]:c?i[e][0]:e;return u?s+" "+f+" ago":"in "+s+" "+f}(t,e,this.opts.numeric,"long"!==this.opts.style)},t.formatToParts=function(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]},e}(),ct=function(){function e(e,t,n,r){var i=function(e){var t=e.indexOf("-u-");if(-1===t)return[e];var n,r=e.substring(0,t);try{n=et(e).resolvedOptions()}catch(e){n=et(r).resolvedOptions()}var i=n;return[r,i.numberingSystem,i.calendar]}(e),o=i[0],a=i[1],u=i[2];this.locale=o,this.numberingSystem=t||a||null,this.outputCalendar=n||u||null,this.intl=function(e,t,n){return J()?n||t?(e+="-u",n&&(e+="-ca-"+n),t&&(e+="-nu-"+t),e):e:[]}(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=r,this.fastNumbersCached=null}e.fromOpts=function(t){return e.create(t.locale,t.numberingSystem,t.outputCalendar,t.defaultToEN)},e.create=function(t,n,r,i){void 0===i&&(i=!1);var o=t||Ke.defaultLocale;return new e(o||(i?"en-US":function(){if(it)return it;if(J()){var e=(new Intl.DateTimeFormat).resolvedOptions().locale;return it=e&&"und"!==e?e:"en-US"}return it="en-US"}()),n||Ke.defaultNumberingSystem,r||Ke.defaultOutputCalendar,o)},e.resetCache=function(){it=null,Xe={},tt={},nt={}},e.fromObject=function(t){var n=void 0===t?{}:t,r=n.locale,i=n.numberingSystem,o=n.outputCalendar;return e.create(r,i,o)};var t=e.prototype;return t.listingMode=function(e){void 0===e&&(e=!0);var t=J()&&Y(),n=this.isEnglish(),r=!(null!==this.numberingSystem&&"latn"!==this.numberingSystem||null!==this.outputCalendar&&"gregory"!==this.outputCalendar);return t||n&&r||e?!t||n&&r?"en":"intl":"error"},t.clone=function(t){return t&&0!==Object.getOwnPropertyNames(t).length?e.create(t.locale||this.specifiedLocale,t.numberingSystem||this.numberingSystem,t.outputCalendar||this.outputCalendar,t.defaultToEN||!1):this},t.redefaultToEN=function(e){return void 0===e&&(e={}),this.clone(Object.assign({},e,{defaultToEN:!0}))},t.redefaultToSystem=function(e){return void 0===e&&(e={}),this.clone(Object.assign({},e,{defaultToEN:!1}))},t.months=function(e,t,n){var r=this;return void 0===t&&(t=!1),void 0===n&&(n=!0),ot(this,e,n,ke,function(){var n=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";return r.monthsCache[i][e]||(r.monthsCache[i][e]=function(e){for(var t=[],n=1;n<=12;n++){var r=sr.utc(2016,n,1);t.push(e(r))}return t}(function(e){return r.extract(e,n,"month")})),r.monthsCache[i][e]})},t.weekdays=function(e,t,n){var r=this;return void 0===t&&(t=!1),void 0===n&&(n=!0),ot(this,e,n,Te,function(){var n=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},i=t?"format":"standalone";return r.weekdaysCache[i][e]||(r.weekdaysCache[i][e]=function(e){for(var t=[],n=1;n<=7;n++){var r=sr.utc(2016,11,13+n);t.push(e(r))}return t}(function(e){return r.extract(e,n,"weekday")})),r.weekdaysCache[i][e]})},t.meridiems=function(e){var t=this;return void 0===e&&(e=!0),ot(this,void 0,e,function(){return Me},function(){if(!t.meridiemCache){var e={hour:"numeric",hour12:!0};t.meridiemCache=[sr.utc(2016,11,13,9),sr.utc(2016,11,13,19)].map(function(n){return t.extract(n,e,"dayperiod")})}return t.meridiemCache})},t.eras=function(e,t){var n=this;return void 0===t&&(t=!0),ot(this,e,t,Ie,function(){var t={era:e};return n.eraCache[e]||(n.eraCache[e]=[sr.utc(-40,1,1),sr.utc(2017,1,1)].map(function(e){return n.extract(e,t,"era")})),n.eraCache[e]})},t.extract=function(e,t,n){var r=this.dtFormatter(e,t).formatToParts().find(function(e){return e.type.toLowerCase()===n});return r?r.value:null},t.numberFormatter=function(e){return void 0===e&&(e={}),new at(this.intl,e.forceSimple||this.fastNumbers,e)},t.dtFormatter=function(e,t){return void 0===t&&(t={}),new ut(e,this.intl,t)},t.relFormatter=function(e){return void 0===e&&(e={}),new st(this.intl,this.isEnglish(),e)},t.isEnglish=function(){return"en"===this.locale||"en-us"===this.locale.toLowerCase()||J()&&new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")},t.equals=function(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar},n(e,[{key:"fastNumbers",get:function(){var e;return null==this.fastNumbersCached&&(this.fastNumbersCached=(!(e=this).numberingSystem||"latn"===e.numberingSystem)&&("latn"===e.numberingSystem||!e.locale||e.locale.startsWith("en")||J()&&"latn"===new Intl.DateTimeFormat(e.intl).resolvedOptions().numberingSystem)),this.fastNumbersCached}}]),e}();function lt(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=t.reduce(function(e,t){return e+t.source},"");return RegExp("^"+r+"$")}function ft(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){return t.reduce(function(t,n){var r=t[0],i=t[1],o=t[2],a=n(e,o),u=a[0],s=a[1],c=a[2];return[Object.assign(r,u),i||s,c]},[{},null,1]).slice(0,2)}}function dt(e){if(null==e)return[null,null];for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];for(var i=0,o=n;i<o.length;i++){var a=o[i],u=a[0],s=a[1],c=u.exec(e);if(c)return s(c)}return[null,null]}function ht(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e,n){var r,i={};for(r=0;r<t.length;r++)i[t[r]]=ee(e[n+r]);return[i,null,n+r]}}var mt=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,yt=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,vt=RegExp(""+yt.source+mt.source+"?"),gt=RegExp("(?:T"+vt.source+")?"),pt=ht("weekYear","weekNumber","weekDay"),wt=ht("year","ordinal"),kt=RegExp(yt.source+" ?(?:"+mt.source+"|("+ye.source+"))?"),bt=RegExp("(?: "+kt.source+")?");function Ot(e,t,n){var r=e[t];return R(r)?n:ee(r)}function St(e,t){return[{year:Ot(e,t),month:Ot(e,t+1,1),day:Ot(e,t+2,1)},null,t+3]}function Tt(e,t){return[{hours:Ot(e,t,0),minutes:Ot(e,t+1,0),seconds:Ot(e,t+2,0),milliseconds:te(e[t+3])},null,t+4]}function Mt(e,t){var n=!e[t]&&!e[t+1],r=le(e[t+1],e[t+2]);return[{},n?null:Re.instance(r),t+3]}function Nt(e,t){return[{},e[t]?He.create(e[t]):null,t+1]}var Et=RegExp("^T?"+yt.source+"$"),Dt=/^-?P(?:(?:(-?\d{1,9})Y)?(?:(-?\d{1,9})M)?(?:(-?\d{1,9})W)?(?:(-?\d{1,9})D)?(?:T(?:(-?\d{1,9})H)?(?:(-?\d{1,9})M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,9}))?S)?)?)$/;function It(e){var t=e[0],n=e[1],r=e[2],i=e[3],o=e[4],a=e[5],u=e[6],s=e[7],c=e[8],l="-"===t[0],f=s&&"-"===s[0],d=function(e,t){return void 0===t&&(t=!1),void 0!==e&&(t||e&&l)?-e:e};return[{years:d(ee(n)),months:d(ee(r)),weeks:d(ee(i)),days:d(ee(o)),hours:d(ee(a)),minutes:d(ee(u)),seconds:d(ee(s),"-0"===s),milliseconds:d(te(c),f)}]}var Vt={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Lt(e,t,n,r,i,o,a){var u={year:2===t.length?se(ee(t)):ee(t),month:pe.indexOf(n)+1,day:ee(r),hour:ee(i),minute:ee(o)};return a&&(u.second=ee(a)),e&&(u.weekday=e.length>3?be.indexOf(e)+1:Oe.indexOf(e)+1),u}var xt=/^(?:(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\d)(\d\d)))$/;function Ct(e){var t,n=e[1],r=e[2],i=e[3],o=e[4],a=e[5],u=e[6],s=e[7],c=e[8],l=e[9],f=e[10],d=e[11],h=Lt(n,o,i,r,a,u,s);return t=c?Vt[c]:l?0:le(f,d),[h,new Re(t)]}var Ft=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Zt=/^(Monday|Tuesday|Wedsday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,jt=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function At(e){var t=e[1],n=e[2],r=e[3];return[Lt(t,e[4],r,n,e[5],e[6],e[7]),Re.utcInstance]}function zt(e){var t=e[1],n=e[2],r=e[3],i=e[4],o=e[5],a=e[6];return[Lt(t,e[7],n,r,i,o,a),Re.utcInstance]}var _t=lt(/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,gt),qt=lt(/(\d{4})-?W(\d\d)(?:-?(\d))?/,gt),Ht=lt(/(\d{4})-?(\d{3})/,gt),Ut=lt(vt),Rt=ft(St,Tt,Mt),Pt=ft(pt,Tt,Mt),Wt=ft(wt,Tt),Jt=ft(Tt,Mt);var Yt=ft(Tt);var Gt=lt(/(\d{4})-(\d\d)-(\d\d)/,bt),$t=lt(kt),Bt=ft(St,Tt,Mt,Nt),Qt=ft(Tt,Mt,Nt);var Kt={weeks:{days:7,hours:168,minutes:10080,seconds:604800,milliseconds:6048e5},days:{hours:24,minutes:1440,seconds:86400,milliseconds:864e5},hours:{minutes:60,seconds:3600,milliseconds:36e5},minutes:{seconds:60,milliseconds:6e4},seconds:{milliseconds:1e3}},Xt=Object.assign({years:{quarters:4,months:12,weeks:52,days:365,hours:8760,minutes:525600,seconds:31536e3,milliseconds:31536e6},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:131040,seconds:7862400,milliseconds:78624e5},months:{weeks:4,days:30,hours:720,minutes:43200,seconds:2592e3,milliseconds:2592e6}},Kt),en=Object.assign({years:{quarters:4,months:12,weeks:52.1775,days:365.2425,hours:8765.82,minutes:525949.2,seconds:525949.2*60,milliseconds:525949.2*60*1e3},quarters:{months:3,weeks:13.044375,days:91.310625,hours:2191.455,minutes:131487.3,seconds:525949.2*60/4,milliseconds:7889237999.999999},months:{weeks:30.436875/7,days:30.436875,hours:730.485,minutes:43829.1,seconds:2629746,milliseconds:2629746e3}},Kt),tn=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],nn=tn.slice(0).reverse();function rn(e,t,n){void 0===n&&(n=!1);var r={values:n?t.values:Object.assign({},e.values,t.values||{}),loc:e.loc.clone(t.loc),conversionAccuracy:t.conversionAccuracy||e.conversionAccuracy};return new an(r)}function on(e,t,n,r,i){var o,a=e[i][n],u=t[n]/a,s=!(Math.sign(u)===Math.sign(r[i]))&&0!==r[i]&&Math.abs(u)<=1?(o=u)<0?Math.floor(o):Math.ceil(o):Math.trunc(u);r[i]+=s,t[n]-=s*a}var an=function(){function e(e){var t="longterm"===e.conversionAccuracy||!1;this.values=e.values,this.loc=e.loc||ct.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=t?en:Xt,this.isLuxonDuration=!0}e.fromMillis=function(t,n){return e.fromObject(Object.assign({milliseconds:t},n))},e.fromObject=function(t){if(null==t||"object"!=typeof t)throw new v("Duration.fromObject: argument expected to be an object, got "+(null===t?"null":typeof t));return new e({values:de(t,e.normalizeUnit,["locale","numberingSystem","conversionAccuracy","zone"]),loc:ct.fromObject(t),conversionAccuracy:t.conversionAccuracy})},e.fromISO=function(t,n){var r=dt(t,[Dt,It])[0];if(r){var i=Object.assign(r,n);return e.fromObject(i)}return e.invalid("unparsable",'the input "'+t+"\" can't be parsed as ISO 8601")},e.fromISOTime=function(t,n){var r=dt(t,[Et,Yt])[0];if(r){var i=Object.assign(r,n);return e.fromObject(i)}return e.invalid("unparsable",'the input "'+t+"\" can't be parsed as ISO 8601")},e.invalid=function(t,n){if(void 0===n&&(n=null),!t)throw new v("need to specify a reason the Duration is invalid");var r=t instanceof Ce?t:new Ce(t,n);if(Ke.throwOnInvalid)throw new h(r);return new e({invalid:r})},e.normalizeUnit=function(e){var t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e?e.toLowerCase():e];if(!t)throw new y(e);return t},e.isDuration=function(e){return e&&e.isLuxonDuration||!1};var t=e.prototype;return t.toFormat=function(e,t){void 0===t&&(t={});var n=Object.assign({},t,{floor:!1!==t.round&&!1!==t.floor});return this.isValid?xe.create(this.loc,n).formatDurationFromString(this,e):"Invalid Duration"},t.toObject=function(e){if(void 0===e&&(e={}),!this.isValid)return{};var t=Object.assign({},this.values);return e.includeConfig&&(t.conversionAccuracy=this.conversionAccuracy,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t},t.toISO=function(){if(!this.isValid)return null;var e="P";return 0!==this.years&&(e+=this.years+"Y"),0===this.months&&0===this.quarters||(e+=this.months+3*this.quarters+"M"),0!==this.weeks&&(e+=this.weeks+"W"),0!==this.days&&(e+=this.days+"D"),0===this.hours&&0===this.minutes&&0===this.seconds&&0===this.milliseconds||(e+="T"),0!==this.hours&&(e+=this.hours+"H"),0!==this.minutes&&(e+=this.minutes+"M"),0===this.seconds&&0===this.milliseconds||(e+=ne(this.seconds+this.milliseconds/1e3,3)+"S"),"P"===e&&(e+="T0S"),e},t.toISOTime=function(e){if(void 0===e&&(e={}),!this.isValid)return null;var t=this.toMillis();if(t<0||t>=864e5)return null;e=Object.assign({suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended"},e);var n=this.shiftTo("hours","minutes","seconds","milliseconds"),r="basic"===e.format?"hhmm":"hh:mm";e.suppressSeconds&&0===n.seconds&&0===n.milliseconds||(r+="basic"===e.format?"ss":":ss",e.suppressMilliseconds&&0===n.milliseconds||(r+=".SSS"));var i=n.toFormat(r);return e.includePrefix&&(i="T"+i),i},t.toJSON=function(){return this.toISO()},t.toString=function(){return this.toISO()},t.toMillis=function(){return this.as("milliseconds")},t.valueOf=function(){return this.toMillis()},t.plus=function(e){if(!this.isValid)return this;for(var t,n=un(e),r={},i=c(tn);!(t=i()).done;){var o=t.value;(Q(n.values,o)||Q(this.values,o))&&(r[o]=n.get(o)+this.get(o))}return rn(this,{values:r},!0)},t.minus=function(e){if(!this.isValid)return this;var t=un(e);return this.plus(t.negate())},t.mapUnits=function(e){if(!this.isValid)return this;for(var t={},n=0,r=Object.keys(this.values);n<r.length;n++){var i=r[n];t[i]=fe(e(this.values[i],i))}return rn(this,{values:t},!0)},t.get=function(t){return this[e.normalizeUnit(t)]},t.set=function(t){return this.isValid?rn(this,{values:Object.assign(this.values,de(t,e.normalizeUnit,[]))}):this},t.reconfigure=function(e){var t=void 0===e?{}:e,n=t.locale,r=t.numberingSystem,i=t.conversionAccuracy,o={loc:this.loc.clone({locale:n,numberingSystem:r})};return i&&(o.conversionAccuracy=i),rn(this,o)},t.as=function(e){return this.isValid?this.shiftTo(e).get(e):NaN},t.normalize=function(){if(!this.isValid)return this;var e=this.toObject();return function(e,t){nn.reduce(function(n,r){return R(t[r])?n:(n&&on(e,t,n,t,r),r)},null)}(this.matrix,e),rn(this,{values:e},!0)},t.shiftTo=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];if(!this.isValid)return this;if(0===n.length)return this;n=n.map(function(t){return e.normalizeUnit(t)});for(var i,o,a={},u={},s=this.toObject(),l=c(tn);!(o=l()).done;){var f=o.value;if(n.indexOf(f)>=0){i=f;var d=0;for(var h in u)d+=this.matrix[h][f]*u[h],u[h]=0;P(s[f])&&(d+=s[f]);var m=Math.trunc(d);for(var y in a[f]=m,u[f]=d-m,s)tn.indexOf(y)>tn.indexOf(f)&&on(this.matrix,s,y,a,f)}else P(s[f])&&(u[f]=s[f])}for(var v in u)0!==u[v]&&(a[i]+=v===i?u[v]:u[v]/this.matrix[i][v]);return rn(this,{values:a},!0).normalize()},t.negate=function(){if(!this.isValid)return this;for(var e={},t=0,n=Object.keys(this.values);t<n.length;t++){var r=n[t];e[r]=-this.values[r]}return rn(this,{values:e},!0)},t.equals=function(e){if(!this.isValid||!e.isValid)return!1;if(!this.loc.equals(e.loc))return!1;for(var t,n=c(tn);!(t=n()).done;){var r=t.value;if(i=this.values[r],o=e.values[r],!(void 0===i||0===i?void 0===o||0===o:i===o))return!1}var i,o;return!0},n(e,[{key:"locale",get:function(){return this.isValid?this.loc.locale:null}},{key:"numberingSystem",get:function(){return this.isValid?this.loc.numberingSystem:null}},{key:"years",get:function(){return this.isValid?this.values.years||0:NaN}},{key:"quarters",get:function(){return this.isValid?this.values.quarters||0:NaN}},{key:"months",get:function(){return this.isValid?this.values.months||0:NaN}},{key:"weeks",get:function(){return this.isValid?this.values.weeks||0:NaN}},{key:"days",get:function(){return this.isValid?this.values.days||0:NaN}},{key:"hours",get:function(){return this.isValid?this.values.hours||0:NaN}},{key:"minutes",get:function(){return this.isValid?this.values.minutes||0:NaN}},{key:"seconds",get:function(){return this.isValid?this.values.seconds||0:NaN}},{key:"milliseconds",get:function(){return this.isValid?this.values.milliseconds||0:NaN}},{key:"isValid",get:function(){return null===this.invalid}},{key:"invalidReason",get:function(){return this.invalid?this.invalid.reason:null}},{key:"invalidExplanation",get:function(){return this.invalid?this.invalid.explanation:null}}]),e}();function un(e){if(P(e))return an.fromMillis(e);if(an.isDuration(e))return e;if("object"==typeof e)return an.fromObject(e);throw new v("Unknown duration argument "+e+" of type "+typeof e)}var sn="Invalid Interval";function cn(e,t){return e&&e.isValid?t&&t.isValid?t<e?ln.invalid("end before start","The end of an interval must be after its start, but you had start="+e.toISO()+" and end="+t.toISO()):null:ln.invalid("missing or invalid end"):ln.invalid("missing or invalid start")}var ln=function(){function e(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}e.invalid=function(t,n){if(void 0===n&&(n=null),!t)throw new v("need to specify a reason the Interval is invalid");var r=t instanceof Ce?t:new Ce(t,n);if(Ke.throwOnInvalid)throw new d(r);return new e({invalid:r})},e.fromDateTimes=function(t,n){var r=cr(t),i=cr(n),o=cn(r,i);return null==o?new e({start:r,end:i}):o},e.after=function(t,n){var r=un(n),i=cr(t);return e.fromDateTimes(i,i.plus(r))},e.before=function(t,n){var r=un(n),i=cr(t);return e.fromDateTimes(i.minus(r),i)},e.fromISO=function(t,n){var r=(t||"").split("/",2),i=r[0],o=r[1];if(i&&o){var a,u,s,c;try{u=(a=sr.fromISO(i,n)).isValid}catch(o){u=!1}try{c=(s=sr.fromISO(o,n)).isValid}catch(o){c=!1}if(u&&c)return e.fromDateTimes(a,s);if(u){var l=an.fromISO(o,n);if(l.isValid)return e.after(a,l)}else if(c){var f=an.fromISO(i,n);if(f.isValid)return e.before(s,f)}}return e.invalid("unparsable",'the input "'+t+"\" can't be parsed as ISO 8601")},e.isInterval=function(e){return e&&e.isLuxonInterval||!1};var t=e.prototype;return t.length=function(e){return void 0===e&&(e="milliseconds"),this.isValid?this.toDuration.apply(this,[e]).get(e):NaN},t.count=function(e){if(void 0===e&&(e="milliseconds"),!this.isValid)return NaN;var t=this.start.startOf(e),n=this.end.startOf(e);return Math.floor(n.diff(t,e).get(e))+1},t.hasSame=function(e){return!!this.isValid&&(this.isEmpty()||this.e.minus(1).hasSame(this.s,e))},t.isEmpty=function(){return this.s.valueOf()===this.e.valueOf()},t.isAfter=function(e){return!!this.isValid&&this.s>e},t.isBefore=function(e){return!!this.isValid&&this.e<=e},t.contains=function(e){return!!this.isValid&&(this.s<=e&&this.e>e)},t.set=function(t){var n=void 0===t?{}:t,r=n.start,i=n.end;return this.isValid?e.fromDateTimes(r||this.s,i||this.e):this},t.splitAt=function(){var t=this;if(!this.isValid)return[];for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];for(var o=r.map(cr).filter(function(e){return t.contains(e)}).sort(),a=[],u=this.s,s=0;u<this.e;){var c=o[s]||this.e,l=+c>+this.e?this.e:c;a.push(e.fromDateTimes(u,l)),u=l,s+=1}return a},t.splitBy=function(t){var n=un(t);if(!this.isValid||!n.isValid||0===n.as("milliseconds"))return[];for(var r,i=this.s,o=1,a=[];i<this.e;){var u=this.start.plus(n.mapUnits(function(e){return e*o}));r=+u>+this.e?this.e:u,a.push(e.fromDateTimes(i,r)),i=r,o+=1}return a},t.divideEqually=function(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]},t.overlaps=function(e){return this.e>e.s&&this.s<e.e},t.abutsStart=function(e){return!!this.isValid&&+this.e==+e.s},t.abutsEnd=function(e){return!!this.isValid&&+e.e==+this.s},t.engulfs=function(e){return!!this.isValid&&(this.s<=e.s&&this.e>=e.e)},t.equals=function(e){return!(!this.isValid||!e.isValid)&&(this.s.equals(e.s)&&this.e.equals(e.e))},t.intersection=function(t){if(!this.isValid)return this;var n=this.s>t.s?this.s:t.s,r=this.e<t.e?this.e:t.e;return n>=r?null:e.fromDateTimes(n,r)},t.union=function(t){if(!this.isValid)return this;var n=this.s<t.s?this.s:t.s,r=this.e>t.e?this.e:t.e;return e.fromDateTimes(n,r)},e.merge=function(e){var t=e.sort(function(e,t){return e.s-t.s}).reduce(function(e,t){var n=e[0],r=e[1];return r?r.overlaps(t)||r.abutsStart(t)?[n,r.union(t)]:[n.concat([r]),t]:[n,t]},[[],null]),n=t[0],r=t[1];return r&&n.push(r),n},e.xor=function(t){for(var n,r,i=null,o=0,a=[],u=t.map(function(e){return[{time:e.s,type:"s"},{time:e.e,type:"e"}]}),s=c((n=Array.prototype).concat.apply(n,u).sort(function(e,t){return e.time-t.time}));!(r=s()).done;){var l=r.value;1===(o+="s"===l.type?1:-1)?i=l.time:(i&&+i!=+l.time&&a.push(e.fromDateTimes(i,l.time)),i=null)}return e.merge(a)},t.difference=function(){for(var t=this,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return e.xor([this].concat(r)).map(function(e){return t.intersection(e)}).filter(function(e){return e&&!e.isEmpty()})},t.toString=function(){return this.isValid?"["+this.s.toISO()+" – "+this.e.toISO()+")":sn},t.toISO=function(e){return this.isValid?this.s.toISO(e)+"/"+this.e.toISO(e):sn},t.toISODate=function(){return this.isValid?this.s.toISODate()+"/"+this.e.toISODate():sn},t.toISOTime=function(e){return this.isValid?this.s.toISOTime(e)+"/"+this.e.toISOTime(e):sn},t.toFormat=function(e,t){var n=(void 0===t?{}:t).separator,r=void 0===n?" – ":n;return this.isValid?""+this.s.toFormat(e)+r+this.e.toFormat(e):sn},t.toDuration=function(e,t){return this.isValid?this.e.diff(this.s,e,t):an.invalid(this.invalidReason)},t.mapEndpoints=function(t){return e.fromDateTimes(t(this.s),t(this.e))},n(e,[{key:"start",get:function(){return this.isValid?this.s:null}},{key:"end",get:function(){return this.isValid?this.e:null}},{key:"isValid",get:function(){return null===this.invalidReason}},{key:"invalidReason",get:function(){return this.invalid?this.invalid.reason:null}},{key:"invalidExplanation",get:function(){return this.invalid?this.invalid.explanation:null}}]),e}(),fn=function(){function e(){}return e.hasDST=function(e){void 0===e&&(e=Ke.defaultZone);var t=sr.now().setZone(e).set({month:12});return!e.universal&&t.offset!==t.set({month:6}).offset},e.isValidIANAZone=function(e){return He.isValidSpecifier(e)&&He.isValidZone(e)},e.normalizeZone=function(e){return We(e,Ke.defaultZone)},e.months=function(e,t){void 0===e&&(e="long");var n=void 0===t?{}:t,r=n.locale,i=void 0===r?null:r,o=n.numberingSystem,a=void 0===o?null:o,u=n.locObj,s=void 0===u?null:u,c=n.outputCalendar,l=void 0===c?"gregory":c;return(s||ct.create(i,a,l)).months(e)},e.monthsFormat=function(e,t){void 0===e&&(e="long");var n=void 0===t?{}:t,r=n.locale,i=void 0===r?null:r,o=n.numberingSystem,a=void 0===o?null:o,u=n.locObj,s=void 0===u?null:u,c=n.outputCalendar,l=void 0===c?"gregory":c;return(s||ct.create(i,a,l)).months(e,!0)},e.weekdays=function(e,t){void 0===e&&(e="long");var n=void 0===t?{}:t,r=n.locale,i=void 0===r?null:r,o=n.numberingSystem,a=void 0===o?null:o,u=n.locObj;return((void 0===u?null:u)||ct.create(i,a,null)).weekdays(e)},e.weekdaysFormat=function(e,t){void 0===e&&(e="long");var n=void 0===t?{}:t,r=n.locale,i=void 0===r?null:r,o=n.numberingSystem,a=void 0===o?null:o,u=n.locObj;return((void 0===u?null:u)||ct.create(i,a,null)).weekdays(e,!0)},e.meridiems=function(e){var t=(void 0===e?{}:e).locale,n=void 0===t?null:t;return ct.create(n).meridiems()},e.eras=function(e,t){void 0===e&&(e="short");var n=(void 0===t?{}:t).locale,r=void 0===n?null:n;return ct.create(r,null,"gregory").eras(e)},e.features=function(){var e=!1,t=!1,n=!1,r=!1;if(J()){e=!0,t=Y(),r=G();try{n="America/New_York"===new Intl.DateTimeFormat("en",{timeZone:"America/New_York"}).resolvedOptions().timeZone}catch(e){n=!1}}return{intl:e,intlTokens:t,zones:n,relative:r}},e}();function dn(e,t){var n=function(e){return e.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf()},r=n(t)-n(e);return Math.floor(an.fromMillis(r).as("days"))}function hn(e,t,n,r){var i=function(e,t,n){for(var r,i,o={},a=0,u=[["years",function(e,t){return t.year-e.year}],["quarters",function(e,t){return t.quarter-e.quarter}],["months",function(e,t){return t.month-e.month+12*(t.year-e.year)}],["weeks",function(e,t){var n=dn(e,t);return(n-n%7)/7}],["days",dn]];a<u.length;a++){var s=u[a],c=s[0],l=s[1];if(n.indexOf(c)>=0){var f;r=c;var d,h=l(e,t);(i=e.plus(((f={})[c]=h,f)))>t?(e=e.plus(((d={})[c]=h-1,d)),h-=1):e=i,o[c]=h}}return[e,o,i,r]}(e,t,n),o=i[0],a=i[1],u=i[2],s=i[3],c=t-o,l=n.filter(function(e){return["hours","minutes","seconds","milliseconds"].indexOf(e)>=0});if(0===l.length){var f;if(u<t)u=o.plus(((f={})[s]=1,f));u!==o&&(a[s]=(a[s]||0)+c/(u-o))}var d,h=an.fromObject(Object.assign(a,r));return l.length>0?(d=an.fromMillis(c,r)).shiftTo.apply(d,l).plus(h):h}var mn={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},yn={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},vn=mn.hanidec.replace(/[\[|\]]/g,"").split("");function gn(e,t){var n=e.numberingSystem;return void 0===t&&(t=""),new RegExp(""+mn[n||"latn"]+t)}var pn="missing Intl.DateTimeFormat.formatToParts support";function wn(e,t){return void 0===t&&(t=function(e){return e}),{regex:e,deser:function(e){var n=e[0];return t(function(e){var t=parseInt(e,10);if(isNaN(t)){t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(-1!==e[n].search(mn.hanidec))t+=vn.indexOf(e[n]);else for(var i in yn){var o=yn[i],a=o[0],u=o[1];r>=a&&r<=u&&(t+=r-a)}}return parseInt(t,10)}return t}(n))}}}var kn="( |"+String.fromCharCode(160)+")",bn=new RegExp(kn,"g");function On(e){return e.replace(/\./g,"\\.?").replace(bn,kn)}function Sn(e){return e.replace(/\./g,"").replace(bn," ").toLowerCase()}function Tn(e,t){return null===e?null:{regex:RegExp(e.map(On).join("|")),deser:function(n){var r=n[0];return e.findIndex(function(e){return Sn(r)===Sn(e)})+t}}}function Mn(e,t){return{regex:e,deser:function(e){return le(e[1],e[2])},groups:t}}function Nn(e){return{regex:e,deser:function(e){return e[0]}}}var En={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour:{numeric:"h","2-digit":"hh"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"}};var Dn=null;function In(e,t){if(e.literal)return e;var n=xe.macroTokenToFormatOpts(e.val);if(!n)return e;var r=xe.create(t,n).formatDateTimeParts((Dn||(Dn=sr.fromMillis(1555555555555)),Dn)).map(function(e){return function(e,t,n){var r=e.type,i=e.value;if("literal"===r)return{literal:!0,val:i};var o=n[r],a=En[r];return"object"==typeof a&&(a=a[o]),a?{literal:!1,val:a}:void 0}(e,0,n)});return r.includes(void 0)?e:r}function Vn(e,t,n){var r=function(e,t){var n;return(n=Array.prototype).concat.apply(n,e.map(function(e){return In(e,t)}))}(xe.parseFormat(n),e),i=r.map(function(t){return n=t,i=gn(r=e),o=gn(r,"{2}"),a=gn(r,"{3}"),u=gn(r,"{4}"),s=gn(r,"{6}"),c=gn(r,"{1,2}"),l=gn(r,"{1,3}"),f=gn(r,"{1,6}"),d=gn(r,"{1,9}"),h=gn(r,"{2,4}"),m=gn(r,"{4,6}"),y=function(e){return{regex:RegExp((t=e.val,t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"))),deser:function(e){return e[0]},literal:!0};var t},(v=function(e){if(n.literal)return y(e);switch(e.val){case"G":return Tn(r.eras("short",!1),0);case"GG":return Tn(r.eras("long",!1),0);case"y":return wn(f);case"yy":return wn(h,se);case"yyyy":return wn(u);case"yyyyy":return wn(m);case"yyyyyy":return wn(s);case"M":return wn(c);case"MM":return wn(o);case"MMM":return Tn(r.months("short",!0,!1),1);case"MMMM":return Tn(r.months("long",!0,!1),1);case"L":return wn(c);case"LL":return wn(o);case"LLL":return Tn(r.months("short",!1,!1),1);case"LLLL":return Tn(r.months("long",!1,!1),1);case"d":return wn(c);case"dd":return wn(o);case"o":return wn(l);case"ooo":return wn(a);case"HH":return wn(o);case"H":return wn(c);case"hh":return wn(o);case"h":return wn(c);case"mm":return wn(o);case"m":case"q":return wn(c);case"qq":return wn(o);case"s":return wn(c);case"ss":return wn(o);case"S":return wn(l);case"SSS":return wn(a);case"u":return Nn(d);case"a":return Tn(r.meridiems(),0);case"kkkk":return wn(u);case"kk":return wn(h,se);case"W":return wn(c);case"WW":return wn(o);case"E":case"c":return wn(i);case"EEE":return Tn(r.weekdays("short",!1,!1),1);case"EEEE":return Tn(r.weekdays("long",!1,!1),1);case"ccc":return Tn(r.weekdays("short",!0,!1),1);case"cccc":return Tn(r.weekdays("long",!0,!1),1);case"Z":case"ZZ":return Mn(new RegExp("([+-]"+c.source+")(?::("+o.source+"))?"),2);case"ZZZ":return Mn(new RegExp("([+-]"+c.source+")("+o.source+")?"),2);case"z":return Nn(/[a-z_+-/]{1,256}?/i);default:return y(e)}}(n)||{invalidReason:pn}).token=n,v;var n,r,i,o,a,u,s,c,l,f,d,h,m,y,v}),o=i.find(function(e){return e.invalidReason});if(o)return{input:t,tokens:r,invalidReason:o.invalidReason};var a=function(e){return["^"+e.map(function(e){return e.regex}).reduce(function(e,t){return e+"("+t.source+")"},"")+"$",e]}(i),u=a[0],s=a[1],c=RegExp(u,"i"),l=function(e,t,n){var r=e.match(t);if(r){var i={},o=1;for(var a in n)if(Q(n,a)){var u=n[a],s=u.groups?u.groups+1:1;!u.literal&&u.token&&(i[u.token.val[0]]=u.deser(r.slice(o,o+s))),o+=s}return[r,i]}return[r,{}]}(t,c,s),f=l[0],d=l[1],h=d?function(e){var t;return t=R(e.Z)?R(e.z)?null:He.create(e.z):new Re(e.Z),R(e.q)||(e.M=3*(e.q-1)+1),R(e.h)||(e.h<12&&1===e.a?e.h+=12:12===e.h&&0===e.a&&(e.h=0)),0===e.G&&e.y&&(e.y=-e.y),R(e.u)||(e.S=te(e.u)),[Object.keys(e).reduce(function(t,n){var r=function(e){switch(e){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}}(n);return r&&(t[r]=e[n]),t},{}),t]}(d):[null,null],y=h[0],v=h[1];if(Q(d,"a")&&Q(d,"H"))throw new m("Can't include meridiem when specifying 24-hour format");return{input:t,tokens:r,regex:c,rawMatches:f,matches:d,result:y,zone:v}}var Ln=[0,31,59,90,120,151,181,212,243,273,304,334],xn=[0,31,60,91,121,152,182,213,244,274,305,335];function Cn(e,t){return new Ce("unit out of range","you specified "+t+" (of type "+typeof t+") as a "+e+", which is invalid")}function Fn(e,t,n){var r=new Date(Date.UTC(e,t-1,n)).getUTCDay();return 0===r?7:r}function Zn(e,t,n){return n+(re(e)?xn:Ln)[t-1]}function jn(e,t){var n=re(e)?xn:Ln,r=n.findIndex(function(e){return e<t});return{month:r+1,day:t-n[r]}}function An(e){var t,n=e.year,r=e.month,i=e.day,o=Zn(n,r,i),a=Fn(n,r,i),u=Math.floor((o-a+10)/7);return u<1?u=ue(t=n-1):u>ue(n)?(t=n+1,u=1):t=n,Object.assign({weekYear:t,weekNumber:u,weekday:a},me(e))}function zn(e){var t,n=e.weekYear,r=e.weekNumber,i=e.weekday,o=Fn(n,1,4),a=ie(n),u=7*r+i-o-3;u<1?u+=ie(t=n-1):u>a?(t=n+1,u-=ie(n)):t=n;var s=jn(t,u),c=s.month,l=s.day;return Object.assign({year:t,month:c,day:l},me(e))}function _n(e){var t=e.year,n=Zn(t,e.month,e.day);return Object.assign({year:t,ordinal:n},me(e))}function qn(e){var t=e.year,n=jn(t,e.ordinal),r=n.month,i=n.day;return Object.assign({year:t,month:r,day:i},me(e))}function Hn(e){var t=W(e.year),n=K(e.month,1,12),r=K(e.day,1,oe(e.year,e.month));return t?n?!r&&Cn("day",e.day):Cn("month",e.month):Cn("year",e.year)}function Un(e){var t=e.hour,n=e.minute,r=e.second,i=e.millisecond,o=K(t,0,23)||24===t&&0===n&&0===r&&0===i,a=K(n,0,59),u=K(r,0,59),s=K(i,0,999);return o?a?u?!s&&Cn("millisecond",i):Cn("second",r):Cn("minute",n):Cn("hour",t)}function Rn(e){return new Ce("unsupported zone",'the zone "'+e.name+'" is not supported')}function Pn(e){return null===e.weekData&&(e.weekData=An(e.c)),e.weekData}function Wn(e,t){var n={ts:e.ts,zone:e.zone,c:e.c,o:e.o,loc:e.loc,invalid:e.invalid};return new sr(Object.assign({},n,t,{old:n}))}function Jn(e,t,n){var r=e-60*t*1e3,i=n.offset(r);if(t===i)return[r,t];r-=60*(i-t)*1e3;var o=n.offset(r);return i===o?[r,i]:[e-60*Math.min(i,o)*1e3,Math.max(i,o)]}function Yn(e,t){var n=new Date(e+=60*t*1e3);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function Gn(e,t,n){return Jn(ae(e),t,n)}function $n(e,t){var n=e.o,r=e.c.year+Math.trunc(t.years),i=e.c.month+Math.trunc(t.months)+3*Math.trunc(t.quarters),o=Object.assign({},e.c,{year:r,month:i,day:Math.min(e.c.day,oe(r,i))+Math.trunc(t.days)+7*Math.trunc(t.weeks)}),a=an.fromObject({years:t.years-Math.trunc(t.years),quarters:t.quarters-Math.trunc(t.quarters),months:t.months-Math.trunc(t.months),weeks:t.weeks-Math.trunc(t.weeks),days:t.days-Math.trunc(t.days),hours:t.hours,minutes:t.minutes,seconds:t.seconds,milliseconds:t.milliseconds}).as("milliseconds"),u=Jn(ae(o),n,e.zone),s=u[0],c=u[1];return 0!==a&&(s+=a,c=e.zone.offset(s)),{ts:s,o:c}}function Bn(e,t,n,r,i){var o=n.setZone,a=n.zone;if(e&&0!==Object.keys(e).length){var u=t||a,s=sr.fromObject(Object.assign(e,n,{zone:u,setZone:void 0}));return o?s:s.setZone(a)}return sr.invalid(new Ce("unparsable",'the input "'+i+"\" can't be parsed as "+r))}function Qn(e,t,n){return void 0===n&&(n=!0),e.isValid?xe.create(ct.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(e,t):null}function Kn(e,t){var n=t.suppressSeconds,r=void 0!==n&&n,i=t.suppressMilliseconds,o=void 0!==i&&i,a=t.includeOffset,u=t.includePrefix,s=void 0!==u&&u,c=t.includeZone,l=void 0!==c&&c,f=t.spaceZone,d=void 0!==f&&f,h=t.format,m=void 0===h?"extended":h,y="basic"===m?"HHmm":"HH:mm";r&&0===e.second&&0===e.millisecond||(y+="basic"===m?"ss":":ss",o&&0===e.millisecond||(y+=".SSS")),(l||a)&&d&&(y+=" "),l?y+="z":a&&(y+="basic"===m?"ZZZ":"ZZ");var v=Qn(e,y);return s&&(v="T"+v),v}var Xn={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},er={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},tr={ordinal:1,hour:0,minute:0,second:0,millisecond:0},nr=["year","month","day","hour","minute","second","millisecond"],rr=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],ir=["year","ordinal","hour","minute","second","millisecond"];function or(e){var t={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[e.toLowerCase()];if(!t)throw new y(e);return t}function ar(e,t){for(var n,r=c(nr);!(n=r()).done;){var i=n.value;R(e[i])&&(e[i]=Xn[i])}var o=Hn(e)||Un(e);if(o)return sr.invalid(o);var a=Ke.now(),u=Gn(e,t.offset(a),t),s=u[0],l=u[1];return new sr({ts:s,zone:t,o:l})}function ur(e,t,n){var r=!!R(n.round)||n.round,i=function(e,i){return e=ne(e,r||n.calendary?0:2,!0),t.loc.clone(n).relFormatter(n).format(e,i)},o=function(r){return n.calendary?t.hasSame(e,r)?0:t.startOf(r).diff(e.startOf(r),r).get(r):t.diff(e,r).get(r)};if(n.unit)return i(o(n.unit),n.unit);for(var a,u=c(n.units);!(a=u()).done;){var s=a.value,l=o(s);if(Math.abs(l)>=1)return i(l,s)}return i(e>t?-0:0,n.units[n.units.length-1])}var sr=function(){function e(e){var t=e.zone||Ke.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new Ce("invalid input"):null)||(t.isValid?null:Rn(t));this.ts=R(e.ts)?Ke.now():e.ts;var r=null,i=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t)){var o=[e.old.c,e.old.o];r=o[0],i=o[1]}else{var a=t.offset(this.ts);r=Yn(this.ts,a),r=(n=Number.isNaN(r.year)?new Ce("invalid input"):null)?null:r,i=n?null:a}this._zone=t,this.loc=e.loc||ct.create(),this.invalid=n,this.weekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}e.now=function(){return new e({})},e.local=function(t,n,r,i,o,a,u){return R(t)?e.now():ar({year:t,month:n,day:r,hour:i,minute:o,second:a,millisecond:u},Ke.defaultZone)},e.utc=function(t,n,r,i,o,a,u){return R(t)?new e({ts:Ke.now(),zone:Re.utcInstance}):ar({year:t,month:n,day:r,hour:i,minute:o,second:a,millisecond:u},Re.utcInstance)},e.fromJSDate=function(t,n){void 0===n&&(n={});var r,i=(r=t,"[object Date]"===Object.prototype.toString.call(r)?t.valueOf():NaN);if(Number.isNaN(i))return e.invalid("invalid input");var o=We(n.zone,Ke.defaultZone);return o.isValid?new e({ts:i,zone:o,loc:ct.fromObject(n)}):e.invalid(Rn(o))},e.fromMillis=function(t,n){if(void 0===n&&(n={}),P(t))return t<-864e13||t>864e13?e.invalid("Timestamp out of range"):new e({ts:t,zone:We(n.zone,Ke.defaultZone),loc:ct.fromObject(n)});throw new v("fromMillis requires a numerical input, but received a "+typeof t+" with value "+t)},e.fromSeconds=function(t,n){if(void 0===n&&(n={}),P(t))return new e({ts:1e3*t,zone:We(n.zone,Ke.defaultZone),loc:ct.fromObject(n)});throw new v("fromSeconds requires a numerical input")},e.fromObject=function(t){var n=We(t.zone,Ke.defaultZone);if(!n.isValid)return e.invalid(Rn(n));var r=Ke.now(),i=n.offset(r),o=de(t,or,["zone","locale","outputCalendar","numberingSystem"]),a=!R(o.ordinal),u=!R(o.year),s=!R(o.month)||!R(o.day),l=u||s,f=o.weekYear||o.weekNumber,d=ct.fromObject(t);if((l||a)&&f)throw new m("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(s&&a)throw new m("Can't mix ordinal dates with month/day");var h,y,v=f||o.weekday&&!l,g=Yn(r,i);v?(h=rr,y=er,g=An(g)):a?(h=ir,y=tr,g=_n(g)):(h=nr,y=Xn);for(var p,w=!1,k=c(h);!(p=k()).done;){var b=p.value;R(o[b])?o[b]=w?y[b]:g[b]:w=!0}var O=(v?function(e){var t=W(e.weekYear),n=K(e.weekNumber,1,ue(e.weekYear)),r=K(e.weekday,1,7);return t?n?!r&&Cn("weekday",e.weekday):Cn("week",e.week):Cn("weekYear",e.weekYear)}(o):a?function(e){var t=W(e.year),n=K(e.ordinal,1,ie(e.year));return t?!n&&Cn("ordinal",e.ordinal):Cn("year",e.year)}(o):Hn(o))||Un(o);if(O)return e.invalid(O);var S=Gn(v?zn(o):a?qn(o):o,i,n),T=new e({ts:S[0],zone:n,o:S[1],loc:d});return o.weekday&&l&&t.weekday!==T.weekday?e.invalid("mismatched weekday","you can't specify both a weekday of "+o.weekday+" and a date of "+T.toISO()):T},e.fromISO=function(e,t){void 0===t&&(t={});var n=dt(e,[_t,Rt],[qt,Pt],[Ht,Wt],[Ut,Jt]);return Bn(n[0],n[1],t,"ISO 8601",e)},e.fromRFC2822=function(e,t){void 0===t&&(t={});var n=dt(function(e){return e.replace(/\([^)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}(e),[xt,Ct]);return Bn(n[0],n[1],t,"RFC 2822",e)},e.fromHTTP=function(e,t){void 0===t&&(t={});var n=dt(e,[Ft,At],[Zt,At],[jt,zt]);return Bn(n[0],n[1],t,"HTTP",t)},e.fromFormat=function(t,n,r){if(void 0===r&&(r={}),R(t)||R(n))throw new v("fromFormat requires an input string and a format");var i=r,o=i.locale,a=void 0===o?null:o,u=i.numberingSystem,s=void 0===u?null:u,c=function(e,t,n){var r=Vn(e,t,n);return[r.result,r.zone,r.invalidReason]}(ct.fromOpts({locale:a,numberingSystem:s,defaultToEN:!0}),t,n),l=c[0],f=c[1],d=c[2];return d?e.invalid(d):Bn(l,f,r,"format "+n,t)},e.fromString=function(t,n,r){return void 0===r&&(r={}),e.fromFormat(t,n,r)},e.fromSQL=function(e,t){void 0===t&&(t={});var n=dt(e,[Gt,Bt],[$t,Qt]);return Bn(n[0],n[1],t,"SQL",e)},e.invalid=function(t,n){if(void 0===n&&(n=null),!t)throw new v("need to specify a reason the DateTime is invalid");var r=t instanceof Ce?t:new Ce(t,n);if(Ke.throwOnInvalid)throw new f(r);return new e({invalid:r})},e.isDateTime=function(e){return e&&e.isLuxonDateTime||!1};var t=e.prototype;return t.get=function(e){return this[e]},t.resolvedLocaleOpts=function(e){void 0===e&&(e={});var t=xe.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t.locale,numberingSystem:t.numberingSystem,outputCalendar:t.calendar}},t.toUTC=function(e,t){return void 0===e&&(e=0),void 0===t&&(t={}),this.setZone(Re.instance(e),t)},t.toLocal=function(){return this.setZone(Ke.defaultZone)},t.setZone=function(t,n){var r=void 0===n?{}:n,i=r.keepLocalTime,o=void 0!==i&&i,a=r.keepCalendarTime,u=void 0!==a&&a;if((t=We(t,Ke.defaultZone)).equals(this.zone))return this;if(t.isValid){var s=this.ts;if(o||u){var c=t.offset(this.ts);s=Gn(this.toObject(),c,t)[0]}return Wn(this,{ts:s,zone:t})}return e.invalid(Rn(t))},t.reconfigure=function(e){var t=void 0===e?{}:e,n=t.locale,r=t.numberingSystem,i=t.outputCalendar;return Wn(this,{loc:this.loc.clone({locale:n,numberingSystem:r,outputCalendar:i})})},t.setLocale=function(e){return this.reconfigure({locale:e})},t.set=function(e){if(!this.isValid)return this;var t,n=de(e,or,[]),r=!R(n.weekYear)||!R(n.weekNumber)||!R(n.weekday),i=!R(n.ordinal),o=!R(n.year),a=!R(n.month)||!R(n.day),u=o||a,s=n.weekYear||n.weekNumber;if((u||i)&&s)throw new m("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(a&&i)throw new m("Can't mix ordinal dates with month/day");r?t=zn(Object.assign(An(this.c),n)):R(n.ordinal)?(t=Object.assign(this.toObject(),n),R(n.day)&&(t.day=Math.min(oe(t.year,t.month),t.day))):t=qn(Object.assign(_n(this.c),n));var c=Gn(t,this.o,this.zone);return Wn(this,{ts:c[0],o:c[1]})},t.plus=function(e){return this.isValid?Wn(this,$n(this,un(e))):this},t.minus=function(e){return this.isValid?Wn(this,$n(this,un(e).negate())):this},t.startOf=function(e){if(!this.isValid)return this;var t={},n=an.normalizeUnit(e);switch(n){case"years":t.month=1;case"quarters":case"months":t.day=1;case"weeks":case"days":t.hour=0;case"hours":t.minute=0;case"minutes":t.second=0;case"seconds":t.millisecond=0}if("weeks"===n&&(t.weekday=1),"quarters"===n){var r=Math.ceil(this.month/3);t.month=3*(r-1)+1}return this.set(t)},t.endOf=function(e){var t;return this.isValid?this.plus((t={},t[e]=1,t)).startOf(e).minus(1):this},t.toFormat=function(e,t){return void 0===t&&(t={}),this.isValid?xe.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):"Invalid DateTime"},t.toLocaleString=function(e){return void 0===e&&(e=b),this.isValid?xe.create(this.loc.clone(e),e).formatDateTime(this):"Invalid DateTime"},t.toLocaleParts=function(e){return void 0===e&&(e={}),this.isValid?xe.create(this.loc.clone(e),e).formatDateTimeParts(this):[]},t.toISO=function(e){return void 0===e&&(e={}),this.isValid?this.toISODate(e)+"T"+this.toISOTime(e):null},t.toISODate=function(e){var t=(void 0===e?{}:e).format,n="basic"===(void 0===t?"extended":t)?"yyyyMMdd":"yyyy-MM-dd";return this.year>9999&&(n="+"+n),Qn(this,n)},t.toISOWeekDate=function(){return Qn(this,"kkkk-'W'WW-c")},t.toISOTime=function(e){var t=void 0===e?{}:e,n=t.suppressMilliseconds,r=void 0!==n&&n,i=t.suppressSeconds,o=void 0!==i&&i,a=t.includeOffset,u=void 0===a||a,s=t.includePrefix,c=void 0!==s&&s,l=t.format;return Kn(this,{suppressSeconds:o,suppressMilliseconds:r,includeOffset:u,includePrefix:c,format:void 0===l?"extended":l})},t.toRFC2822=function(){return Qn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)},t.toHTTP=function(){return Qn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")},t.toSQLDate=function(){return Qn(this,"yyyy-MM-dd")},t.toSQLTime=function(e){var t=void 0===e?{}:e,n=t.includeOffset,r=void 0===n||n,i=t.includeZone;return Kn(this,{includeOffset:r,includeZone:void 0!==i&&i,spaceZone:!0})},t.toSQL=function(e){return void 0===e&&(e={}),this.isValid?this.toSQLDate()+" "+this.toSQLTime(e):null},t.toString=function(){return this.isValid?this.toISO():"Invalid DateTime"},t.valueOf=function(){return this.toMillis()},t.toMillis=function(){return this.isValid?this.ts:NaN},t.toSeconds=function(){return this.isValid?this.ts/1e3:NaN},t.toJSON=function(){return this.toISO()},t.toBSON=function(){return this.toJSDate()},t.toObject=function(e){if(void 0===e&&(e={}),!this.isValid)return{};var t=Object.assign({},this.c);return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t},t.toJSDate=function(){return new Date(this.isValid?this.ts:NaN)},t.diff=function(e,t,n){if(void 0===t&&(t="milliseconds"),void 0===n&&(n={}),!this.isValid||!e.isValid)return an.invalid(this.invalid||e.invalid,"created by diffing an invalid DateTime");var r,i=Object.assign({locale:this.locale,numberingSystem:this.numberingSystem},n),o=(r=t,Array.isArray(r)?r:[r]).map(an.normalizeUnit),a=e.valueOf()>this.valueOf(),u=hn(a?this:e,a?e:this,o,i);return a?u.negate():u},t.diffNow=function(t,n){return void 0===t&&(t="milliseconds"),void 0===n&&(n={}),this.diff(e.now(),t,n)},t.until=function(e){return this.isValid?ln.fromDateTimes(this,e):this},t.hasSame=function(e,t){if(!this.isValid)return!1;var n=e.valueOf(),r=this.setZone(e.zone,{keepLocalTime:!0});return r.startOf(t)<=n&&n<=r.endOf(t)},t.equals=function(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)},t.toRelative=function(t){if(void 0===t&&(t={}),!this.isValid)return null;var n=t.base||e.fromObject({zone:this.zone}),r=t.padding?this<n?-t.padding:t.padding:0,i=["years","months","days","hours","minutes","seconds"],o=t.unit;return Array.isArray(t.unit)&&(i=t.unit,o=void 0),ur(n,this.plus(r),Object.assign(t,{numeric:"always",units:i,unit:o}))},t.toRelativeCalendar=function(t){return void 0===t&&(t={}),this.isValid?ur(t.base||e.fromObject({zone:this.zone}),this,Object.assign(t,{numeric:"auto",units:["years","months","days"],calendary:!0})):null},e.min=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];if(!n.every(e.isDateTime))throw new v("min requires all arguments be DateTimes");return $(n,function(e){return e.valueOf()},Math.min)},e.max=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];if(!n.every(e.isDateTime))throw new v("max requires all arguments be DateTimes");return $(n,function(e){return e.valueOf()},Math.max)},e.fromFormatExplain=function(e,t,n){void 0===n&&(n={});var r=n,i=r.locale,o=void 0===i?null:i,a=r.numberingSystem,u=void 0===a?null:a;return Vn(ct.fromOpts({locale:o,numberingSystem:u,defaultToEN:!0}),e,t)},e.fromStringExplain=function(t,n,r){return void 0===r&&(r={}),e.fromFormatExplain(t,n,r)},n(e,[{key:"isValid",get:function(){return null===this.invalid}},{key:"invalidReason",get:function(){return this.invalid?this.invalid.reason:null}},{key:"invalidExplanation",get:function(){return this.invalid?this.invalid.explanation:null}},{key:"locale",get:function(){return this.isValid?this.loc.locale:null}},{key:"numberingSystem",get:function(){return this.isValid?this.loc.numberingSystem:null}},{key:"outputCalendar",get:function(){return this.isValid?this.loc.outputCalendar:null}},{key:"zone",get:function(){return this._zone}},{key:"zoneName",get:function(){return this.isValid?this.zone.name:null}},{key:"year",get:function(){return this.isValid?this.c.year:NaN}},{key:"quarter",get:function(){return this.isValid?Math.ceil(this.c.month/3):NaN}},{key:"month",get:function(){return this.isValid?this.c.month:NaN}},{key:"day",get:function(){return this.isValid?this.c.day:NaN}},{key:"hour",get:function(){return this.isValid?this.c.hour:NaN}},{key:"minute",get:function(){return this.isValid?this.c.minute:NaN}},{key:"second",get:function(){return this.isValid?this.c.second:NaN}},{key:"millisecond",get:function(){return this.isValid?this.c.millisecond:NaN}},{key:"weekYear",get:function(){return this.isValid?Pn(this).weekYear:NaN}},{key:"weekNumber",get:function(){return this.isValid?Pn(this).weekNumber:NaN}},{key:"weekday",get:function(){return this.isValid?Pn(this).weekday:NaN}},{key:"ordinal",get:function(){return this.isValid?_n(this.c).ordinal:NaN}},{key:"monthShort",get:function(){return this.isValid?fn.months("short",{locObj:this.loc})[this.month-1]:null}},{key:"monthLong",get:function(){return this.isValid?fn.months("long",{locObj:this.loc})[this.month-1]:null}},{key:"weekdayShort",get:function(){return this.isValid?fn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}},{key:"weekdayLong",get:function(){return this.isValid?fn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}},{key:"offset",get:function(){return this.isValid?+this.o:NaN}},{key:"offsetNameShort",get:function(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}},{key:"offsetNameLong",get:function(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}},{key:"isOffsetFixed",get:function(){return this.isValid?this.zone.universal:null}},{key:"isInDST",get:function(){return!this.isOffsetFixed&&(this.offset>this.set({month:1}).offset||this.offset>this.set({month:5}).offset)}},{key:"isInLeapYear",get:function(){return re(this.year)}},{key:"daysInMonth",get:function(){return oe(this.year,this.month)}},{key:"daysInYear",get:function(){return this.isValid?ie(this.year):NaN}},{key:"weeksInWeekYear",get:function(){return this.isValid?ue(this.weekYear):NaN}}],[{key:"DATE_SHORT",get:function(){return b}},{key:"DATE_MED",get:function(){return O}},{key:"DATE_MED_WITH_WEEKDAY",get:function(){return S}},{key:"DATE_FULL",get:function(){return T}},{key:"DATE_HUGE",get:function(){return M}},{key:"TIME_SIMPLE",get:function(){return N}},{key:"TIME_WITH_SECONDS",get:function(){return E}},{key:"TIME_WITH_SHORT_OFFSET",get:function(){return D}},{key:"TIME_WITH_LONG_OFFSET",get:function(){return I}},{key:"TIME_24_SIMPLE",get:function(){return V}},{key:"TIME_24_WITH_SECONDS",get:function(){return L}},{key:"TIME_24_WITH_SHORT_OFFSET",get:function(){return x}},{key:"TIME_24_WITH_LONG_OFFSET",get:function(){return C}},{key:"DATETIME_SHORT",get:function(){return F}},{key:"DATETIME_SHORT_WITH_SECONDS",get:function(){return Z}},{key:"DATETIME_MED",get:function(){return j}},{key:"DATETIME_MED_WITH_SECONDS",get:function(){return A}},{key:"DATETIME_MED_WITH_WEEKDAY",get:function(){return z}},{key:"DATETIME_FULL",get:function(){return _}},{key:"DATETIME_FULL_WITH_SECONDS",get:function(){return q}},{key:"DATETIME_HUGE",get:function(){return H}},{key:"DATETIME_HUGE_WITH_SECONDS",get:function(){return U}}]),e}();function cr(e){if(sr.isDateTime(e))return e;if(e&&e.valueOf&&P(e.valueOf()))return sr.fromJSDate(e);if(e&&"object"==typeof e)return sr.fromObject(e);throw new v("Unknown datetime argument: "+e+", of type "+typeof e)}return e.DateTime=sr,e.Duration=an,e.FixedOffsetZone=Re,e.IANAZone=He,e.Info=fn,e.Interval=ln,e.InvalidZone=Pe,e.LocalZone=je,e.Settings=Ke,e.VERSION="1.27.0",e.Zone=Fe,e}({});
\ No newline at end of file
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Copyright 2019 JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "luxon",
"version": "1.27.0",
"description": "Immutable date wrapper",
"author": "Isaac Cambron",
"keywords": [
"date",
"immutable"
],
"repository": "https://github.com/moment/luxon",
"scripts": {
"build": "babel-node tasks/buildAll.js",
"build-node": "babel-node tasks/buildNode.js",
"build-global": "babel-node tasks/buildGlobal.js",
"jest": "jest",
"test": "jest --coverage",
"docs": "esdoc -c docs/index.js",
"site": "cp -r site/** build/",
"lint": "eslint --quiet src test benchmarks",
"lint!": "npm run format && npm run lint",
"format": "prettier --write 'src/**/*.js' 'test/**/*.js' 'benchmarks/*.js'",
"benchmark": "babel-node benchmarks/index.js",
"codecov": "codecov",
"check-doc-coverage": "babel-node tasks/docCoverage"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,json}": [
"prettier --write"
]
},
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/node": "^7.8.7",
"@babel/plugin-external-helpers": "^7.8.3",
"@babel/preset-env": "^7.9.5",
"@rollup/plugin-commonjs": "^11.1.0",
"@rollup/plugin-node-resolve": "^7.1.3",
"babel-core": "^7.0.0-bridge.0",
"babel-eslint": "latest",
"babel-jest": "^25.3.0",
"benchmark": "latest",
"codecov": ">= 3.6.5",
"core-js": "^3.6.5",
"esdoc": "^1.1.0",
"esdoc-standard-plugin": "latest",
"eslint": "6.4.0",
"eslint-config-defaults": "latest",
"eslint-config-prettier": "6.3.0",
"eslint-config-standard": "^14.1.1",
"eslint-plugin-babel": "latest",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-node": "10.0.0",
"eslint-plugin-prettier": "3.1.1",
"eslint-plugin-promise": "latest",
"eslint-plugin-react": "^7.19.0",
"eslint-plugin-standard": "^4.0.1",
"fs-extra": "^6.0.1",
"full-icu": "^1.3.1",
"husky": "^4.2.5",
"jest": "^25.3.0",
"lint-staged": "^10.1.3",
"prettier": "1.14.3",
"rollup": "^1.32.1",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-babel-minify": "^6.2.0",
"uglify-es": "^3.3.9"
},
"main": "build/node/luxon.js",
"module": "src/luxon.js",
"browser": "build/cjs-browser/luxon.js",
"jsdelivr": "build/global/luxon.min.js",
"unpkg": "build/global/luxon.min.js",
"engines": {
"node": "*"
},
"files": [
"build/node/luxon.js",
"build/node/luxon.js.map",
"build/cjs-browser/luxon.js",
"build/cjs-browser/luxon.js.map",
"build/amd/luxon.js",
"build/amd/luxon.js.map",
"build/global/luxon.js",
"build/global/luxon.js.map",
"build/global/luxon.min.js",
"build/global/luxon.min.js.map",
"src"
],
"license": "MIT",
"sideEffects": false
}
import Duration, { friendlyDuration } from "./duration.js";
import Interval from "./interval.js";
import Settings from "./settings.js";
import Info from "./info.js";
import Formatter from "./impl/formatter.js";
import FixedOffsetZone from "./zones/fixedOffsetZone.js";
import Locale from "./impl/locale.js";
import {
isUndefined,
maybeArray,
isDate,
isNumber,
bestBy,
daysInMonth,
daysInYear,
isLeapYear,
weeksInWeekYear,
normalizeObject,
roundTo,
objToLocalTS
} from "./impl/util.js";
import { normalizeZone } from "./impl/zoneUtil.js";
import diff from "./impl/diff.js";
import { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from "./impl/regexParser.js";
import { parseFromTokens, explainFromTokens } from "./impl/tokenParser.js";
import {
gregorianToWeek,
weekToGregorian,
gregorianToOrdinal,
ordinalToGregorian,
hasInvalidGregorianData,
hasInvalidWeekData,
hasInvalidOrdinalData,
hasInvalidTimeData
} from "./impl/conversions.js";
import * as Formats from "./impl/formats.js";
import {
InvalidArgumentError,
ConflictingSpecificationError,
InvalidUnitError,
InvalidDateTimeError
} from "./errors.js";
import Invalid from "./impl/invalid.js";
const INVALID = "Invalid DateTime";
const MAX_DATE = 8.64e15;
function unsupportedZone(zone) {
return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`);
}
// we cache week data on the DT object and this intermediates the cache
function possiblyCachedWeekData(dt) {
if (dt.weekData === null) {
dt.weekData = gregorianToWeek(dt.c);
}
return dt.weekData;
}
// clone really means, "make a new object with these modifications". all "setters" really use this
// to create a new object while only changing some of the properties
function clone(inst, alts) {
const current = {
ts: inst.ts,
zone: inst.zone,
c: inst.c,
o: inst.o,
loc: inst.loc,
invalid: inst.invalid
};
return new DateTime(Object.assign({}, current, alts, { old: current }));
}
// find the right offset a given local time. The o input is our guess, which determines which
// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)
function fixOffset(localTS, o, tz) {
// Our UTC time is just a guess because our offset is just a guess
let utcGuess = localTS - o * 60 * 1000;
// Test whether the zone matches the offset for this ts
const o2 = tz.offset(utcGuess);
// If so, offset didn't change and we're done
if (o === o2) {
return [utcGuess, o];
}
// If not, change the ts by the difference in the offset
utcGuess -= (o2 - o) * 60 * 1000;
// If that gives us the local time we want, we're done
const o3 = tz.offset(utcGuess);
if (o2 === o3) {
return [utcGuess, o2];
}
// If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time
return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];
}
// convert an epoch timestamp into a calendar object with the given offset
function tsToObj(ts, offset) {
ts += offset * 60 * 1000;
const d = new Date(ts);
return {
year: d.getUTCFullYear(),
month: d.getUTCMonth() + 1,
day: d.getUTCDate(),
hour: d.getUTCHours(),
minute: d.getUTCMinutes(),
second: d.getUTCSeconds(),
millisecond: d.getUTCMilliseconds()
};
}
// convert a calendar object to a epoch timestamp
function objToTS(obj, offset, zone) {
return fixOffset(objToLocalTS(obj), offset, zone);
}
// create a new DT instance by adding a duration, adjusting for DSTs
function adjustTime(inst, dur) {
const oPre = inst.o,
year = inst.c.year + Math.trunc(dur.years),
month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,
c = Object.assign({}, inst.c, {
year,
month,
day:
Math.min(inst.c.day, daysInMonth(year, month)) +
Math.trunc(dur.days) +
Math.trunc(dur.weeks) * 7
}),
millisToAdd = Duration.fromObject({
years: dur.years - Math.trunc(dur.years),
quarters: dur.quarters - Math.trunc(dur.quarters),
months: dur.months - Math.trunc(dur.months),
weeks: dur.weeks - Math.trunc(dur.weeks),
days: dur.days - Math.trunc(dur.days),
hours: dur.hours,
minutes: dur.minutes,
seconds: dur.seconds,
milliseconds: dur.milliseconds
}).as("milliseconds"),
localTS = objToLocalTS(c);
let [ts, o] = fixOffset(localTS, oPre, inst.zone);
if (millisToAdd !== 0) {
ts += millisToAdd;
// that could have changed the offset by going over a DST, but we want to keep the ts the same
o = inst.zone.offset(ts);
}
return { ts, o };
}
// helper useful in turning the results of parsing into real dates
// by handling the zone options
function parseDataToDateTime(parsed, parsedZone, opts, format, text) {
const { setZone, zone } = opts;
if (parsed && Object.keys(parsed).length !== 0) {
const interpretationZone = parsedZone || zone,
inst = DateTime.fromObject(
Object.assign(parsed, opts, {
zone: interpretationZone,
// setZone is a valid option in the calling methods, but not in fromObject
setZone: undefined
})
);
return setZone ? inst : inst.setZone(zone);
} else {
return DateTime.invalid(
new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`)
);
}
}
// if you want to output a technical format (e.g. RFC 2822), this helper
// helps handle the details
function toTechFormat(dt, format, allowZ = true) {
return dt.isValid
? Formatter.create(Locale.create("en-US"), {
allowZ,
forceSimple: true
}).formatDateTimeFromString(dt, format)
: null;
}
// technical time formats (e.g. the time part of ISO 8601), take some options
// and this commonizes their handling
function toTechTimeFormat(
dt,
{
suppressSeconds = false,
suppressMilliseconds = false,
includeOffset,
includePrefix = false,
includeZone = false,
spaceZone = false,
format = "extended"
}
) {
let fmt = format === "basic" ? "HHmm" : "HH:mm";
if (!suppressSeconds || dt.second !== 0 || dt.millisecond !== 0) {
fmt += format === "basic" ? "ss" : ":ss";
if (!suppressMilliseconds || dt.millisecond !== 0) {
fmt += ".SSS";
}
}
if ((includeZone || includeOffset) && spaceZone) {
fmt += " ";
}
if (includeZone) {
fmt += "z";
} else if (includeOffset) {
fmt += format === "basic" ? "ZZZ" : "ZZ";
}
let str = toTechFormat(dt, fmt);
if (includePrefix) {
str = "T" + str;
}
return str;
}
// defaults for unspecified units in the supported calendars
const defaultUnitValues = {
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
},
defaultWeekUnitValues = {
weekNumber: 1,
weekday: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
},
defaultOrdinalUnitValues = {
ordinal: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
};
// Units in the supported calendars, sorted by bigness
const orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"],
orderedWeekUnits = [
"weekYear",
"weekNumber",
"weekday",
"hour",
"minute",
"second",
"millisecond"
],
orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
// standardize case and plurality in units
function normalizeUnit(unit) {
const normalized = {
year: "year",
years: "year",
month: "month",
months: "month",
day: "day",
days: "day",
hour: "hour",
hours: "hour",
minute: "minute",
minutes: "minute",
quarter: "quarter",
quarters: "quarter",
second: "second",
seconds: "second",
millisecond: "millisecond",
milliseconds: "millisecond",
weekday: "weekday",
weekdays: "weekday",
weeknumber: "weekNumber",
weeksnumber: "weekNumber",
weeknumbers: "weekNumber",
weekyear: "weekYear",
weekyears: "weekYear",
ordinal: "ordinal"
}[unit.toLowerCase()];
if (!normalized) throw new InvalidUnitError(unit);
return normalized;
}
// this is a dumbed down version of fromObject() that runs about 60% faster
// but doesn't do any validation, makes a bunch of assumptions about what units
// are present, and so on.
function quickDT(obj, zone) {
// assume we have the higher-order units
for (const u of orderedUnits) {
if (isUndefined(obj[u])) {
obj[u] = defaultUnitValues[u];
}
}
const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
if (invalid) {
return DateTime.invalid(invalid);
}
const tsNow = Settings.now(),
offsetProvis = zone.offset(tsNow),
[ts, o] = objToTS(obj, offsetProvis, zone);
return new DateTime({
ts,
zone,
o
});
}
function diffRelative(start, end, opts) {
const round = isUndefined(opts.round) ? true : opts.round,
format = (c, unit) => {
c = roundTo(c, round || opts.calendary ? 0 : 2, true);
const formatter = end.loc.clone(opts).relFormatter(opts);
return formatter.format(c, unit);
},
differ = unit => {
if (opts.calendary) {
if (!end.hasSame(start, unit)) {
return end
.startOf(unit)
.diff(start.startOf(unit), unit)
.get(unit);
} else return 0;
} else {
return end.diff(start, unit).get(unit);
}
};
if (opts.unit) {
return format(differ(opts.unit), opts.unit);
}
for (const unit of opts.units) {
const count = differ(unit);
if (Math.abs(count) >= 1) {
return format(count, unit);
}
}
return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
}
/**
* A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.
*
* A DateTime comprises of:
* * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.
* * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).
* * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.
*
* Here is a brief overview of the most commonly used functionality it provides:
*
* * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link local}, {@link utc}, and (most flexibly) {@link fromObject}. To create one from a standard string format, use {@link fromISO}, {@link fromHTTP}, and {@link fromRFC2822}. To create one from a custom string format, use {@link fromFormat}. To create one from a native JS date, use {@link fromJSDate}.
* * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link toObject}), use the {@link year}, {@link month},
* {@link day}, {@link hour}, {@link minute}, {@link second}, {@link millisecond} accessors.
* * **Week calendar**: For ISO week calendar attributes, see the {@link weekYear}, {@link weekNumber}, and {@link weekday} accessors.
* * **Configuration** See the {@link locale} and {@link numberingSystem} accessors.
* * **Transformation**: To transform the DateTime into other DateTimes, use {@link set}, {@link reconfigure}, {@link setZone}, {@link setLocale}, {@link plus}, {@link minus}, {@link endOf}, {@link startOf}, {@link toUTC}, and {@link toLocal}.
* * **Output**: To convert the DateTime to other representations, use the {@link toRelative}, {@link toRelativeCalendar}, {@link toJSON}, {@link toISO}, {@link toHTTP}, {@link toObject}, {@link toRFC2822}, {@link toString}, {@link toLocaleString}, {@link toFormat}, {@link toMillis} and {@link toJSDate}.
*
* There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.
*/
export default class DateTime {
/**
* @access private
*/
constructor(config) {
const zone = config.zone || Settings.defaultZone;
let invalid =
config.invalid ||
(Number.isNaN(config.ts) ? new Invalid("invalid input") : null) ||
(!zone.isValid ? unsupportedZone(zone) : null);
/**
* @access private
*/
this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
let c = null,
o = null;
if (!invalid) {
const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
if (unchanged) {
[c, o] = [config.old.c, config.old.o];
} else {
const ot = zone.offset(this.ts);
c = tsToObj(this.ts, ot);
invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
c = invalid ? null : c;
o = invalid ? null : ot;
}
}
/**
* @access private
*/
this._zone = zone;
/**
* @access private
*/
this.loc = config.loc || Locale.create();
/**
* @access private
*/
this.invalid = invalid;
/**
* @access private
*/
this.weekData = null;
/**
* @access private
*/
this.c = c;
/**
* @access private
*/
this.o = o;
/**
* @access private
*/
this.isLuxonDateTime = true;
}
// CONSTRUCT
/**
* Create a DateTime for the current instant, in the system's time zone.
*
* Use Settings to override these default values if needed.
* @example DateTime.now().toISO() //~> now in the ISO format
* @return {DateTime}
*/
static now() {
return new DateTime({});
}
/**
* Create a local DateTime
* @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
* @param {number} [month=1] - The month, 1-indexed
* @param {number} [day=1] - The day of the month, 1-indexed
* @param {number} [hour=0] - The hour of the day, in 24-hour time
* @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
* @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
* @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
* @example DateTime.local() //~> now
* @example DateTime.local(2017) //~> 2017-01-01T00:00:00
* @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00
* @example DateTime.local(2017, 3, 12) //~> 2017-03-12T00:00:00
* @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00
* @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00
* @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10
* @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765
* @return {DateTime}
*/
static local(year, month, day, hour, minute, second, millisecond) {
if (isUndefined(year)) {
return DateTime.now();
} else {
return quickDT(
{
year,
month,
day,
hour,
minute,
second,
millisecond
},
Settings.defaultZone
);
}
}
/**
* Create a DateTime in UTC
* @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
* @param {number} [month=1] - The month, 1-indexed
* @param {number} [day=1] - The day of the month
* @param {number} [hour=0] - The hour of the day, in 24-hour time
* @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
* @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
* @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
* @example DateTime.utc() //~> now
* @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z
* @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z
* @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z
* @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z
* @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z
* @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z
* @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765Z
* @return {DateTime}
*/
static utc(year, month, day, hour, minute, second, millisecond) {
if (isUndefined(year)) {
return new DateTime({
ts: Settings.now(),
zone: FixedOffsetZone.utcInstance
});
} else {
return quickDT(
{
year,
month,
day,
hour,
minute,
second,
millisecond
},
FixedOffsetZone.utcInstance
);
}
}
/**
* Create a DateTime from a JavaScript Date object. Uses the default zone.
* @param {Date} date - a JavaScript Date object
* @param {Object} options - configuration options for the DateTime
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
* @return {DateTime}
*/
static fromJSDate(date, options = {}) {
const ts = isDate(date) ? date.valueOf() : NaN;
if (Number.isNaN(ts)) {
return DateTime.invalid("invalid input");
}
const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
if (!zoneToUse.isValid) {
return DateTime.invalid(unsupportedZone(zoneToUse));
}
return new DateTime({
ts: ts,
zone: zoneToUse,
loc: Locale.fromObject(options)
});
}
/**
* Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
* @param {number} milliseconds - a number of milliseconds since 1970 UTC
* @param {Object} options - configuration options for the DateTime
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
* @param {string} [options.locale] - a locale to set on the resulting DateTime instance
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
* @return {DateTime}
*/
static fromMillis(milliseconds, options = {}) {
if (!isNumber(milliseconds)) {
throw new InvalidArgumentError(
`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`
);
} else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
// this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start
return DateTime.invalid("Timestamp out of range");
} else {
return new DateTime({
ts: milliseconds,
zone: normalizeZone(options.zone, Settings.defaultZone),
loc: Locale.fromObject(options)
});
}
}
/**
* Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
* @param {number} seconds - a number of seconds since 1970 UTC
* @param {Object} options - configuration options for the DateTime
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
* @param {string} [options.locale] - a locale to set on the resulting DateTime instance
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
* @return {DateTime}
*/
static fromSeconds(seconds, options = {}) {
if (!isNumber(seconds)) {
throw new InvalidArgumentError("fromSeconds requires a numerical input");
} else {
return new DateTime({
ts: seconds * 1000,
zone: normalizeZone(options.zone, Settings.defaultZone),
loc: Locale.fromObject(options)
});
}
}
/**
* Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
* @param {Object} obj - the object to create the DateTime from
* @param {number} obj.year - a year, such as 1987
* @param {number} obj.month - a month, 1-12
* @param {number} obj.day - a day of the month, 1-31, depending on the month
* @param {number} obj.ordinal - day of the year, 1-365 or 366
* @param {number} obj.weekYear - an ISO week year
* @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
* @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
* @param {number} obj.hour - hour of the day, 0-23
* @param {number} obj.minute - minute of the hour, 0-59
* @param {number} obj.second - second of the minute, 0-59
* @param {number} obj.millisecond - millisecond of the second, 0-999
* @param {string|Zone} [obj.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
* @param {string} [obj.locale='system's locale'] - a locale to set on the resulting DateTime instance
* @param {string} obj.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} obj.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
* @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'utc' }),
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'local' })
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'America/New_York' })
* @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
* @return {DateTime}
*/
static fromObject(obj) {
const zoneToUse = normalizeZone(obj.zone, Settings.defaultZone);
if (!zoneToUse.isValid) {
return DateTime.invalid(unsupportedZone(zoneToUse));
}
const tsNow = Settings.now(),
offsetProvis = zoneToUse.offset(tsNow),
normalized = normalizeObject(obj, normalizeUnit, [
"zone",
"locale",
"outputCalendar",
"numberingSystem"
]),
containsOrdinal = !isUndefined(normalized.ordinal),
containsGregorYear = !isUndefined(normalized.year),
containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
containsGregor = containsGregorYear || containsGregorMD,
definiteWeekDef = normalized.weekYear || normalized.weekNumber,
loc = Locale.fromObject(obj);
// cases:
// just a weekday -> this week's instance of that weekday, no worries
// (gregorian data or ordinal) + (weekYear or weekNumber) -> error
// (gregorian month or day) + ordinal -> error
// otherwise just use weeks or ordinals or gregorian, depending on what's specified
if ((containsGregor || containsOrdinal) && definiteWeekDef) {
throw new ConflictingSpecificationError(
"Can't mix weekYear/weekNumber units with year/month/day or ordinals"
);
}
if (containsGregorMD && containsOrdinal) {
throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
}
const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);
// configure ourselves to deal with gregorian dates or week stuff
let units,
defaultValues,
objNow = tsToObj(tsNow, offsetProvis);
if (useWeekData) {
units = orderedWeekUnits;
defaultValues = defaultWeekUnitValues;
objNow = gregorianToWeek(objNow);
} else if (containsOrdinal) {
units = orderedOrdinalUnits;
defaultValues = defaultOrdinalUnitValues;
objNow = gregorianToOrdinal(objNow);
} else {
units = orderedUnits;
defaultValues = defaultUnitValues;
}
// set default values for missing stuff
let foundFirst = false;
for (const u of units) {
const v = normalized[u];
if (!isUndefined(v)) {
foundFirst = true;
} else if (foundFirst) {
normalized[u] = defaultValues[u];
} else {
normalized[u] = objNow[u];
}
}
// make sure the values we have are in range
const higherOrderInvalid = useWeekData
? hasInvalidWeekData(normalized)
: containsOrdinal
? hasInvalidOrdinalData(normalized)
: hasInvalidGregorianData(normalized),
invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
if (invalid) {
return DateTime.invalid(invalid);
}
// compute the actual time
const gregorian = useWeekData
? weekToGregorian(normalized)
: containsOrdinal
? ordinalToGregorian(normalized)
: normalized,
[tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),
inst = new DateTime({
ts: tsFinal,
zone: zoneToUse,
o: offsetFinal,
loc
});
// gregorian data + weekday serves only to validate
if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
return DateTime.invalid(
"mismatched weekday",
`you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`
);
}
return inst;
}
/**
* Create a DateTime from an ISO 8601 string
* @param {string} text - the ISO string
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
* @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
* @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
* @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromISO('2016-05-25T09:08:34.123')
* @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
* @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
* @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
* @example DateTime.fromISO('2016-W05-4')
* @return {DateTime}
*/
static fromISO(text, opts = {}) {
const [vals, parsedZone] = parseISODate(text);
return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
}
/**
* Create a DateTime from an RFC 2822 string
* @param {string} text - the RFC 2822 string
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
* @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
* @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
* @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
* @return {DateTime}
*/
static fromRFC2822(text, opts = {}) {
const [vals, parsedZone] = parseRFC2822Date(text);
return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
}
/**
* Create a DateTime from an HTTP header date
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
* @param {string} text - the HTTP header date
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
* @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
* @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
* @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')
* @return {DateTime}
*/
static fromHTTP(text, opts = {}) {
const [vals, parsedZone] = parseHTTPDate(text);
return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
}
/**
* Create a DateTime from an input string and format string.
* Defaults to en-US if no locale has been specified, regardless of the system's locale.
* @see https://moment.github.io/luxon/docs/manual/parsing.html#table-of-tokens
* @param {string} text - the string to parse
* @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
* @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
* @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @return {DateTime}
*/
static fromFormat(text, fmt, opts = {}) {
if (isUndefined(text) || isUndefined(fmt)) {
throw new InvalidArgumentError("fromFormat requires an input string and a format");
}
const { locale = null, numberingSystem = null } = opts,
localeToUse = Locale.fromOpts({
locale,
numberingSystem,
defaultToEN: true
}),
[vals, parsedZone, invalid] = parseFromTokens(localeToUse, text, fmt);
if (invalid) {
return DateTime.invalid(invalid);
} else {
return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text);
}
}
/**
* @deprecated use fromFormat instead
*/
static fromString(text, fmt, opts = {}) {
return DateTime.fromFormat(text, fmt, opts);
}
/**
* Create a DateTime from a SQL date, time, or datetime
* Defaults to en-US if no locale has been specified, regardless of the system's locale
* @param {string} text - the string to parse
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
* @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
* @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @example DateTime.fromSQL('2017-05-15')
* @example DateTime.fromSQL('2017-05-15 09:12:34')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
* @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
* @example DateTime.fromSQL('09:12:34.342')
* @return {DateTime}
*/
static fromSQL(text, opts = {}) {
const [vals, parsedZone] = parseSQL(text);
return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
}
/**
* Create an invalid DateTime.
* @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent
* @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
* @return {DateTime}
*/
static invalid(reason, explanation = null) {
if (!reason) {
throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
}
const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
if (Settings.throwOnInvalid) {
throw new InvalidDateTimeError(invalid);
} else {
return new DateTime({ invalid });
}
}
/**
* Check if an object is a DateTime. Works across context boundaries
* @param {object} o
* @return {boolean}
*/
static isDateTime(o) {
return (o && o.isLuxonDateTime) || false;
}
// INFO
/**
* Get the value of unit.
* @param {string} unit - a unit such as 'minute' or 'day'
* @example DateTime.local(2017, 7, 4).get('month'); //=> 7
* @example DateTime.local(2017, 7, 4).get('day'); //=> 4
* @return {number}
*/
get(unit) {
return this[unit];
}
/**
* Returns whether the DateTime is valid. Invalid DateTimes occur when:
* * The DateTime was created from invalid calendar information, such as the 13th month or February 30
* * The DateTime was created by an operation on another invalid date
* @type {boolean}
*/
get isValid() {
return this.invalid === null;
}
/**
* Returns an error code if this DateTime is invalid, or null if the DateTime is valid
* @type {string}
*/
get invalidReason() {
return this.invalid ? this.invalid.reason : null;
}
/**
* Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
* @type {string}
*/
get invalidExplanation() {
return this.invalid ? this.invalid.explanation : null;
}
/**
* Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
*
* @type {string}
*/
get locale() {
return this.isValid ? this.loc.locale : null;
}
/**
* Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
*
* @type {string}
*/
get numberingSystem() {
return this.isValid ? this.loc.numberingSystem : null;
}
/**
* Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
*
* @type {string}
*/
get outputCalendar() {
return this.isValid ? this.loc.outputCalendar : null;
}
/**
* Get the time zone associated with this DateTime.
* @type {Zone}
*/
get zone() {
return this._zone;
}
/**
* Get the name of the time zone.
* @type {string}
*/
get zoneName() {
return this.isValid ? this.zone.name : null;
}
/**
* Get the year
* @example DateTime.local(2017, 5, 25).year //=> 2017
* @type {number}
*/
get year() {
return this.isValid ? this.c.year : NaN;
}
/**
* Get the quarter
* @example DateTime.local(2017, 5, 25).quarter //=> 2
* @type {number}
*/
get quarter() {
return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
}
/**
* Get the month (1-12).
* @example DateTime.local(2017, 5, 25).month //=> 5
* @type {number}
*/
get month() {
return this.isValid ? this.c.month : NaN;
}
/**
* Get the day of the month (1-30ish).
* @example DateTime.local(2017, 5, 25).day //=> 25
* @type {number}
*/
get day() {
return this.isValid ? this.c.day : NaN;
}
/**
* Get the hour of the day (0-23).
* @example DateTime.local(2017, 5, 25, 9).hour //=> 9
* @type {number}
*/
get hour() {
return this.isValid ? this.c.hour : NaN;
}
/**
* Get the minute of the hour (0-59).
* @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
* @type {number}
*/
get minute() {
return this.isValid ? this.c.minute : NaN;
}
/**
* Get the second of the minute (0-59).
* @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
* @type {number}
*/
get second() {
return this.isValid ? this.c.second : NaN;
}
/**
* Get the millisecond of the second (0-999).
* @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
* @type {number}
*/
get millisecond() {
return this.isValid ? this.c.millisecond : NaN;
}
/**
* Get the week year
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2014, 12, 31).weekYear //=> 2015
* @type {number}
*/
get weekYear() {
return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
}
/**
* Get the week number of the week year (1-52ish).
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2017, 5, 25).weekNumber //=> 21
* @type {number}
*/
get weekNumber() {
return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
}
/**
* Get the day of the week.
* 1 is Monday and 7 is Sunday
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2014, 11, 31).weekday //=> 4
* @type {number}
*/
get weekday() {
return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
}
/**
* Get the ordinal (meaning the day of the year)
* @example DateTime.local(2017, 5, 25).ordinal //=> 145
* @type {number|DateTime}
*/
get ordinal() {
return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
}
/**
* Get the human readable short month name, such as 'Oct'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).monthShort //=> Oct
* @type {string}
*/
get monthShort() {
return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null;
}
/**
* Get the human readable long month name, such as 'October'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).monthLong //=> October
* @type {string}
*/
get monthLong() {
return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null;
}
/**
* Get the human readable short weekday, such as 'Mon'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
* @type {string}
*/
get weekdayShort() {
return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null;
}
/**
* Get the human readable long weekday, such as 'Monday'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
* @type {string}
*/
get weekdayLong() {
return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null;
}
/**
* Get the UTC offset of this DateTime in minutes
* @example DateTime.now().offset //=> -240
* @example DateTime.utc().offset //=> 0
* @type {number}
*/
get offset() {
return this.isValid ? +this.o : NaN;
}
/**
* Get the short human name for the zone's current offset, for example "EST" or "EDT".
* Defaults to the system's locale if no locale has been specified
* @type {string}
*/
get offsetNameShort() {
if (this.isValid) {
return this.zone.offsetName(this.ts, {
format: "short",
locale: this.locale
});
} else {
return null;
}
}
/**
* Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
* Defaults to the system's locale if no locale has been specified
* @type {string}
*/
get offsetNameLong() {
if (this.isValid) {
return this.zone.offsetName(this.ts, {
format: "long",
locale: this.locale
});
} else {
return null;
}
}
/**
* Get whether this zone's offset ever changes, as in a DST.
* @type {boolean}
*/
get isOffsetFixed() {
return this.isValid ? this.zone.universal : null;
}
/**
* Get whether the DateTime is in a DST.
* @type {boolean}
*/
get isInDST() {
if (this.isOffsetFixed) {
return false;
} else {
return (
this.offset > this.set({ month: 1 }).offset || this.offset > this.set({ month: 5 }).offset
);
}
}
/**
* Returns true if this DateTime is in a leap year, false otherwise
* @example DateTime.local(2016).isInLeapYear //=> true
* @example DateTime.local(2013).isInLeapYear //=> false
* @type {boolean}
*/
get isInLeapYear() {
return isLeapYear(this.year);
}
/**
* Returns the number of days in this DateTime's month
* @example DateTime.local(2016, 2).daysInMonth //=> 29
* @example DateTime.local(2016, 3).daysInMonth //=> 31
* @type {number}
*/
get daysInMonth() {
return daysInMonth(this.year, this.month);
}
/**
* Returns the number of days in this DateTime's year
* @example DateTime.local(2016).daysInYear //=> 366
* @example DateTime.local(2013).daysInYear //=> 365
* @type {number}
*/
get daysInYear() {
return this.isValid ? daysInYear(this.year) : NaN;
}
/**
* Returns the number of weeks in this DateTime's year
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2004).weeksInWeekYear //=> 53
* @example DateTime.local(2013).weeksInWeekYear //=> 52
* @type {number}
*/
get weeksInWeekYear() {
return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
}
/**
* Returns the resolved Intl options for this DateTime.
* This is useful in understanding the behavior of formatting methods
* @param {Object} opts - the same options as toLocaleString
* @return {Object}
*/
resolvedLocaleOpts(opts = {}) {
const { locale, numberingSystem, calendar } = Formatter.create(
this.loc.clone(opts),
opts
).resolvedOptions(this);
return { locale, numberingSystem, outputCalendar: calendar };
}
// TRANSFORM
/**
* "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
*
* Equivalent to {@link setZone}('utc')
* @param {number} [offset=0] - optionally, an offset from UTC in minutes
* @param {Object} [opts={}] - options to pass to `setZone()`
* @return {DateTime}
*/
toUTC(offset = 0, opts = {}) {
return this.setZone(FixedOffsetZone.instance(offset), opts);
}
/**
* "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
*
* Equivalent to `setZone('local')`
* @return {DateTime}
*/
toLocal() {
return this.setZone(Settings.defaultZone);
}
/**
* "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
*
* By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link plus}. You may wish to use {@link toLocal} and {@link toUTC} which provide simple convenience wrappers for commonly used zones.
* @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link Zone} class.
* @param {Object} opts - options
* @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
* @return {DateTime}
*/
setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {
zone = normalizeZone(zone, Settings.defaultZone);
if (zone.equals(this.zone)) {
return this;
} else if (!zone.isValid) {
return DateTime.invalid(unsupportedZone(zone));
} else {
let newTS = this.ts;
if (keepLocalTime || keepCalendarTime) {
const offsetGuess = zone.offset(this.ts);
const asObj = this.toObject();
[newTS] = objToTS(asObj, offsetGuess, zone);
}
return clone(this, { ts: newTS, zone });
}
}
/**
* "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
* @param {Object} properties - the properties to set
* @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
* @return {DateTime}
*/
reconfigure({ locale, numberingSystem, outputCalendar } = {}) {
const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });
return clone(this, { loc });
}
/**
* "Set" the locale. Returns a newly-constructed DateTime.
* Just a convenient alias for reconfigure({ locale })
* @example DateTime.local(2017, 5, 25).setLocale('en-GB')
* @return {DateTime}
*/
setLocale(locale) {
return this.reconfigure({ locale });
}
/**
* "Set" the values of specified units. Returns a newly-constructed DateTime.
* You can only set units with this method; for "setting" metadata, see {@link reconfigure} and {@link setZone}.
* @param {Object} values - a mapping of units to numbers
* @example dt.set({ year: 2017 })
* @example dt.set({ hour: 8, minute: 30 })
* @example dt.set({ weekday: 5 })
* @example dt.set({ year: 2005, ordinal: 234 })
* @return {DateTime}
*/
set(values) {
if (!this.isValid) return this;
const normalized = normalizeObject(values, normalizeUnit, []),
settingWeekStuff =
!isUndefined(normalized.weekYear) ||
!isUndefined(normalized.weekNumber) ||
!isUndefined(normalized.weekday),
containsOrdinal = !isUndefined(normalized.ordinal),
containsGregorYear = !isUndefined(normalized.year),
containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
containsGregor = containsGregorYear || containsGregorMD,
definiteWeekDef = normalized.weekYear || normalized.weekNumber;
if ((containsGregor || containsOrdinal) && definiteWeekDef) {
throw new ConflictingSpecificationError(
"Can't mix weekYear/weekNumber units with year/month/day or ordinals"
);
}
if (containsGregorMD && containsOrdinal) {
throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
}
let mixed;
if (settingWeekStuff) {
mixed = weekToGregorian(Object.assign(gregorianToWeek(this.c), normalized));
} else if (!isUndefined(normalized.ordinal)) {
mixed = ordinalToGregorian(Object.assign(gregorianToOrdinal(this.c), normalized));
} else {
mixed = Object.assign(this.toObject(), normalized);
// if we didn't set the day but we ended up on an overflow date,
// use the last day of the right month
if (isUndefined(normalized.day)) {
mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
}
}
const [ts, o] = objToTS(mixed, this.o, this.zone);
return clone(this, { ts, o });
}
/**
* Add a period of time to this DateTime and return the resulting DateTime
*
* Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
* @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
* @example DateTime.now().plus(123) //~> in 123 milliseconds
* @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
* @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
* @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
* @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
* @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
* @return {DateTime}
*/
plus(duration) {
if (!this.isValid) return this;
const dur = friendlyDuration(duration);
return clone(this, adjustTime(this, dur));
}
/**
* Subtract a period of time to this DateTime and return the resulting DateTime
* See {@link plus}
* @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
@return {DateTime}
*/
minus(duration) {
if (!this.isValid) return this;
const dur = friendlyDuration(duration).negate();
return clone(this, adjustTime(this, dur));
}
/**
* "Set" this DateTime to the beginning of a unit of time.
* @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
* @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
* @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
* @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
* @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
* @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
* @return {DateTime}
*/
startOf(unit) {
if (!this.isValid) return this;
const o = {},
normalizedUnit = Duration.normalizeUnit(unit);
switch (normalizedUnit) {
case "years":
o.month = 1;
// falls through
case "quarters":
case "months":
o.day = 1;
// falls through
case "weeks":
case "days":
o.hour = 0;
// falls through
case "hours":
o.minute = 0;
// falls through
case "minutes":
o.second = 0;
// falls through
case "seconds":
o.millisecond = 0;
break;
case "milliseconds":
break;
// no default, invalid units throw in normalizeUnit()
}
if (normalizedUnit === "weeks") {
o.weekday = 1;
}
if (normalizedUnit === "quarters") {
const q = Math.ceil(this.month / 3);
o.month = (q - 1) * 3 + 1;
}
return this.set(o);
}
/**
* "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
* @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
* @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
* @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
* @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
* @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
* @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
* @return {DateTime}
*/
endOf(unit) {
return this.isValid
? this.plus({ [unit]: 1 })
.startOf(unit)
.minus(1)
: this;
}
// OUTPUT
/**
* Returns a string representation of this DateTime formatted according to the specified format string.
* **You may not want this.** See {@link toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens).
* Defaults to en-US if no locale has been specified, regardless of the system's locale.
* @see https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens
* @param {string} fmt - the format string
* @param {Object} opts - opts to override the configuration options
* @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
* @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
* @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
* @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
* @return {string}
*/
toFormat(fmt, opts = {}) {
return this.isValid
? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt)
: INVALID;
}
/**
* Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
* The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
* of the DateTime in the assigned locale.
* Defaults to the system's locale if no locale has been specified
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
* @param opts {Object} - Intl.DateTimeFormat constructor options and configuration options
* @example DateTime.now().toLocaleString(); //=> 4/20/2017
* @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
* @example DateTime.now().toLocaleString({ locale: 'en-gb' }); //=> '20/04/2017'
* @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
* @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
* @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
* @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
* @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
* @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hour12: false }); //=> '11:32'
* @return {string}
*/
toLocaleString(opts = Formats.DATE_SHORT) {
return this.isValid
? Formatter.create(this.loc.clone(opts), opts).formatDateTime(this)
: INVALID;
}
/**
* Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
* Defaults to the system's locale if no locale has been specified
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
* @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
* @example DateTime.now().toLocaleParts(); //=> [
* //=> { type: 'day', value: '25' },
* //=> { type: 'literal', value: '/' },
* //=> { type: 'month', value: '05' },
* //=> { type: 'literal', value: '/' },
* //=> { type: 'year', value: '1982' }
* //=> ]
*/
toLocaleParts(opts = {}) {
return this.isValid
? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this)
: [];
}
/**
* Returns an ISO 8601-compliant string representation of this DateTime
* @param {Object} opts - options
* @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
* @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
* @param {string} [opts.format='extended'] - choose between the basic and extended format
* @example DateTime.utc(1982, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
* @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
* @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
* @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
* @return {string}
*/
toISO(opts = {}) {
if (!this.isValid) {
return null;
}
return `${this.toISODate(opts)}T${this.toISOTime(opts)}`;
}
/**
* Returns an ISO 8601-compliant string representation of this DateTime's date component
* @param {Object} opts - options
* @param {string} [opts.format='extended'] - choose between the basic and extended format
* @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
* @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
* @return {string}
*/
toISODate({ format = "extended" } = {}) {
let fmt = format === "basic" ? "yyyyMMdd" : "yyyy-MM-dd";
if (this.year > 9999) {
fmt = "+" + fmt;
}
return toTechFormat(this, fmt);
}
/**
* Returns an ISO 8601-compliant string representation of this DateTime's week date
* @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
* @return {string}
*/
toISOWeekDate() {
return toTechFormat(this, "kkkk-'W'WW-c");
}
/**
* Returns an ISO 8601-compliant string representation of this DateTime's time component
* @param {Object} opts - options
* @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
* @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
* @param {boolean} [opts.includePrefix=false] - include the `T` prefix
* @param {string} [opts.format='extended'] - choose between the basic and extended format
* @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
* @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
* @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
* @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
* @return {string}
*/
toISOTime({
suppressMilliseconds = false,
suppressSeconds = false,
includeOffset = true,
includePrefix = false,
format = "extended"
} = {}) {
return toTechTimeFormat(this, {
suppressSeconds,
suppressMilliseconds,
includeOffset,
includePrefix,
format
});
}
/**
* Returns an RFC 2822-compatible string representation of this DateTime, always in UTC
* @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
* @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
* @return {string}
*/
toRFC2822() {
return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
}
/**
* Returns a string representation of this DateTime appropriate for use in HTTP headers.
* Specifically, the string conforms to RFC 1123.
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
* @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
* @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
* @return {string}
*/
toHTTP() {
return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
}
/**
* Returns a string representation of this DateTime appropriate for use in SQL Date
* @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
* @return {string}
*/
toSQLDate() {
return toTechFormat(this, "yyyy-MM-dd");
}
/**
* Returns a string representation of this DateTime appropriate for use in SQL Time
* @param {Object} opts - options
* @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
* @example DateTime.utc().toSQL() //=> '05:15:16.345'
* @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
* @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
* @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
* @return {string}
*/
toSQLTime({ includeOffset = true, includeZone = false } = {}) {
return toTechTimeFormat(this, {
includeOffset,
includeZone,
spaceZone: true
});
}
/**
* Returns a string representation of this DateTime appropriate for use in SQL DateTime
* @param {Object} opts - options
* @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
* @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
* @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
* @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
* @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
* @return {string}
*/
toSQL(opts = {}) {
if (!this.isValid) {
return null;
}
return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
}
/**
* Returns a string representation of this DateTime appropriate for debugging
* @return {string}
*/
toString() {
return this.isValid ? this.toISO() : INVALID;
}
/**
* Returns the epoch milliseconds of this DateTime. Alias of {@link toMillis}
* @return {number}
*/
valueOf() {
return this.toMillis();
}
/**
* Returns the epoch milliseconds of this DateTime.
* @return {number}
*/
toMillis() {
return this.isValid ? this.ts : NaN;
}
/**
* Returns the epoch seconds of this DateTime.
* @return {number}
*/
toSeconds() {
return this.isValid ? this.ts / 1000 : NaN;
}
/**
* Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
* @return {string}
*/
toJSON() {
return this.toISO();
}
/**
* Returns a BSON serializable equivalent to this DateTime.
* @return {Date}
*/
toBSON() {
return this.toJSDate();
}
/**
* Returns a JavaScript object with this DateTime's year, month, day, and so on.
* @param opts - options for generating the object
* @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
* @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
* @return {Object}
*/
toObject(opts = {}) {
if (!this.isValid) return {};
const base = Object.assign({}, this.c);
if (opts.includeConfig) {
base.outputCalendar = this.outputCalendar;
base.numberingSystem = this.loc.numberingSystem;
base.locale = this.loc.locale;
}
return base;
}
/**
* Returns a JavaScript Date equivalent to this DateTime.
* @return {Date}
*/
toJSDate() {
return new Date(this.isValid ? this.ts : NaN);
}
// COMPARE
/**
* Return the difference between two DateTimes as a Duration.
* @param {DateTime} otherDateTime - the DateTime to compare this one to
* @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
* @param {Object} opts - options that affect the creation of the Duration
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @example
* var i1 = DateTime.fromISO('1982-05-25T09:45'),
* i2 = DateTime.fromISO('1983-10-14T10:30');
* i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
* i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
* i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
* i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
* @return {Duration}
*/
diff(otherDateTime, unit = "milliseconds", opts = {}) {
if (!this.isValid || !otherDateTime.isValid) {
return Duration.invalid(
this.invalid || otherDateTime.invalid,
"created by diffing an invalid DateTime"
);
}
const durOpts = Object.assign(
{ locale: this.locale, numberingSystem: this.numberingSystem },
opts
);
const units = maybeArray(unit).map(Duration.normalizeUnit),
otherIsLater = otherDateTime.valueOf() > this.valueOf(),
earlier = otherIsLater ? this : otherDateTime,
later = otherIsLater ? otherDateTime : this,
diffed = diff(earlier, later, units, durOpts);
return otherIsLater ? diffed.negate() : diffed;
}
/**
* Return the difference between this DateTime and right now.
* See {@link diff}
* @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
* @param {Object} opts - options that affect the creation of the Duration
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @return {Duration}
*/
diffNow(unit = "milliseconds", opts = {}) {
return this.diff(DateTime.now(), unit, opts);
}
/**
* Return an Interval spanning between this DateTime and another DateTime
* @param {DateTime} otherDateTime - the other end point of the Interval
* @return {Interval}
*/
until(otherDateTime) {
return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
}
/**
* Return whether this DateTime is in the same unit of time as another DateTime.
* Higher-order units must also be identical for this function to return `true`.
* Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link setZone} to convert one of the dates if needed.
* @param {DateTime} otherDateTime - the other DateTime
* @param {string} unit - the unit of time to check sameness on
* @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
* @return {boolean}
*/
hasSame(otherDateTime, unit) {
if (!this.isValid) return false;
const inputMs = otherDateTime.valueOf();
const otherZoneDateTime = this.setZone(otherDateTime.zone, { keepLocalTime: true });
return otherZoneDateTime.startOf(unit) <= inputMs && inputMs <= otherZoneDateTime.endOf(unit);
}
/**
* Equality check
* Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid.
* To compare just the millisecond values, use `+dt1 === +dt2`.
* @param {DateTime} other - the other DateTime
* @return {boolean}
*/
equals(other) {
return (
this.isValid &&
other.isValid &&
this.valueOf() === other.valueOf() &&
this.zone.equals(other.zone) &&
this.loc.equals(other.loc)
);
}
/**
* Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
* platform supports Intl.RelativeTimeFormat. Rounds down by default.
* @param {Object} options - options that affect the output
* @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
* @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
* @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
* @param {boolean} [options.round=true] - whether to round the numbers in the output.
* @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
* @param {string} options.locale - override the locale of this DateTime
* @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
* @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
* @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
* @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
* @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
* @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
* @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
*/
toRelative(options = {}) {
if (!this.isValid) return null;
const base = options.base || DateTime.fromObject({ zone: this.zone }),
padding = options.padding ? (this < base ? -options.padding : options.padding) : 0;
let units = ["years", "months", "days", "hours", "minutes", "seconds"];
let unit = options.unit;
if (Array.isArray(options.unit)) {
units = options.unit;
unit = undefined;
}
return diffRelative(
base,
this.plus(padding),
Object.assign(options, {
numeric: "always",
units,
unit
})
);
}
/**
* Returns a string representation of this date relative to today, such as "yesterday" or "next month".
* Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
* @param {Object} options - options that affect the output
* @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
* @param {string} options.locale - override the locale of this DateTime
* @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
* @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
* @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
* @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
* @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
* @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
*/
toRelativeCalendar(options = {}) {
if (!this.isValid) return null;
return diffRelative(
options.base || DateTime.fromObject({ zone: this.zone }),
this,
Object.assign(options, {
numeric: "auto",
units: ["years", "months", "days"],
calendary: true
})
);
}
/**
* Return the min of several date times
* @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
* @return {DateTime} the min DateTime, or undefined if called with no argument
*/
static min(...dateTimes) {
if (!dateTimes.every(DateTime.isDateTime)) {
throw new InvalidArgumentError("min requires all arguments be DateTimes");
}
return bestBy(dateTimes, i => i.valueOf(), Math.min);
}
/**
* Return the max of several date times
* @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
* @return {DateTime} the max DateTime, or undefined if called with no argument
*/
static max(...dateTimes) {
if (!dateTimes.every(DateTime.isDateTime)) {
throw new InvalidArgumentError("max requires all arguments be DateTimes");
}
return bestBy(dateTimes, i => i.valueOf(), Math.max);
}
// MISC
/**
* Explain how a string would be parsed by fromFormat()
* @param {string} text - the string to parse
* @param {string} fmt - the format the string is expected to be in (see description)
* @param {Object} options - options taken by fromFormat()
* @return {Object}
*/
static fromFormatExplain(text, fmt, options = {}) {
const { locale = null, numberingSystem = null } = options,
localeToUse = Locale.fromOpts({
locale,
numberingSystem,
defaultToEN: true
});
return explainFromTokens(localeToUse, text, fmt);
}
/**
* @deprecated use fromFormatExplain instead
*/
static fromStringExplain(text, fmt, options = {}) {
return DateTime.fromFormatExplain(text, fmt, options);
}
// FORMAT PRESETS
/**
* {@link toLocaleString} format like 10/14/1983
* @type {Object}
*/
static get DATE_SHORT() {
return Formats.DATE_SHORT;
}
/**
* {@link toLocaleString} format like 'Oct 14, 1983'
* @type {Object}
*/
static get DATE_MED() {
return Formats.DATE_MED;
}
/**
* {@link toLocaleString} format like 'Fri, Oct 14, 1983'
* @type {Object}
*/
static get DATE_MED_WITH_WEEKDAY() {
return Formats.DATE_MED_WITH_WEEKDAY;
}
/**
* {@link toLocaleString} format like 'October 14, 1983'
* @type {Object}
*/
static get DATE_FULL() {
return Formats.DATE_FULL;
}
/**
* {@link toLocaleString} format like 'Tuesday, October 14, 1983'
* @type {Object}
*/
static get DATE_HUGE() {
return Formats.DATE_HUGE;
}
/**
* {@link toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get TIME_SIMPLE() {
return Formats.TIME_SIMPLE;
}
/**
* {@link toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get TIME_WITH_SECONDS() {
return Formats.TIME_WITH_SECONDS;
}
/**
* {@link toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
* @type {Object}
*/
static get TIME_WITH_SHORT_OFFSET() {
return Formats.TIME_WITH_SHORT_OFFSET;
}
/**
* {@link toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
* @type {Object}
*/
static get TIME_WITH_LONG_OFFSET() {
return Formats.TIME_WITH_LONG_OFFSET;
}
/**
* {@link toLocaleString} format like '09:30', always 24-hour.
* @type {Object}
*/
static get TIME_24_SIMPLE() {
return Formats.TIME_24_SIMPLE;
}
/**
* {@link toLocaleString} format like '09:30:23', always 24-hour.
* @type {Object}
*/
static get TIME_24_WITH_SECONDS() {
return Formats.TIME_24_WITH_SECONDS;
}
/**
* {@link toLocaleString} format like '09:30:23 EDT', always 24-hour.
* @type {Object}
*/
static get TIME_24_WITH_SHORT_OFFSET() {
return Formats.TIME_24_WITH_SHORT_OFFSET;
}
/**
* {@link toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
* @type {Object}
*/
static get TIME_24_WITH_LONG_OFFSET() {
return Formats.TIME_24_WITH_LONG_OFFSET;
}
/**
* {@link toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_SHORT() {
return Formats.DATETIME_SHORT;
}
/**
* {@link toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_SHORT_WITH_SECONDS() {
return Formats.DATETIME_SHORT_WITH_SECONDS;
}
/**
* {@link toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_MED() {
return Formats.DATETIME_MED;
}
/**
* {@link toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_MED_WITH_SECONDS() {
return Formats.DATETIME_MED_WITH_SECONDS;
}
/**
* {@link toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_MED_WITH_WEEKDAY() {
return Formats.DATETIME_MED_WITH_WEEKDAY;
}
/**
* {@link toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_FULL() {
return Formats.DATETIME_FULL;
}
/**
* {@link toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_FULL_WITH_SECONDS() {
return Formats.DATETIME_FULL_WITH_SECONDS;
}
/**
* {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_HUGE() {
return Formats.DATETIME_HUGE;
}
/**
* {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_HUGE_WITH_SECONDS() {
return Formats.DATETIME_HUGE_WITH_SECONDS;
}
}
/**
* @private
*/
export function friendlyDateTime(dateTimeish) {
if (DateTime.isDateTime(dateTimeish)) {
return dateTimeish;
} else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
return DateTime.fromJSDate(dateTimeish);
} else if (dateTimeish && typeof dateTimeish === "object") {
return DateTime.fromObject(dateTimeish);
} else {
throw new InvalidArgumentError(
`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`
);
}
}
import { InvalidArgumentError, InvalidDurationError, InvalidUnitError } from "./errors.js";
import Formatter from "./impl/formatter.js";
import Invalid from "./impl/invalid.js";
import Locale from "./impl/locale.js";
import { parseISODuration, parseISOTimeOnly } from "./impl/regexParser.js";
import {
asNumber,
hasOwnProperty,
isNumber,
isUndefined,
normalizeObject,
roundTo
} from "./impl/util.js";
import Settings from "./settings.js";
const INVALID = "Invalid Duration";
// unit conversion constants
const lowOrderMatrix = {
weeks: {
days: 7,
hours: 7 * 24,
minutes: 7 * 24 * 60,
seconds: 7 * 24 * 60 * 60,
milliseconds: 7 * 24 * 60 * 60 * 1000
},
days: {
hours: 24,
minutes: 24 * 60,
seconds: 24 * 60 * 60,
milliseconds: 24 * 60 * 60 * 1000
},
hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 },
minutes: { seconds: 60, milliseconds: 60 * 1000 },
seconds: { milliseconds: 1000 }
},
casualMatrix = Object.assign(
{
years: {
quarters: 4,
months: 12,
weeks: 52,
days: 365,
hours: 365 * 24,
minutes: 365 * 24 * 60,
seconds: 365 * 24 * 60 * 60,
milliseconds: 365 * 24 * 60 * 60 * 1000
},
quarters: {
months: 3,
weeks: 13,
days: 91,
hours: 91 * 24,
minutes: 91 * 24 * 60,
seconds: 91 * 24 * 60 * 60,
milliseconds: 91 * 24 * 60 * 60 * 1000
},
months: {
weeks: 4,
days: 30,
hours: 30 * 24,
minutes: 30 * 24 * 60,
seconds: 30 * 24 * 60 * 60,
milliseconds: 30 * 24 * 60 * 60 * 1000
}
},
lowOrderMatrix
),
daysInYearAccurate = 146097.0 / 400,
daysInMonthAccurate = 146097.0 / 4800,
accurateMatrix = Object.assign(
{
years: {
quarters: 4,
months: 12,
weeks: daysInYearAccurate / 7,
days: daysInYearAccurate,
hours: daysInYearAccurate * 24,
minutes: daysInYearAccurate * 24 * 60,
seconds: daysInYearAccurate * 24 * 60 * 60,
milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000
},
quarters: {
months: 3,
weeks: daysInYearAccurate / 28,
days: daysInYearAccurate / 4,
hours: (daysInYearAccurate * 24) / 4,
minutes: (daysInYearAccurate * 24 * 60) / 4,
seconds: (daysInYearAccurate * 24 * 60 * 60) / 4,
milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4
},
months: {
weeks: daysInMonthAccurate / 7,
days: daysInMonthAccurate,
hours: daysInMonthAccurate * 24,
minutes: daysInMonthAccurate * 24 * 60,
seconds: daysInMonthAccurate * 24 * 60 * 60,
milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000
}
},
lowOrderMatrix
);
// units ordered by size
const orderedUnits = [
"years",
"quarters",
"months",
"weeks",
"days",
"hours",
"minutes",
"seconds",
"milliseconds"
];
const reverseUnits = orderedUnits.slice(0).reverse();
// clone really means "create another instance just like this one, but with these changes"
function clone(dur, alts, clear = false) {
// deep merge for vals
const conf = {
values: clear ? alts.values : Object.assign({}, dur.values, alts.values || {}),
loc: dur.loc.clone(alts.loc),
conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy
};
return new Duration(conf);
}
function antiTrunc(n) {
return n < 0 ? Math.floor(n) : Math.ceil(n);
}
// NB: mutates parameters
function convert(matrix, fromMap, fromUnit, toMap, toUnit) {
const conv = matrix[toUnit][fromUnit],
raw = fromMap[fromUnit] / conv,
sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]),
// ok, so this is wild, but see the matrix in the tests
added =
!sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);
toMap[toUnit] += added;
fromMap[fromUnit] -= added * conv;
}
// NB: mutates parameters
function normalizeValues(matrix, vals) {
reverseUnits.reduce((previous, current) => {
if (!isUndefined(vals[current])) {
if (previous) {
convert(matrix, vals, previous, vals, current);
}
return current;
} else {
return previous;
}
}, null);
}
/**
* A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime.plus} to add a Duration object to a DateTime, producing another DateTime.
*
* Here is a brief overview of commonly used methods and getters in Duration:
*
* * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.
* * **Unit values** See the {@link Duration.years}, {@link Duration.months}, {@link Duration.weeks}, {@link Duration.days}, {@link Duration.hours}, {@link Duration.minutes}, {@link Duration.seconds}, {@link Duration.milliseconds} accessors.
* * **Configuration** See {@link Duration.locale} and {@link Duration.numberingSystem} accessors.
* * **Transformation** To create new Durations out of old ones use {@link Duration.plus}, {@link Duration.minus}, {@link Duration.normalize}, {@link Duration.set}, {@link Duration.reconfigure}, {@link Duration.shiftTo}, and {@link Duration.negate}.
* * **Output** To convert the Duration into other representations, see {@link Duration.as}, {@link Duration.toISO}, {@link Duration.toFormat}, and {@link Duration.toJSON}
*
* There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.
*/
export default class Duration {
/**
* @private
*/
constructor(config) {
const accurate = config.conversionAccuracy === "longterm" || false;
/**
* @access private
*/
this.values = config.values;
/**
* @access private
*/
this.loc = config.loc || Locale.create();
/**
* @access private
*/
this.conversionAccuracy = accurate ? "longterm" : "casual";
/**
* @access private
*/
this.invalid = config.invalid || null;
/**
* @access private
*/
this.matrix = accurate ? accurateMatrix : casualMatrix;
/**
* @access private
*/
this.isLuxonDuration = true;
}
/**
* Create Duration from a number of milliseconds.
* @param {number} count of milliseconds
* @param {Object} opts - options for parsing
* @param {string} [opts.locale='en-US'] - the locale to use
* @param {string} opts.numberingSystem - the numbering system to use
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @return {Duration}
*/
static fromMillis(count, opts) {
return Duration.fromObject(Object.assign({ milliseconds: count }, opts));
}
/**
* Create a Duration from a JavaScript object with keys like 'years' and 'hours.
* If this object is empty then a zero milliseconds duration is returned.
* @param {Object} obj - the object to create the DateTime from
* @param {number} obj.years
* @param {number} obj.quarters
* @param {number} obj.months
* @param {number} obj.weeks
* @param {number} obj.days
* @param {number} obj.hours
* @param {number} obj.minutes
* @param {number} obj.seconds
* @param {number} obj.milliseconds
* @param {string} [obj.locale='en-US'] - the locale to use
* @param {string} obj.numberingSystem - the numbering system to use
* @param {string} [obj.conversionAccuracy='casual'] - the conversion system to use
* @return {Duration}
*/
static fromObject(obj) {
if (obj == null || typeof obj !== "object") {
throw new InvalidArgumentError(
`Duration.fromObject: argument expected to be an object, got ${
obj === null ? "null" : typeof obj
}`
);
}
return new Duration({
values: normalizeObject(obj, Duration.normalizeUnit, [
"locale",
"numberingSystem",
"conversionAccuracy",
"zone" // a bit of debt; it's super inconvenient internally not to be able to blindly pass this
]),
loc: Locale.fromObject(obj),
conversionAccuracy: obj.conversionAccuracy
});
}
/**
* Create a Duration from an ISO 8601 duration string.
* @param {string} text - text to parse
* @param {Object} opts - options for parsing
* @param {string} [opts.locale='en-US'] - the locale to use
* @param {string} opts.numberingSystem - the numbering system to use
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @see https://en.wikipedia.org/wiki/ISO_8601#Durations
* @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
* @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
* @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
* @return {Duration}
*/
static fromISO(text, opts) {
const [parsed] = parseISODuration(text);
if (parsed) {
const obj = Object.assign(parsed, opts);
return Duration.fromObject(obj);
} else {
return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
}
}
/**
* Create a Duration from an ISO 8601 time string.
* @param {string} text - text to parse
* @param {Object} opts - options for parsing
* @param {string} [opts.locale='en-US'] - the locale to use
* @param {string} opts.numberingSystem - the numbering system to use
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @see https://en.wikipedia.org/wiki/ISO_8601#Times
* @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
* @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
* @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
* @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
* @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
* @return {Duration}
*/
static fromISOTime(text, opts) {
const [parsed] = parseISOTimeOnly(text);
if (parsed) {
const obj = Object.assign(parsed, opts);
return Duration.fromObject(obj);
} else {
return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
}
}
/**
* Create an invalid Duration.
* @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
* @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
* @return {Duration}
*/
static invalid(reason, explanation = null) {
if (!reason) {
throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
}
const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
if (Settings.throwOnInvalid) {
throw new InvalidDurationError(invalid);
} else {
return new Duration({ invalid });
}
}
/**
* @private
*/
static normalizeUnit(unit) {
const normalized = {
year: "years",
years: "years",
quarter: "quarters",
quarters: "quarters",
month: "months",
months: "months",
week: "weeks",
weeks: "weeks",
day: "days",
days: "days",
hour: "hours",
hours: "hours",
minute: "minutes",
minutes: "minutes",
second: "seconds",
seconds: "seconds",
millisecond: "milliseconds",
milliseconds: "milliseconds"
}[unit ? unit.toLowerCase() : unit];
if (!normalized) throw new InvalidUnitError(unit);
return normalized;
}
/**
* Check if an object is a Duration. Works across context boundaries
* @param {object} o
* @return {boolean}
*/
static isDuration(o) {
return (o && o.isLuxonDuration) || false;
}
/**
* Get the locale of a Duration, such 'en-GB'
* @type {string}
*/
get locale() {
return this.isValid ? this.loc.locale : null;
}
/**
* Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
*
* @type {string}
*/
get numberingSystem() {
return this.isValid ? this.loc.numberingSystem : null;
}
/**
* Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
* * `S` for milliseconds
* * `s` for seconds
* * `m` for minutes
* * `h` for hours
* * `d` for days
* * `M` for months
* * `y` for years
* Notes:
* * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
* * The duration will be converted to the set of units in the format string using {@link Duration.shiftTo} and the Durations's conversion accuracy setting.
* @param {string} fmt - the format string
* @param {Object} opts - options
* @param {boolean} [opts.floor=true] - floor numerical values
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
* @return {string}
*/
toFormat(fmt, opts = {}) {
// reverse-compat since 1.2; we always round down now, never up, and we do it by default
const fmtOpts = Object.assign({}, opts, {
floor: opts.round !== false && opts.floor !== false
});
return this.isValid
? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt)
: INVALID;
}
/**
* Returns a JavaScript object with this Duration's values.
* @param opts - options for generating the object
* @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
* @return {Object}
*/
toObject(opts = {}) {
if (!this.isValid) return {};
const base = Object.assign({}, this.values);
if (opts.includeConfig) {
base.conversionAccuracy = this.conversionAccuracy;
base.numberingSystem = this.loc.numberingSystem;
base.locale = this.loc.locale;
}
return base;
}
/**
* Returns an ISO 8601-compliant string representation of this Duration.
* @see https://en.wikipedia.org/wiki/ISO_8601#Durations
* @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
* @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
* @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
* @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
* @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
* @return {string}
*/
toISO() {
// we could use the formatter, but this is an easier way to get the minimum string
if (!this.isValid) return null;
let s = "P";
if (this.years !== 0) s += this.years + "Y";
if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M";
if (this.weeks !== 0) s += this.weeks + "W";
if (this.days !== 0) s += this.days + "D";
if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
s += "T";
if (this.hours !== 0) s += this.hours + "H";
if (this.minutes !== 0) s += this.minutes + "M";
if (this.seconds !== 0 || this.milliseconds !== 0)
// this will handle "floating point madness" by removing extra decimal places
// https://stackoverflow.com/questions/588004/is-floating-point-math-broken
s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S";
if (s === "P") s += "T0S";
return s;
}
/**
* Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
* Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
* @see https://en.wikipedia.org/wiki/ISO_8601#Times
* @param {Object} opts - options
* @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
* @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
* @param {boolean} [opts.includePrefix=false] - include the `T` prefix
* @param {string} [opts.format='extended'] - choose between the basic and extended format
* @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
* @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
* @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
* @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
* @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
* @return {string}
*/
toISOTime(opts = {}) {
if (!this.isValid) return null;
const millis = this.toMillis();
if (millis < 0 || millis >= 86400000) return null;
opts = Object.assign(
{
suppressMilliseconds: false,
suppressSeconds: false,
includePrefix: false,
format: "extended"
},
opts
);
const value = this.shiftTo("hours", "minutes", "seconds", "milliseconds");
let fmt = opts.format === "basic" ? "hhmm" : "hh:mm";
if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) {
fmt += opts.format === "basic" ? "ss" : ":ss";
if (!opts.suppressMilliseconds || value.milliseconds !== 0) {
fmt += ".SSS";
}
}
let str = value.toFormat(fmt);
if (opts.includePrefix) {
str = "T" + str;
}
return str;
}
/**
* Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
* @return {string}
*/
toJSON() {
return this.toISO();
}
/**
* Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
* @return {string}
*/
toString() {
return this.toISO();
}
/**
* Returns an milliseconds value of this Duration.
* @return {number}
*/
toMillis() {
return this.as("milliseconds");
}
/**
* Returns an milliseconds value of this Duration. Alias of {@link toMillis}
* @return {number}
*/
valueOf() {
return this.toMillis();
}
/**
* Make this Duration longer by the specified amount. Return a newly-constructed Duration.
* @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
* @return {Duration}
*/
plus(duration) {
if (!this.isValid) return this;
const dur = friendlyDuration(duration),
result = {};
for (const k of orderedUnits) {
if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
result[k] = dur.get(k) + this.get(k);
}
}
return clone(this, { values: result }, true);
}
/**
* Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
* @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
* @return {Duration}
*/
minus(duration) {
if (!this.isValid) return this;
const dur = friendlyDuration(duration);
return this.plus(dur.negate());
}
/**
* Scale this Duration by the specified amount. Return a newly-constructed Duration.
* @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
* @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnit(x => x * 2) //=> { hours: 2, minutes: 60 }
* @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnit((x, u) => u === "hour" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
* @return {Duration}
*/
mapUnits(fn) {
if (!this.isValid) return this;
const result = {};
for (const k of Object.keys(this.values)) {
result[k] = asNumber(fn(this.values[k], k));
}
return clone(this, { values: result }, true);
}
/**
* Get the value of unit.
* @param {string} unit - a unit such as 'minute' or 'day'
* @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
* @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
* @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
* @return {number}
*/
get(unit) {
return this[Duration.normalizeUnit(unit)];
}
/**
* "Set" the values of specified units. Return a newly-constructed Duration.
* @param {Object} values - a mapping of units to numbers
* @example dur.set({ years: 2017 })
* @example dur.set({ hours: 8, minutes: 30 })
* @return {Duration}
*/
set(values) {
if (!this.isValid) return this;
const mixed = Object.assign(this.values, normalizeObject(values, Duration.normalizeUnit, []));
return clone(this, { values: mixed });
}
/**
* "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration.
* @example dur.reconfigure({ locale: 'en-GB' })
* @return {Duration}
*/
reconfigure({ locale, numberingSystem, conversionAccuracy } = {}) {
const loc = this.loc.clone({ locale, numberingSystem }),
opts = { loc };
if (conversionAccuracy) {
opts.conversionAccuracy = conversionAccuracy;
}
return clone(this, opts);
}
/**
* Return the length of the duration in the specified unit.
* @param {string} unit - a unit such as 'minutes' or 'days'
* @example Duration.fromObject({years: 1}).as('days') //=> 365
* @example Duration.fromObject({years: 1}).as('months') //=> 12
* @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
* @return {number}
*/
as(unit) {
return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
}
/**
* Reduce this Duration to its canonical representation in its current units.
* @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
* @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
* @return {Duration}
*/
normalize() {
if (!this.isValid) return this;
const vals = this.toObject();
normalizeValues(this.matrix, vals);
return clone(this, { values: vals }, true);
}
/**
* Convert this Duration into its representation in a different set of units.
* @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
* @return {Duration}
*/
shiftTo(...units) {
if (!this.isValid) return this;
if (units.length === 0) {
return this;
}
units = units.map(u => Duration.normalizeUnit(u));
const built = {},
accumulated = {},
vals = this.toObject();
let lastUnit;
for (const k of orderedUnits) {
if (units.indexOf(k) >= 0) {
lastUnit = k;
let own = 0;
// anything we haven't boiled down yet should get boiled to this unit
for (const ak in accumulated) {
own += this.matrix[ak][k] * accumulated[ak];
accumulated[ak] = 0;
}
// plus anything that's already in this unit
if (isNumber(vals[k])) {
own += vals[k];
}
const i = Math.trunc(own);
built[k] = i;
accumulated[k] = own - i; // we'd like to absorb these fractions in another unit
// plus anything further down the chain that should be rolled up in to this
for (const down in vals) {
if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) {
convert(this.matrix, vals, down, built, k);
}
}
// otherwise, keep it in the wings to boil it later
} else if (isNumber(vals[k])) {
accumulated[k] = vals[k];
}
}
// anything leftover becomes the decimal for the last unit
// lastUnit must be defined since units is not empty
for (const key in accumulated) {
if (accumulated[key] !== 0) {
built[lastUnit] +=
key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
}
}
return clone(this, { values: built }, true).normalize();
}
/**
* Return the negative of this Duration.
* @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
* @return {Duration}
*/
negate() {
if (!this.isValid) return this;
const negated = {};
for (const k of Object.keys(this.values)) {
negated[k] = -this.values[k];
}
return clone(this, { values: negated }, true);
}
/**
* Get the years.
* @type {number}
*/
get years() {
return this.isValid ? this.values.years || 0 : NaN;
}
/**
* Get the quarters.
* @type {number}
*/
get quarters() {
return this.isValid ? this.values.quarters || 0 : NaN;
}
/**
* Get the months.
* @type {number}
*/
get months() {
return this.isValid ? this.values.months || 0 : NaN;
}
/**
* Get the weeks
* @type {number}
*/
get weeks() {
return this.isValid ? this.values.weeks || 0 : NaN;
}
/**
* Get the days.
* @type {number}
*/
get days() {
return this.isValid ? this.values.days || 0 : NaN;
}
/**
* Get the hours.
* @type {number}
*/
get hours() {
return this.isValid ? this.values.hours || 0 : NaN;
}
/**
* Get the minutes.
* @type {number}
*/
get minutes() {
return this.isValid ? this.values.minutes || 0 : NaN;
}
/**
* Get the seconds.
* @return {number}
*/
get seconds() {
return this.isValid ? this.values.seconds || 0 : NaN;
}
/**
* Get the milliseconds.
* @return {number}
*/
get milliseconds() {
return this.isValid ? this.values.milliseconds || 0 : NaN;
}
/**
* Returns whether the Duration is invalid. Invalid durations are returned by diff operations
* on invalid DateTimes or Intervals.
* @return {boolean}
*/
get isValid() {
return this.invalid === null;
}
/**
* Returns an error code if this Duration became invalid, or null if the Duration is valid
* @return {string}
*/
get invalidReason() {
return this.invalid ? this.invalid.reason : null;
}
/**
* Returns an explanation of why this Duration became invalid, or null if the Duration is valid
* @type {string}
*/
get invalidExplanation() {
return this.invalid ? this.invalid.explanation : null;
}
/**
* Equality check
* Two Durations are equal iff they have the same units and the same values for each unit.
* @param {Duration} other
* @return {boolean}
*/
equals(other) {
if (!this.isValid || !other.isValid) {
return false;
}
if (!this.loc.equals(other.loc)) {
return false;
}
function eq(v1, v2) {
// Consider 0 and undefined as equal
if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;
return v1 === v2;
}
for (const u of orderedUnits) {
if (!eq(this.values[u], other.values[u])) {
return false;
}
}
return true;
}
}
/**
* @private
*/
export function friendlyDuration(durationish) {
if (isNumber(durationish)) {
return Duration.fromMillis(durationish);
} else if (Duration.isDuration(durationish)) {
return durationish;
} else if (typeof durationish === "object") {
return Duration.fromObject(durationish);
} else {
throw new InvalidArgumentError(
`Unknown duration argument ${durationish} of type ${typeof durationish}`
);
}
}
// these aren't really private, but nor are they really useful to document
/**
* @private
*/
class LuxonError extends Error {}
/**
* @private
*/
export class InvalidDateTimeError extends LuxonError {
constructor(reason) {
super(`Invalid DateTime: ${reason.toMessage()}`);
}
}
/**
* @private
*/
export class InvalidIntervalError extends LuxonError {
constructor(reason) {
super(`Invalid Interval: ${reason.toMessage()}`);
}
}
/**
* @private
*/
export class InvalidDurationError extends LuxonError {
constructor(reason) {
super(`Invalid Duration: ${reason.toMessage()}`);
}
}
/**
* @private
*/
export class ConflictingSpecificationError extends LuxonError {}
/**
* @private
*/
export class InvalidUnitError extends LuxonError {
constructor(unit) {
super(`Invalid unit ${unit}`);
}
}
/**
* @private
*/
export class InvalidArgumentError extends LuxonError {}
/**
* @private
*/
export class ZoneIsAbstractError extends LuxonError {
constructor() {
super("Zone is an abstract class");
}
}
import {
integerBetween,
isLeapYear,
timeObject,
daysInYear,
daysInMonth,
weeksInWeekYear,
isInteger
} from "./util.js";
import Invalid from "./invalid.js";
const nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
function unitOutOfRange(unit, value) {
return new Invalid(
"unit out of range",
`you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`
);
}
function dayOfWeek(year, month, day) {
const js = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
return js === 0 ? 7 : js;
}
function computeOrdinal(year, month, day) {
return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];
}
function uncomputeOrdinal(year, ordinal) {
const table = isLeapYear(year) ? leapLadder : nonLeapLadder,
month0 = table.findIndex(i => i < ordinal),
day = ordinal - table[month0];
return { month: month0 + 1, day };
}
/**
* @private
*/
export function gregorianToWeek(gregObj) {
const { year, month, day } = gregObj,
ordinal = computeOrdinal(year, month, day),
weekday = dayOfWeek(year, month, day);
let weekNumber = Math.floor((ordinal - weekday + 10) / 7),
weekYear;
if (weekNumber < 1) {
weekYear = year - 1;
weekNumber = weeksInWeekYear(weekYear);
} else if (weekNumber > weeksInWeekYear(year)) {
weekYear = year + 1;
weekNumber = 1;
} else {
weekYear = year;
}
return Object.assign({ weekYear, weekNumber, weekday }, timeObject(gregObj));
}
export function weekToGregorian(weekData) {
const { weekYear, weekNumber, weekday } = weekData,
weekdayOfJan4 = dayOfWeek(weekYear, 1, 4),
yearInDays = daysInYear(weekYear);
let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3,
year;
if (ordinal < 1) {
year = weekYear - 1;
ordinal += daysInYear(year);
} else if (ordinal > yearInDays) {
year = weekYear + 1;
ordinal -= daysInYear(weekYear);
} else {
year = weekYear;
}
const { month, day } = uncomputeOrdinal(year, ordinal);
return Object.assign({ year, month, day }, timeObject(weekData));
}
export function gregorianToOrdinal(gregData) {
const { year, month, day } = gregData,
ordinal = computeOrdinal(year, month, day);
return Object.assign({ year, ordinal }, timeObject(gregData));
}
export function ordinalToGregorian(ordinalData) {
const { year, ordinal } = ordinalData,
{ month, day } = uncomputeOrdinal(year, ordinal);
return Object.assign({ year, month, day }, timeObject(ordinalData));
}
export function hasInvalidWeekData(obj) {
const validYear = isInteger(obj.weekYear),
validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)),
validWeekday = integerBetween(obj.weekday, 1, 7);
if (!validYear) {
return unitOutOfRange("weekYear", obj.weekYear);
} else if (!validWeek) {
return unitOutOfRange("week", obj.week);
} else if (!validWeekday) {
return unitOutOfRange("weekday", obj.weekday);
} else return false;
}
export function hasInvalidOrdinalData(obj) {
const validYear = isInteger(obj.year),
validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));
if (!validYear) {
return unitOutOfRange("year", obj.year);
} else if (!validOrdinal) {
return unitOutOfRange("ordinal", obj.ordinal);
} else return false;
}
export function hasInvalidGregorianData(obj) {
const validYear = isInteger(obj.year),
validMonth = integerBetween(obj.month, 1, 12),
validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));
if (!validYear) {
return unitOutOfRange("year", obj.year);
} else if (!validMonth) {
return unitOutOfRange("month", obj.month);
} else if (!validDay) {
return unitOutOfRange("day", obj.day);
} else return false;
}
export function hasInvalidTimeData(obj) {
const { hour, minute, second, millisecond } = obj;
const validHour =
integerBetween(hour, 0, 23) ||
(hour === 24 && minute === 0 && second === 0 && millisecond === 0),
validMinute = integerBetween(minute, 0, 59),
validSecond = integerBetween(second, 0, 59),
validMillisecond = integerBetween(millisecond, 0, 999);
if (!validHour) {
return unitOutOfRange("hour", hour);
} else if (!validMinute) {
return unitOutOfRange("minute", minute);
} else if (!validSecond) {
return unitOutOfRange("second", second);
} else if (!validMillisecond) {
return unitOutOfRange("millisecond", millisecond);
} else return false;
}
import Duration from "../duration.js";
function dayDiff(earlier, later) {
const utcDayStart = dt =>
dt
.toUTC(0, { keepLocalTime: true })
.startOf("day")
.valueOf(),
ms = utcDayStart(later) - utcDayStart(earlier);
return Math.floor(Duration.fromMillis(ms).as("days"));
}
function highOrderDiffs(cursor, later, units) {
const differs = [
["years", (a, b) => b.year - a.year],
["quarters", (a, b) => b.quarter - a.quarter],
["months", (a, b) => b.month - a.month + (b.year - a.year) * 12],
[
"weeks",
(a, b) => {
const days = dayDiff(a, b);
return (days - (days % 7)) / 7;
}
],
["days", dayDiff]
];
const results = {};
let lowestOrder, highWater;
for (const [unit, differ] of differs) {
if (units.indexOf(unit) >= 0) {
lowestOrder = unit;
let delta = differ(cursor, later);
highWater = cursor.plus({ [unit]: delta });
if (highWater > later) {
cursor = cursor.plus({ [unit]: delta - 1 });
delta -= 1;
} else {
cursor = highWater;
}
results[unit] = delta;
}
}
return [cursor, results, highWater, lowestOrder];
}
export default function(earlier, later, units, opts) {
let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);
const remainingMillis = later - cursor;
const lowerOrderUnits = units.filter(
u => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0
);
if (lowerOrderUnits.length === 0) {
if (highWater < later) {
highWater = cursor.plus({ [lowestOrder]: 1 });
}
if (highWater !== cursor) {
results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);
}
}
const duration = Duration.fromObject(Object.assign(results, opts));
if (lowerOrderUnits.length > 0) {
return Duration.fromMillis(remainingMillis, opts)
.shiftTo(...lowerOrderUnits)
.plus(duration);
} else {
return duration;
}
}
const numberingSystems = {
arab: "[\u0660-\u0669]",
arabext: "[\u06F0-\u06F9]",
bali: "[\u1B50-\u1B59]",
beng: "[\u09E6-\u09EF]",
deva: "[\u0966-\u096F]",
fullwide: "[\uFF10-\uFF19]",
gujr: "[\u0AE6-\u0AEF]",
hanidec: "[〇|一|二|三|四|五|六|七|八|九]",
khmr: "[\u17E0-\u17E9]",
knda: "[\u0CE6-\u0CEF]",
laoo: "[\u0ED0-\u0ED9]",
limb: "[\u1946-\u194F]",
mlym: "[\u0D66-\u0D6F]",
mong: "[\u1810-\u1819]",
mymr: "[\u1040-\u1049]",
orya: "[\u0B66-\u0B6F]",
tamldec: "[\u0BE6-\u0BEF]",
telu: "[\u0C66-\u0C6F]",
thai: "[\u0E50-\u0E59]",
tibt: "[\u0F20-\u0F29]",
latn: "\\d"
};
const numberingSystemsUTF16 = {
arab: [1632, 1641],
arabext: [1776, 1785],
bali: [6992, 7001],
beng: [2534, 2543],
deva: [2406, 2415],
fullwide: [65296, 65303],
gujr: [2790, 2799],
khmr: [6112, 6121],
knda: [3302, 3311],
laoo: [3792, 3801],
limb: [6470, 6479],
mlym: [3430, 3439],
mong: [6160, 6169],
mymr: [4160, 4169],
orya: [2918, 2927],
tamldec: [3046, 3055],
telu: [3174, 3183],
thai: [3664, 3673],
tibt: [3872, 3881]
};
// eslint-disable-next-line
const hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split("");
export function parseDigits(str) {
let value = parseInt(str, 10);
if (isNaN(value)) {
value = "";
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (str[i].search(numberingSystems.hanidec) !== -1) {
value += hanidecChars.indexOf(str[i]);
} else {
for (const key in numberingSystemsUTF16) {
const [min, max] = numberingSystemsUTF16[key];
if (code >= min && code <= max) {
value += code - min;
}
}
}
}
return parseInt(value, 10);
} else {
return value;
}
}
export function digitRegex({ numberingSystem }, append = "") {
return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append}`);
}
import * as Formats from "./formats.js";
import { pick } from "./util.js";
function stringify(obj) {
return JSON.stringify(obj, Object.keys(obj).sort());
}
/**
* @private
*/
export const monthsLong = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
export const monthsShort = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
export const monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
export function months(length) {
switch (length) {
case "narrow":
return [...monthsNarrow];
case "short":
return [...monthsShort];
case "long":
return [...monthsLong];
case "numeric":
return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
case "2-digit":
return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
default:
return null;
}
}
export const weekdaysLong = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
];
export const weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
export const weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"];
export function weekdays(length) {
switch (length) {
case "narrow":
return [...weekdaysNarrow];
case "short":
return [...weekdaysShort];
case "long":
return [...weekdaysLong];
case "numeric":
return ["1", "2", "3", "4", "5", "6", "7"];
default:
return null;
}
}
export const meridiems = ["AM", "PM"];
export const erasLong = ["Before Christ", "Anno Domini"];
export const erasShort = ["BC", "AD"];
export const erasNarrow = ["B", "A"];
export function eras(length) {
switch (length) {
case "narrow":
return [...erasNarrow];
case "short":
return [...erasShort];
case "long":
return [...erasLong];
default:
return null;
}
}
export function meridiemForDateTime(dt) {
return meridiems[dt.hour < 12 ? 0 : 1];
}
export function weekdayForDateTime(dt, length) {
return weekdays(length)[dt.weekday - 1];
}
export function monthForDateTime(dt, length) {
return months(length)[dt.month - 1];
}
export function eraForDateTime(dt, length) {
return eras(length)[dt.year < 0 ? 0 : 1];
}
export function formatRelativeTime(unit, count, numeric = "always", narrow = false) {
const units = {
years: ["year", "yr."],
quarters: ["quarter", "qtr."],
months: ["month", "mo."],
weeks: ["week", "wk."],
days: ["day", "day", "days"],
hours: ["hour", "hr."],
minutes: ["minute", "min."],
seconds: ["second", "sec."]
};
const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1;
if (numeric === "auto" && lastable) {
const isDay = unit === "days";
switch (count) {
case 1:
return isDay ? "tomorrow" : `next ${units[unit][0]}`;
case -1:
return isDay ? "yesterday" : `last ${units[unit][0]}`;
case 0:
return isDay ? "today" : `this ${units[unit][0]}`;
default: // fall through
}
}
const isInPast = Object.is(count, -0) || count < 0,
fmtValue = Math.abs(count),
singular = fmtValue === 1,
lilUnits = units[unit],
fmtUnit = narrow
? singular
? lilUnits[1]
: lilUnits[2] || lilUnits[1]
: singular
? units[unit][0]
: unit;
return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;
}
export function formatString(knownFormat) {
// these all have the offsets removed because we don't have access to them
// without all the intl stuff this is backfilling
const filtered = pick(knownFormat, [
"weekday",
"era",
"year",
"month",
"day",
"hour",
"minute",
"second",
"timeZoneName",
"hour12"
]),
key = stringify(filtered),
dateTimeHuge = "EEEE, LLLL d, yyyy, h:mm a";
switch (key) {
case stringify(Formats.DATE_SHORT):
return "M/d/yyyy";
case stringify(Formats.DATE_MED):
return "LLL d, yyyy";
case stringify(Formats.DATE_MED_WITH_WEEKDAY):
return "EEE, LLL d, yyyy";
case stringify(Formats.DATE_FULL):
return "LLLL d, yyyy";
case stringify(Formats.DATE_HUGE):
return "EEEE, LLLL d, yyyy";
case stringify(Formats.TIME_SIMPLE):
return "h:mm a";
case stringify(Formats.TIME_WITH_SECONDS):
return "h:mm:ss a";
case stringify(Formats.TIME_WITH_SHORT_OFFSET):
return "h:mm a";
case stringify(Formats.TIME_WITH_LONG_OFFSET):
return "h:mm a";
case stringify(Formats.TIME_24_SIMPLE):
return "HH:mm";
case stringify(Formats.TIME_24_WITH_SECONDS):
return "HH:mm:ss";
case stringify(Formats.TIME_24_WITH_SHORT_OFFSET):
return "HH:mm";
case stringify(Formats.TIME_24_WITH_LONG_OFFSET):
return "HH:mm";
case stringify(Formats.DATETIME_SHORT):
return "M/d/yyyy, h:mm a";
case stringify(Formats.DATETIME_MED):
return "LLL d, yyyy, h:mm a";
case stringify(Formats.DATETIME_FULL):
return "LLLL d, yyyy, h:mm a";
case stringify(Formats.DATETIME_HUGE):
return dateTimeHuge;
case stringify(Formats.DATETIME_SHORT_WITH_SECONDS):
return "M/d/yyyy, h:mm:ss a";
case stringify(Formats.DATETIME_MED_WITH_SECONDS):
return "LLL d, yyyy, h:mm:ss a";
case stringify(Formats.DATETIME_MED_WITH_WEEKDAY):
return "EEE, d LLL yyyy, h:mm a";
case stringify(Formats.DATETIME_FULL_WITH_SECONDS):
return "LLLL d, yyyy, h:mm:ss a";
case stringify(Formats.DATETIME_HUGE_WITH_SECONDS):
return "EEEE, LLLL d, yyyy, h:mm:ss a";
default:
return dateTimeHuge;
}
}
/**
* @private
*/
const n = "numeric",
s = "short",
l = "long";
export const DATE_SHORT = {
year: n,
month: n,
day: n
};
export const DATE_MED = {
year: n,
month: s,
day: n
};
export const DATE_MED_WITH_WEEKDAY = {
year: n,
month: s,
day: n,
weekday: s
};
export const DATE_FULL = {
year: n,
month: l,
day: n
};
export const DATE_HUGE = {
year: n,
month: l,
day: n,
weekday: l
};
export const TIME_SIMPLE = {
hour: n,
minute: n
};
export const TIME_WITH_SECONDS = {
hour: n,
minute: n,
second: n
};
export const TIME_WITH_SHORT_OFFSET = {
hour: n,
minute: n,
second: n,
timeZoneName: s
};
export const TIME_WITH_LONG_OFFSET = {
hour: n,
minute: n,
second: n,
timeZoneName: l
};
export const TIME_24_SIMPLE = {
hour: n,
minute: n,
hour12: false
};
/**
* {@link toLocaleString}; format like '09:30:23', always 24-hour.
*/
export const TIME_24_WITH_SECONDS = {
hour: n,
minute: n,
second: n,
hour12: false
};
/**
* {@link toLocaleString}; format like '09:30:23 EDT', always 24-hour.
*/
export const TIME_24_WITH_SHORT_OFFSET = {
hour: n,
minute: n,
second: n,
hour12: false,
timeZoneName: s
};
/**
* {@link toLocaleString}; format like '09:30:23 Eastern Daylight Time', always 24-hour.
*/
export const TIME_24_WITH_LONG_OFFSET = {
hour: n,
minute: n,
second: n,
hour12: false,
timeZoneName: l
};
/**
* {@link toLocaleString}; format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
*/
export const DATETIME_SHORT = {
year: n,
month: n,
day: n,
hour: n,
minute: n
};
/**
* {@link toLocaleString}; format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
*/
export const DATETIME_SHORT_WITH_SECONDS = {
year: n,
month: n,
day: n,
hour: n,
minute: n,
second: n
};
export const DATETIME_MED = {
year: n,
month: s,
day: n,
hour: n,
minute: n
};
export const DATETIME_MED_WITH_SECONDS = {
year: n,
month: s,
day: n,
hour: n,
minute: n,
second: n
};
export const DATETIME_MED_WITH_WEEKDAY = {
year: n,
month: s,
day: n,
weekday: s,
hour: n,
minute: n
};
export const DATETIME_FULL = {
year: n,
month: l,
day: n,
hour: n,
minute: n,
timeZoneName: s
};
export const DATETIME_FULL_WITH_SECONDS = {
year: n,
month: l,
day: n,
hour: n,
minute: n,
second: n,
timeZoneName: s
};
export const DATETIME_HUGE = {
year: n,
month: l,
day: n,
weekday: l,
hour: n,
minute: n,
timeZoneName: l
};
export const DATETIME_HUGE_WITH_SECONDS = {
year: n,
month: l,
day: n,
weekday: l,
hour: n,
minute: n,
second: n,
timeZoneName: l
};
import * as English from "./english.js";
import * as Formats from "./formats.js";
import { hasFormatToParts, padStart } from "./util.js";
function stringifyTokens(splits, tokenToString) {
let s = "";
for (const token of splits) {
if (token.literal) {
s += token.val;
} else {
s += tokenToString(token.val);
}
}
return s;
}
const macroTokenToFormatOpts = {
D: Formats.DATE_SHORT,
DD: Formats.DATE_MED,
DDD: Formats.DATE_FULL,
DDDD: Formats.DATE_HUGE,
t: Formats.TIME_SIMPLE,
tt: Formats.TIME_WITH_SECONDS,
ttt: Formats.TIME_WITH_SHORT_OFFSET,
tttt: Formats.TIME_WITH_LONG_OFFSET,
T: Formats.TIME_24_SIMPLE,
TT: Formats.TIME_24_WITH_SECONDS,
TTT: Formats.TIME_24_WITH_SHORT_OFFSET,
TTTT: Formats.TIME_24_WITH_LONG_OFFSET,
f: Formats.DATETIME_SHORT,
ff: Formats.DATETIME_MED,
fff: Formats.DATETIME_FULL,
ffff: Formats.DATETIME_HUGE,
F: Formats.DATETIME_SHORT_WITH_SECONDS,
FF: Formats.DATETIME_MED_WITH_SECONDS,
FFF: Formats.DATETIME_FULL_WITH_SECONDS,
FFFF: Formats.DATETIME_HUGE_WITH_SECONDS
};
/**
* @private
*/
export default class Formatter {
static create(locale, opts = {}) {
return new Formatter(locale, opts);
}
static parseFormat(fmt) {
let current = null,
currentFull = "",
bracketed = false;
const splits = [];
for (let i = 0; i < fmt.length; i++) {
const c = fmt.charAt(i);
if (c === "'") {
if (currentFull.length > 0) {
splits.push({ literal: bracketed, val: currentFull });
}
current = null;
currentFull = "";
bracketed = !bracketed;
} else if (bracketed) {
currentFull += c;
} else if (c === current) {
currentFull += c;
} else {
if (currentFull.length > 0) {
splits.push({ literal: false, val: currentFull });
}
currentFull = c;
current = c;
}
}
if (currentFull.length > 0) {
splits.push({ literal: bracketed, val: currentFull });
}
return splits;
}
static macroTokenToFormatOpts(token) {
return macroTokenToFormatOpts[token];
}
constructor(locale, formatOpts) {
this.opts = formatOpts;
this.loc = locale;
this.systemLoc = null;
}
formatWithSystemDefault(dt, opts) {
if (this.systemLoc === null) {
this.systemLoc = this.loc.redefaultToSystem();
}
const df = this.systemLoc.dtFormatter(dt, Object.assign({}, this.opts, opts));
return df.format();
}
formatDateTime(dt, opts = {}) {
const df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts));
return df.format();
}
formatDateTimeParts(dt, opts = {}) {
const df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts));
return df.formatToParts();
}
resolvedOptions(dt, opts = {}) {
const df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts));
return df.resolvedOptions();
}
num(n, p = 0) {
// we get some perf out of doing this here, annoyingly
if (this.opts.forceSimple) {
return padStart(n, p);
}
const opts = Object.assign({}, this.opts);
if (p > 0) {
opts.padTo = p;
}
return this.loc.numberFormatter(opts).format(n);
}
formatDateTimeFromString(dt, fmt) {
const knownEnglish = this.loc.listingMode() === "en",
useDateTimeFormatter =
this.loc.outputCalendar && this.loc.outputCalendar !== "gregory" && hasFormatToParts(),
string = (opts, extract) => this.loc.extract(dt, opts, extract),
formatOffset = opts => {
if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {
return "Z";
}
return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : "";
},
meridiem = () =>
knownEnglish
? English.meridiemForDateTime(dt)
: string({ hour: "numeric", hour12: true }, "dayperiod"),
month = (length, standalone) =>
knownEnglish
? English.monthForDateTime(dt, length)
: string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"),
weekday = (length, standalone) =>
knownEnglish
? English.weekdayForDateTime(dt, length)
: string(
standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" },
"weekday"
),
maybeMacro = token => {
const formatOpts = Formatter.macroTokenToFormatOpts(token);
if (formatOpts) {
return this.formatWithSystemDefault(dt, formatOpts);
} else {
return token;
}
},
era = length =>
knownEnglish ? English.eraForDateTime(dt, length) : string({ era: length }, "era"),
tokenToString = token => {
// Where possible: http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles
switch (token) {
// ms
case "S":
return this.num(dt.millisecond);
case "u":
// falls through
case "SSS":
return this.num(dt.millisecond, 3);
// seconds
case "s":
return this.num(dt.second);
case "ss":
return this.num(dt.second, 2);
// minutes
case "m":
return this.num(dt.minute);
case "mm":
return this.num(dt.minute, 2);
// hours
case "h":
return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);
case "hh":
return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);
case "H":
return this.num(dt.hour);
case "HH":
return this.num(dt.hour, 2);
// offset
case "Z":
// like +6
return formatOffset({ format: "narrow", allowZ: this.opts.allowZ });
case "ZZ":
// like +06:00
return formatOffset({ format: "short", allowZ: this.opts.allowZ });
case "ZZZ":
// like +0600
return formatOffset({ format: "techie", allowZ: this.opts.allowZ });
case "ZZZZ":
// like EST
return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale });
case "ZZZZZ":
// like Eastern Standard Time
return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale });
// zone
case "z":
// like America/New_York
return dt.zoneName;
// meridiems
case "a":
return meridiem();
// dates
case "d":
return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day);
case "dd":
return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2);
// weekdays - standalone
case "c":
// like 1
return this.num(dt.weekday);
case "ccc":
// like 'Tues'
return weekday("short", true);
case "cccc":
// like 'Tuesday'
return weekday("long", true);
case "ccccc":
// like 'T'
return weekday("narrow", true);
// weekdays - format
case "E":
// like 1
return this.num(dt.weekday);
case "EEE":
// like 'Tues'
return weekday("short", false);
case "EEEE":
// like 'Tuesday'
return weekday("long", false);
case "EEEEE":
// like 'T'
return weekday("narrow", false);
// months - standalone
case "L":
// like 1
return useDateTimeFormatter
? string({ month: "numeric", day: "numeric" }, "month")
: this.num(dt.month);
case "LL":
// like 01, doesn't seem to work
return useDateTimeFormatter
? string({ month: "2-digit", day: "numeric" }, "month")
: this.num(dt.month, 2);
case "LLL":
// like Jan
return month("short", true);
case "LLLL":
// like January
return month("long", true);
case "LLLLL":
// like J
return month("narrow", true);
// months - format
case "M":
// like 1
return useDateTimeFormatter
? string({ month: "numeric" }, "month")
: this.num(dt.month);
case "MM":
// like 01
return useDateTimeFormatter
? string({ month: "2-digit" }, "month")
: this.num(dt.month, 2);
case "MMM":
// like Jan
return month("short", false);
case "MMMM":
// like January
return month("long", false);
case "MMMMM":
// like J
return month("narrow", false);
// years
case "y":
// like 2014
return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year);
case "yy":
// like 14
return useDateTimeFormatter
? string({ year: "2-digit" }, "year")
: this.num(dt.year.toString().slice(-2), 2);
case "yyyy":
// like 0012
return useDateTimeFormatter
? string({ year: "numeric" }, "year")
: this.num(dt.year, 4);
case "yyyyyy":
// like 000012
return useDateTimeFormatter
? string({ year: "numeric" }, "year")
: this.num(dt.year, 6);
// eras
case "G":
// like AD
return era("short");
case "GG":
// like Anno Domini
return era("long");
case "GGGGG":
return era("narrow");
case "kk":
return this.num(dt.weekYear.toString().slice(-2), 2);
case "kkkk":
return this.num(dt.weekYear, 4);
case "W":
return this.num(dt.weekNumber);
case "WW":
return this.num(dt.weekNumber, 2);
case "o":
return this.num(dt.ordinal);
case "ooo":
return this.num(dt.ordinal, 3);
case "q":
// like 1
return this.num(dt.quarter);
case "qq":
// like 01
return this.num(dt.quarter, 2);
case "X":
return this.num(Math.floor(dt.ts / 1000));
case "x":
return this.num(dt.ts);
default:
return maybeMacro(token);
}
};
return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);
}
formatDurationFromString(dur, fmt) {
const tokenToField = token => {
switch (token[0]) {
case "S":
return "millisecond";
case "s":
return "second";
case "m":
return "minute";
case "h":
return "hour";
case "d":
return "day";
case "M":
return "month";
case "y":
return "year";
default:
return null;
}
},
tokenToString = lildur => token => {
const mapped = tokenToField(token);
if (mapped) {
return this.num(lildur.get(mapped), token.length);
} else {
return token;
}
},
tokens = Formatter.parseFormat(fmt),
realTokens = tokens.reduce(
(found, { literal, val }) => (literal ? found : found.concat(val)),
[]
),
collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter(t => t));
return stringifyTokens(tokens, tokenToString(collapsed));
}
}
export default class Invalid {
constructor(reason, explanation) {
this.reason = reason;
this.explanation = explanation;
}
toMessage() {
if (this.explanation) {
return `${this.reason}: ${this.explanation}`;
} else {
return this.reason;
}
}
}
import { hasFormatToParts, hasIntl, padStart, roundTo, hasRelative } from "./util.js";
import * as English from "./english.js";
import Settings from "../settings.js";
import DateTime from "../datetime.js";
import Formatter from "./formatter.js";
import IANAZone from "../zones/IANAZone.js";
let intlDTCache = {};
function getCachedDTF(locString, opts = {}) {
const key = JSON.stringify([locString, opts]);
let dtf = intlDTCache[key];
if (!dtf) {
dtf = new Intl.DateTimeFormat(locString, opts);
intlDTCache[key] = dtf;
}
return dtf;
}
let intlNumCache = {};
function getCachedINF(locString, opts = {}) {
const key = JSON.stringify([locString, opts]);
let inf = intlNumCache[key];
if (!inf) {
inf = new Intl.NumberFormat(locString, opts);
intlNumCache[key] = inf;
}
return inf;
}
let intlRelCache = {};
function getCachedRTF(locString, opts = {}) {
const { base, ...cacheKeyOpts } = opts; // exclude `base` from the options
const key = JSON.stringify([locString, cacheKeyOpts]);
let inf = intlRelCache[key];
if (!inf) {
inf = new Intl.RelativeTimeFormat(locString, opts);
intlRelCache[key] = inf;
}
return inf;
}
let sysLocaleCache = null;
function systemLocale() {
if (sysLocaleCache) {
return sysLocaleCache;
} else if (hasIntl()) {
const computedSys = new Intl.DateTimeFormat().resolvedOptions().locale;
// node sometimes defaults to "und". Override that because that is dumb
sysLocaleCache = !computedSys || computedSys === "und" ? "en-US" : computedSys;
return sysLocaleCache;
} else {
sysLocaleCache = "en-US";
return sysLocaleCache;
}
}
function parseLocaleString(localeStr) {
// I really want to avoid writing a BCP 47 parser
// see, e.g. https://github.com/wooorm/bcp-47
// Instead, we'll do this:
// a) if the string has no -u extensions, just leave it alone
// b) if it does, use Intl to resolve everything
// c) if Intl fails, try again without the -u
const uIndex = localeStr.indexOf("-u-");
if (uIndex === -1) {
return [localeStr];
} else {
let options;
const smaller = localeStr.substring(0, uIndex);
try {
options = getCachedDTF(localeStr).resolvedOptions();
} catch (e) {
options = getCachedDTF(smaller).resolvedOptions();
}
const { numberingSystem, calendar } = options;
// return the smaller one so that we can append the calendar and numbering overrides to it
return [smaller, numberingSystem, calendar];
}
}
function intlConfigString(localeStr, numberingSystem, outputCalendar) {
if (hasIntl()) {
if (outputCalendar || numberingSystem) {
localeStr += "-u";
if (outputCalendar) {
localeStr += `-ca-${outputCalendar}`;
}
if (numberingSystem) {
localeStr += `-nu-${numberingSystem}`;
}
return localeStr;
} else {
return localeStr;
}
} else {
return [];
}
}
function mapMonths(f) {
const ms = [];
for (let i = 1; i <= 12; i++) {
const dt = DateTime.utc(2016, i, 1);
ms.push(f(dt));
}
return ms;
}
function mapWeekdays(f) {
const ms = [];
for (let i = 1; i <= 7; i++) {
const dt = DateTime.utc(2016, 11, 13 + i);
ms.push(f(dt));
}
return ms;
}
function listStuff(loc, length, defaultOK, englishFn, intlFn) {
const mode = loc.listingMode(defaultOK);
if (mode === "error") {
return null;
} else if (mode === "en") {
return englishFn(length);
} else {
return intlFn(length);
}
}
function supportsFastNumbers(loc) {
if (loc.numberingSystem && loc.numberingSystem !== "latn") {
return false;
} else {
return (
loc.numberingSystem === "latn" ||
!loc.locale ||
loc.locale.startsWith("en") ||
(hasIntl() && new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn")
);
}
}
/**
* @private
*/
class PolyNumberFormatter {
constructor(intl, forceSimple, opts) {
this.padTo = opts.padTo || 0;
this.floor = opts.floor || false;
if (!forceSimple && hasIntl()) {
const intlOpts = { useGrouping: false };
if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;
this.inf = getCachedINF(intl, intlOpts);
}
}
format(i) {
if (this.inf) {
const fixed = this.floor ? Math.floor(i) : i;
return this.inf.format(fixed);
} else {
// to match the browser's numberformatter defaults
const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);
return padStart(fixed, this.padTo);
}
}
}
/**
* @private
*/
class PolyDateFormatter {
constructor(dt, intl, opts) {
this.opts = opts;
this.hasIntl = hasIntl();
let z;
if (dt.zone.universal && this.hasIntl) {
// UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.
// That is why fixed-offset TZ is set to that unless it is:
// 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.
// 2. Unsupported by the browser:
// - some do not support Etc/
// - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata
const gmtOffset = -1 * (dt.offset / 60);
const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;
const isOffsetZoneSupported = IANAZone.isValidZone(offsetZ);
if (dt.offset !== 0 && isOffsetZoneSupported) {
z = offsetZ;
this.dt = dt;
} else {
// Not all fixed-offset zones like Etc/+4:30 are present in tzdata.
// So we have to make do. Two cases:
// 1. The format options tell us to show the zone. We can't do that, so the best
// we can do is format the date in UTC.
// 2. The format options don't tell us to show the zone. Then we can adjust them
// the time and tell the formatter to show it to us in UTC, so that the time is right
// and the bad zone doesn't show up.
z = "UTC";
if (opts.timeZoneName) {
this.dt = dt;
} else {
this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000);
}
}
} else if (dt.zone.type === "local") {
this.dt = dt;
} else {
this.dt = dt;
z = dt.zone.name;
}
if (this.hasIntl) {
const intlOpts = Object.assign({}, this.opts);
if (z) {
intlOpts.timeZone = z;
}
this.dtf = getCachedDTF(intl, intlOpts);
}
}
format() {
if (this.hasIntl) {
return this.dtf.format(this.dt.toJSDate());
} else {
const tokenFormat = English.formatString(this.opts),
loc = Locale.create("en-US");
return Formatter.create(loc).formatDateTimeFromString(this.dt, tokenFormat);
}
}
formatToParts() {
if (this.hasIntl && hasFormatToParts()) {
return this.dtf.formatToParts(this.dt.toJSDate());
} else {
// This is kind of a cop out. We actually could do this for English. However, we couldn't do it for intl strings
// and IMO it's too weird to have an uncanny valley like that
return [];
}
}
resolvedOptions() {
if (this.hasIntl) {
return this.dtf.resolvedOptions();
} else {
return {
locale: "en-US",
numberingSystem: "latn",
outputCalendar: "gregory"
};
}
}
}
/**
* @private
*/
class PolyRelFormatter {
constructor(intl, isEnglish, opts) {
this.opts = Object.assign({ style: "long" }, opts);
if (!isEnglish && hasRelative()) {
this.rtf = getCachedRTF(intl, opts);
}
}
format(count, unit) {
if (this.rtf) {
return this.rtf.format(count, unit);
} else {
return English.formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long");
}
}
formatToParts(count, unit) {
if (this.rtf) {
return this.rtf.formatToParts(count, unit);
} else {
return [];
}
}
}
/**
* @private
*/
export default class Locale {
static fromOpts(opts) {
return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);
}
static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {
const specifiedLocale = locale || Settings.defaultLocale,
// the system locale is useful for human readable strings but annoying for parsing/formatting known formats
localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()),
numberingSystemR = numberingSystem || Settings.defaultNumberingSystem,
outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);
}
static resetCache() {
sysLocaleCache = null;
intlDTCache = {};
intlNumCache = {};
intlRelCache = {};
}
static fromObject({ locale, numberingSystem, outputCalendar } = {}) {
return Locale.create(locale, numberingSystem, outputCalendar);
}
constructor(locale, numbering, outputCalendar, specifiedLocale) {
const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);
this.locale = parsedLocale;
this.numberingSystem = numbering || parsedNumberingSystem || null;
this.outputCalendar = outputCalendar || parsedOutputCalendar || null;
this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);
this.weekdaysCache = { format: {}, standalone: {} };
this.monthsCache = { format: {}, standalone: {} };
this.meridiemCache = null;
this.eraCache = {};
this.specifiedLocale = specifiedLocale;
this.fastNumbersCached = null;
}
get fastNumbers() {
if (this.fastNumbersCached == null) {
this.fastNumbersCached = supportsFastNumbers(this);
}
return this.fastNumbersCached;
}
listingMode(defaultOK = true) {
const intl = hasIntl(),
hasFTP = intl && hasFormatToParts(),
isActuallyEn = this.isEnglish(),
hasNoWeirdness =
(this.numberingSystem === null || this.numberingSystem === "latn") &&
(this.outputCalendar === null || this.outputCalendar === "gregory");
if (!hasFTP && !(isActuallyEn && hasNoWeirdness) && !defaultOK) {
return "error";
} else if (!hasFTP || (isActuallyEn && hasNoWeirdness)) {
return "en";
} else {
return "intl";
}
}
clone(alts) {
if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
return this;
} else {
return Locale.create(
alts.locale || this.specifiedLocale,
alts.numberingSystem || this.numberingSystem,
alts.outputCalendar || this.outputCalendar,
alts.defaultToEN || false
);
}
}
redefaultToEN(alts = {}) {
return this.clone(Object.assign({}, alts, { defaultToEN: true }));
}
redefaultToSystem(alts = {}) {
return this.clone(Object.assign({}, alts, { defaultToEN: false }));
}
months(length, format = false, defaultOK = true) {
return listStuff(this, length, defaultOK, English.months, () => {
const intl = format ? { month: length, day: "numeric" } : { month: length },
formatStr = format ? "format" : "standalone";
if (!this.monthsCache[formatStr][length]) {
this.monthsCache[formatStr][length] = mapMonths(dt => this.extract(dt, intl, "month"));
}
return this.monthsCache[formatStr][length];
});
}
weekdays(length, format = false, defaultOK = true) {
return listStuff(this, length, defaultOK, English.weekdays, () => {
const intl = format
? { weekday: length, year: "numeric", month: "long", day: "numeric" }
: { weekday: length },
formatStr = format ? "format" : "standalone";
if (!this.weekdaysCache[formatStr][length]) {
this.weekdaysCache[formatStr][length] = mapWeekdays(dt =>
this.extract(dt, intl, "weekday")
);
}
return this.weekdaysCache[formatStr][length];
});
}
meridiems(defaultOK = true) {
return listStuff(
this,
undefined,
defaultOK,
() => English.meridiems,
() => {
// In theory there could be aribitrary day periods. We're gonna assume there are exactly two
// for AM and PM. This is probably wrong, but it's makes parsing way easier.
if (!this.meridiemCache) {
const intl = { hour: "numeric", hour12: true };
this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(
dt => this.extract(dt, intl, "dayperiod")
);
}
return this.meridiemCache;
}
);
}
eras(length, defaultOK = true) {
return listStuff(this, length, defaultOK, English.eras, () => {
const intl = { era: length };
// This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates
// to definitely enumerate them.
if (!this.eraCache[length]) {
this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(dt =>
this.extract(dt, intl, "era")
);
}
return this.eraCache[length];
});
}
extract(dt, intlOpts, field) {
const df = this.dtFormatter(dt, intlOpts),
results = df.formatToParts(),
matching = results.find(m => m.type.toLowerCase() === field);
return matching ? matching.value : null;
}
numberFormatter(opts = {}) {
// this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)
// (in contrast, the rest of the condition is used heavily)
return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);
}
dtFormatter(dt, intlOpts = {}) {
return new PolyDateFormatter(dt, this.intl, intlOpts);
}
relFormatter(opts = {}) {
return new PolyRelFormatter(this.intl, this.isEnglish(), opts);
}
isEnglish() {
return (
this.locale === "en" ||
this.locale.toLowerCase() === "en-us" ||
(hasIntl() && new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us"))
);
}
equals(other) {
return (
this.locale === other.locale &&
this.numberingSystem === other.numberingSystem &&
this.outputCalendar === other.outputCalendar
);
}
}
import {
untruncateYear,
signedOffset,
parseInteger,
parseMillis,
ianaRegex,
isUndefined
} from "./util.js";
import * as English from "./english.js";
import FixedOffsetZone from "../zones/fixedOffsetZone.js";
import IANAZone from "../zones/IANAZone.js";
/*
* This file handles parsing for well-specified formats. Here's how it works:
* Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.
* An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object
* parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.
* Extractors can take a "cursor" representing the offset in the match to look at. This makes it easy to combine extractors.
* combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.
* Some extractions are super dumb and simpleParse and fromStrings help DRY them.
*/
function combineRegexes(...regexes) {
const full = regexes.reduce((f, r) => f + r.source, "");
return RegExp(`^${full}$`);
}
function combineExtractors(...extractors) {
return m =>
extractors
.reduce(
([mergedVals, mergedZone, cursor], ex) => {
const [val, zone, next] = ex(m, cursor);
return [Object.assign(mergedVals, val), mergedZone || zone, next];
},
[{}, null, 1]
)
.slice(0, 2);
}
function parse(s, ...patterns) {
if (s == null) {
return [null, null];
}
for (const [regex, extractor] of patterns) {
const m = regex.exec(s);
if (m) {
return extractor(m);
}
}
return [null, null];
}
function simpleParse(...keys) {
return (match, cursor) => {
const ret = {};
let i;
for (i = 0; i < keys.length; i++) {
ret[keys[i]] = parseInteger(match[cursor + i]);
}
return [ret, null, cursor + i];
};
}
// ISO and SQL parsing
const offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,
isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,
isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${offsetRegex.source}?`),
isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`),
isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,
isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/,
isoOrdinalRegex = /(\d{4})-?(\d{3})/,
extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"),
extractISOOrdinalData = simpleParse("year", "ordinal"),
sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/, // dumbed-down version of the ISO one
sqlTimeRegex = RegExp(
`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`
),
sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);
function int(match, pos, fallback) {
const m = match[pos];
return isUndefined(m) ? fallback : parseInteger(m);
}
function extractISOYmd(match, cursor) {
const item = {
year: int(match, cursor),
month: int(match, cursor + 1, 1),
day: int(match, cursor + 2, 1)
};
return [item, null, cursor + 3];
}
function extractISOTime(match, cursor) {
const item = {
hours: int(match, cursor, 0),
minutes: int(match, cursor + 1, 0),
seconds: int(match, cursor + 2, 0),
milliseconds: parseMillis(match[cursor + 3])
};
return [item, null, cursor + 4];
}
function extractISOOffset(match, cursor) {
const local = !match[cursor] && !match[cursor + 1],
fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),
zone = local ? null : FixedOffsetZone.instance(fullOffset);
return [{}, zone, cursor + 3];
}
function extractIANAZone(match, cursor) {
const zone = match[cursor] ? IANAZone.create(match[cursor]) : null;
return [{}, zone, cursor + 1];
}
// ISO time parsing
const isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);
// ISO duration parsing
const isoDuration = /^-?P(?:(?:(-?\d{1,9})Y)?(?:(-?\d{1,9})M)?(?:(-?\d{1,9})W)?(?:(-?\d{1,9})D)?(?:T(?:(-?\d{1,9})H)?(?:(-?\d{1,9})M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,9}))?S)?)?)$/;
function extractISODuration(match) {
const [
s,
yearStr,
monthStr,
weekStr,
dayStr,
hourStr,
minuteStr,
secondStr,
millisecondsStr
] = match;
const hasNegativePrefix = s[0] === "-";
const negativeSeconds = secondStr && secondStr[0] === "-";
const maybeNegate = (num, force = false) =>
num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num;
return [
{
years: maybeNegate(parseInteger(yearStr)),
months: maybeNegate(parseInteger(monthStr)),
weeks: maybeNegate(parseInteger(weekStr)),
days: maybeNegate(parseInteger(dayStr)),
hours: maybeNegate(parseInteger(hourStr)),
minutes: maybeNegate(parseInteger(minuteStr)),
seconds: maybeNegate(parseInteger(secondStr), secondStr === "-0"),
milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)
}
];
}
// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York
// and not just that we're in -240 *right now*. But since I don't think these are used that often
// I'm just going to ignore that
const obsOffsets = {
GMT: 0,
EDT: -4 * 60,
EST: -5 * 60,
CDT: -5 * 60,
CST: -6 * 60,
MDT: -6 * 60,
MST: -7 * 60,
PDT: -7 * 60,
PST: -8 * 60
};
function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
const result = {
year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),
month: English.monthsShort.indexOf(monthStr) + 1,
day: parseInteger(dayStr),
hour: parseInteger(hourStr),
minute: parseInteger(minuteStr)
};
if (secondStr) result.second = parseInteger(secondStr);
if (weekdayStr) {
result.weekday =
weekdayStr.length > 3
? English.weekdaysLong.indexOf(weekdayStr) + 1
: English.weekdaysShort.indexOf(weekdayStr) + 1;
}
return result;
}
// RFC 2822/5322
const rfc2822 = /^(?:(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\d)(\d\d)))$/;
function extractRFC2822(match) {
const [
,
weekdayStr,
dayStr,
monthStr,
yearStr,
hourStr,
minuteStr,
secondStr,
obsOffset,
milOffset,
offHourStr,
offMinuteStr
] = match,
result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
let offset;
if (obsOffset) {
offset = obsOffsets[obsOffset];
} else if (milOffset) {
offset = 0;
} else {
offset = signedOffset(offHourStr, offMinuteStr);
}
return [result, new FixedOffsetZone(offset)];
}
function preprocessRFC2822(s) {
// Remove comments and folding whitespace and replace multiple-spaces with a single space
return s
.replace(/\([^)]*\)|[\n\t]/g, " ")
.replace(/(\s\s+)/g, " ")
.trim();
}
// http date
const rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,
rfc850 = /^(Monday|Tuesday|Wedsday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,
ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;
function extractRFC1123Or850(match) {
const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match,
result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
return [result, FixedOffsetZone.utcInstance];
}
function extractASCII(match) {
const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match,
result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
return [result, FixedOffsetZone.utcInstance];
}
const isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);
const isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);
const isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);
const isoTimeCombinedRegex = combineRegexes(isoTimeRegex);
const extractISOYmdTimeAndOffset = combineExtractors(
extractISOYmd,
extractISOTime,
extractISOOffset
);
const extractISOWeekTimeAndOffset = combineExtractors(
extractISOWeekData,
extractISOTime,
extractISOOffset
);
const extractISOOrdinalDataAndTime = combineExtractors(extractISOOrdinalData, extractISOTime);
const extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset);
/**
* @private
*/
export function parseISODate(s) {
return parse(
s,
[isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],
[isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset],
[isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDataAndTime],
[isoTimeCombinedRegex, extractISOTimeAndOffset]
);
}
export function parseRFC2822Date(s) {
return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);
}
export function parseHTTPDate(s) {
return parse(
s,
[rfc1123, extractRFC1123Or850],
[rfc850, extractRFC1123Or850],
[ascii, extractASCII]
);
}
export function parseISODuration(s) {
return parse(s, [isoDuration, extractISODuration]);
}
const extractISOTimeOnly = combineExtractors(extractISOTime);
export function parseISOTimeOnly(s) {
return parse(s, [isoTimeOnly, extractISOTimeOnly]);
}
const sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);
const sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);
const extractISOYmdTimeOffsetAndIANAZone = combineExtractors(
extractISOYmd,
extractISOTime,
extractISOOffset,
extractIANAZone
);
const extractISOTimeOffsetAndIANAZone = combineExtractors(
extractISOTime,
extractISOOffset,
extractIANAZone
);
export function parseSQL(s) {
return parse(
s,
[sqlYmdWithTimeExtensionRegex, extractISOYmdTimeOffsetAndIANAZone],
[sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]
);
}
import { parseMillis, isUndefined, untruncateYear, signedOffset, hasOwnProperty } from "./util.js";
import Formatter from "./formatter.js";
import FixedOffsetZone from "../zones/fixedOffsetZone.js";
import IANAZone from "../zones/IANAZone.js";
import DateTime from "../datetime.js";
import { digitRegex, parseDigits } from "./digits.js";
import { ConflictingSpecificationError } from "../errors.js";
const MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support";
function intUnit(regex, post = i => i) {
return { regex, deser: ([s]) => post(parseDigits(s)) };
}
const NBSP = String.fromCharCode(160);
const spaceOrNBSP = `( |${NBSP})`;
const spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g");
function fixListRegex(s) {
// make dots optional and also make them literal
// make space and non breakable space characters interchangeable
return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP);
}
function stripInsensitivities(s) {
return s
.replace(/\./g, "") // ignore dots that were made optional
.replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp
.toLowerCase();
}
function oneOf(strings, startIndex) {
if (strings === null) {
return null;
} else {
return {
regex: RegExp(strings.map(fixListRegex).join("|")),
deser: ([s]) =>
strings.findIndex(i => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex
};
}
}
function offset(regex, groups) {
return { regex, deser: ([, h, m]) => signedOffset(h, m), groups };
}
function simple(regex) {
return { regex, deser: ([s]) => s };
}
function escapeToken(value) {
// eslint-disable-next-line no-useless-escape
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
function unitForToken(token, loc) {
const one = digitRegex(loc),
two = digitRegex(loc, "{2}"),
three = digitRegex(loc, "{3}"),
four = digitRegex(loc, "{4}"),
six = digitRegex(loc, "{6}"),
oneOrTwo = digitRegex(loc, "{1,2}"),
oneToThree = digitRegex(loc, "{1,3}"),
oneToSix = digitRegex(loc, "{1,6}"),
oneToNine = digitRegex(loc, "{1,9}"),
twoToFour = digitRegex(loc, "{2,4}"),
fourToSix = digitRegex(loc, "{4,6}"),
literal = t => ({ regex: RegExp(escapeToken(t.val)), deser: ([s]) => s, literal: true }),
unitate = t => {
if (token.literal) {
return literal(t);
}
switch (t.val) {
// era
case "G":
return oneOf(loc.eras("short", false), 0);
case "GG":
return oneOf(loc.eras("long", false), 0);
// years
case "y":
return intUnit(oneToSix);
case "yy":
return intUnit(twoToFour, untruncateYear);
case "yyyy":
return intUnit(four);
case "yyyyy":
return intUnit(fourToSix);
case "yyyyyy":
return intUnit(six);
// months
case "M":
return intUnit(oneOrTwo);
case "MM":
return intUnit(two);
case "MMM":
return oneOf(loc.months("short", true, false), 1);
case "MMMM":
return oneOf(loc.months("long", true, false), 1);
case "L":
return intUnit(oneOrTwo);
case "LL":
return intUnit(two);
case "LLL":
return oneOf(loc.months("short", false, false), 1);
case "LLLL":
return oneOf(loc.months("long", false, false), 1);
// dates
case "d":
return intUnit(oneOrTwo);
case "dd":
return intUnit(two);
// ordinals
case "o":
return intUnit(oneToThree);
case "ooo":
return intUnit(three);
// time
case "HH":
return intUnit(two);
case "H":
return intUnit(oneOrTwo);
case "hh":
return intUnit(two);
case "h":
return intUnit(oneOrTwo);
case "mm":
return intUnit(two);
case "m":
return intUnit(oneOrTwo);
case "q":
return intUnit(oneOrTwo);
case "qq":
return intUnit(two);
case "s":
return intUnit(oneOrTwo);
case "ss":
return intUnit(two);
case "S":
return intUnit(oneToThree);
case "SSS":
return intUnit(three);
case "u":
return simple(oneToNine);
// meridiem
case "a":
return oneOf(loc.meridiems(), 0);
// weekYear (k)
case "kkkk":
return intUnit(four);
case "kk":
return intUnit(twoToFour, untruncateYear);
// weekNumber (W)
case "W":
return intUnit(oneOrTwo);
case "WW":
return intUnit(two);
// weekdays
case "E":
case "c":
return intUnit(one);
case "EEE":
return oneOf(loc.weekdays("short", false, false), 1);
case "EEEE":
return oneOf(loc.weekdays("long", false, false), 1);
case "ccc":
return oneOf(loc.weekdays("short", true, false), 1);
case "cccc":
return oneOf(loc.weekdays("long", true, false), 1);
// offset/zone
case "Z":
case "ZZ":
return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);
case "ZZZ":
return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);
// we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing
// because we don't have any way to figure out what they are
case "z":
return simple(/[a-z_+-/]{1,256}?/i);
default:
return literal(t);
}
};
const unit = unitate(token) || {
invalidReason: MISSING_FTP
};
unit.token = token;
return unit;
}
const partTypeStyleToTokenVal = {
year: {
"2-digit": "yy",
numeric: "yyyyy"
},
month: {
numeric: "M",
"2-digit": "MM",
short: "MMM",
long: "MMMM"
},
day: {
numeric: "d",
"2-digit": "dd"
},
weekday: {
short: "EEE",
long: "EEEE"
},
dayperiod: "a",
dayPeriod: "a",
hour: {
numeric: "h",
"2-digit": "hh"
},
minute: {
numeric: "m",
"2-digit": "mm"
},
second: {
numeric: "s",
"2-digit": "ss"
}
};
function tokenForPart(part, locale, formatOpts) {
const { type, value } = part;
if (type === "literal") {
return {
literal: true,
val: value
};
}
const style = formatOpts[type];
let val = partTypeStyleToTokenVal[type];
if (typeof val === "object") {
val = val[style];
}
if (val) {
return {
literal: false,
val
};
}
return undefined;
}
function buildRegex(units) {
const re = units.map(u => u.regex).reduce((f, r) => `${f}(${r.source})`, "");
return [`^${re}$`, units];
}
function match(input, regex, handlers) {
const matches = input.match(regex);
if (matches) {
const all = {};
let matchIndex = 1;
for (const i in handlers) {
if (hasOwnProperty(handlers, i)) {
const h = handlers[i],
groups = h.groups ? h.groups + 1 : 1;
if (!h.literal && h.token) {
all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));
}
matchIndex += groups;
}
}
return [matches, all];
} else {
return [matches, {}];
}
}
function dateTimeFromMatches(matches) {
const toField = token => {
switch (token) {
case "S":
return "millisecond";
case "s":
return "second";
case "m":
return "minute";
case "h":
case "H":
return "hour";
case "d":
return "day";
case "o":
return "ordinal";
case "L":
case "M":
return "month";
case "y":
return "year";
case "E":
case "c":
return "weekday";
case "W":
return "weekNumber";
case "k":
return "weekYear";
case "q":
return "quarter";
default:
return null;
}
};
let zone;
if (!isUndefined(matches.Z)) {
zone = new FixedOffsetZone(matches.Z);
} else if (!isUndefined(matches.z)) {
zone = IANAZone.create(matches.z);
} else {
zone = null;
}
if (!isUndefined(matches.q)) {
matches.M = (matches.q - 1) * 3 + 1;
}
if (!isUndefined(matches.h)) {
if (matches.h < 12 && matches.a === 1) {
matches.h += 12;
} else if (matches.h === 12 && matches.a === 0) {
matches.h = 0;
}
}
if (matches.G === 0 && matches.y) {
matches.y = -matches.y;
}
if (!isUndefined(matches.u)) {
matches.S = parseMillis(matches.u);
}
const vals = Object.keys(matches).reduce((r, k) => {
const f = toField(k);
if (f) {
r[f] = matches[k];
}
return r;
}, {});
return [vals, zone];
}
let dummyDateTimeCache = null;
function getDummyDateTime() {
if (!dummyDateTimeCache) {
dummyDateTimeCache = DateTime.fromMillis(1555555555555);
}
return dummyDateTimeCache;
}
function maybeExpandMacroToken(token, locale) {
if (token.literal) {
return token;
}
const formatOpts = Formatter.macroTokenToFormatOpts(token.val);
if (!formatOpts) {
return token;
}
const formatter = Formatter.create(locale, formatOpts);
const parts = formatter.formatDateTimeParts(getDummyDateTime());
const tokens = parts.map(p => tokenForPart(p, locale, formatOpts));
if (tokens.includes(undefined)) {
return token;
}
return tokens;
}
function expandMacroTokens(tokens, locale) {
return Array.prototype.concat(...tokens.map(t => maybeExpandMacroToken(t, locale)));
}
/**
* @private
*/
export function explainFromTokens(locale, input, format) {
const tokens = expandMacroTokens(Formatter.parseFormat(format), locale),
units = tokens.map(t => unitForToken(t, locale)),
disqualifyingUnit = units.find(t => t.invalidReason);
if (disqualifyingUnit) {
return { input, tokens, invalidReason: disqualifyingUnit.invalidReason };
} else {
const [regexString, handlers] = buildRegex(units),
regex = RegExp(regexString, "i"),
[rawMatches, matches] = match(input, regex, handlers),
[result, zone] = matches ? dateTimeFromMatches(matches) : [null, null];
if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
throw new ConflictingSpecificationError(
"Can't include meridiem when specifying 24-hour format"
);
}
return { input, tokens, regex, rawMatches, matches, result, zone };
}
}
export function parseFromTokens(locale, input, format) {
const { result, zone, invalidReason } = explainFromTokens(locale, input, format);
return [result, zone, invalidReason];
}
/*
This is just a junk drawer, containing anything used across multiple classes.
Because Luxon is small(ish), this should stay small and we won't worry about splitting
it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area.
*/
import { InvalidArgumentError } from "../errors.js";
/**
* @private
*/
// TYPES
export function isUndefined(o) {
return typeof o === "undefined";
}
export function isNumber(o) {
return typeof o === "number";
}
export function isInteger(o) {
return typeof o === "number" && o % 1 === 0;
}
export function isString(o) {
return typeof o === "string";
}
export function isDate(o) {
return Object.prototype.toString.call(o) === "[object Date]";
}
// CAPABILITIES
export function hasIntl() {
try {
return typeof Intl !== "undefined" && Intl.DateTimeFormat;
} catch (e) {
return false;
}
}
export function hasFormatToParts() {
return !isUndefined(Intl.DateTimeFormat.prototype.formatToParts);
}
export function hasRelative() {
try {
return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat;
} catch (e) {
return false;
}
}
// OBJECTS AND ARRAYS
export function maybeArray(thing) {
return Array.isArray(thing) ? thing : [thing];
}
export function bestBy(arr, by, compare) {
if (arr.length === 0) {
return undefined;
}
return arr.reduce((best, next) => {
const pair = [by(next), next];
if (!best) {
return pair;
} else if (compare(best[0], pair[0]) === best[0]) {
return best;
} else {
return pair;
}
}, null)[1];
}
export function pick(obj, keys) {
return keys.reduce((a, k) => {
a[k] = obj[k];
return a;
}, {});
}
export function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
// NUMBERS AND STRINGS
export function integerBetween(thing, bottom, top) {
return isInteger(thing) && thing >= bottom && thing <= top;
}
// x % n but takes the sign of n instead of x
export function floorMod(x, n) {
return x - n * Math.floor(x / n);
}
export function padStart(input, n = 2) {
const minus = input < 0 ? "-" : "";
const target = minus ? input * -1 : input;
let result;
if (target.toString().length < n) {
result = ("0".repeat(n) + target).slice(-n);
} else {
result = target.toString();
}
return `${minus}${result}`;
}
export function parseInteger(string) {
if (isUndefined(string) || string === null || string === "") {
return undefined;
} else {
return parseInt(string, 10);
}
}
export function parseMillis(fraction) {
// Return undefined (instead of 0) in these cases, where fraction is not set
if (isUndefined(fraction) || fraction === null || fraction === "") {
return undefined;
} else {
const f = parseFloat("0." + fraction) * 1000;
return Math.floor(f);
}
}
export function roundTo(number, digits, towardZero = false) {
const factor = 10 ** digits,
rounder = towardZero ? Math.trunc : Math.round;
return rounder(number * factor) / factor;
}
// DATE BASICS
export function isLeapYear(year) {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
export function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
export function daysInMonth(year, month) {
const modMonth = floorMod(month - 1, 12) + 1,
modYear = year + (month - modMonth) / 12;
if (modMonth === 2) {
return isLeapYear(modYear) ? 29 : 28;
} else {
return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
}
}
// covert a calendar object to a local timestamp (epoch, but with the offset baked in)
export function objToLocalTS(obj) {
let d = Date.UTC(
obj.year,
obj.month - 1,
obj.day,
obj.hour,
obj.minute,
obj.second,
obj.millisecond
);
// for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that
if (obj.year < 100 && obj.year >= 0) {
d = new Date(d);
d.setUTCFullYear(d.getUTCFullYear() - 1900);
}
return +d;
}
export function weeksInWeekYear(weekYear) {
const p1 =
(weekYear +
Math.floor(weekYear / 4) -
Math.floor(weekYear / 100) +
Math.floor(weekYear / 400)) %
7,
last = weekYear - 1,
p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;
return p1 === 4 || p2 === 3 ? 53 : 52;
}
export function untruncateYear(year) {
if (year > 99) {
return year;
} else return year > 60 ? 1900 + year : 2000 + year;
}
// PARSING
export function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {
const date = new Date(ts),
intlOpts = {
hour12: false,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit"
};
if (timeZone) {
intlOpts.timeZone = timeZone;
}
const modified = Object.assign({ timeZoneName: offsetFormat }, intlOpts),
intl = hasIntl();
if (intl && hasFormatToParts()) {
const parsed = new Intl.DateTimeFormat(locale, modified)
.formatToParts(date)
.find(m => m.type.toLowerCase() === "timezonename");
return parsed ? parsed.value : null;
} else if (intl) {
// this probably doesn't work for all locales
const without = new Intl.DateTimeFormat(locale, intlOpts).format(date),
included = new Intl.DateTimeFormat(locale, modified).format(date),
diffed = included.substring(without.length),
trimmed = diffed.replace(/^[, \u200e]+/, "");
return trimmed;
} else {
return null;
}
}
// signedOffset('-5', '30') -> -330
export function signedOffset(offHourStr, offMinuteStr) {
let offHour = parseInt(offHourStr, 10);
// don't || this because we want to preserve -0
if (Number.isNaN(offHour)) {
offHour = 0;
}
const offMin = parseInt(offMinuteStr, 10) || 0,
offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;
return offHour * 60 + offMinSigned;
}
// COERCION
export function asNumber(value) {
const numericValue = Number(value);
if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue))
throw new InvalidArgumentError(`Invalid unit value ${value}`);
return numericValue;
}
export function normalizeObject(obj, normalizer, nonUnitKeys) {
const normalized = {};
for (const u in obj) {
if (hasOwnProperty(obj, u)) {
if (nonUnitKeys.indexOf(u) >= 0) continue;
const v = obj[u];
if (v === undefined || v === null) continue;
normalized[normalizer(u)] = asNumber(v);
}
}
return normalized;
}
export function formatOffset(offset, format) {
const hours = Math.trunc(Math.abs(offset / 60)),
minutes = Math.trunc(Math.abs(offset % 60)),
sign = offset >= 0 ? "+" : "-";
switch (format) {
case "short":
return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;
case "narrow":
return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`;
case "techie":
return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;
default:
throw new RangeError(`Value format ${format} is out of range for property format`);
}
}
export function timeObject(obj) {
return pick(obj, ["hour", "minute", "second", "millisecond"]);
}
export const ianaRegex = /[A-Za-z_+-]{1,256}(:?\/[A-Za-z_+-]{1,256}(\/[A-Za-z_+-]{1,256})?)?/;
/**
* @private
*/
import Zone from "../zone.js";
import IANAZone from "../zones/IANAZone.js";
import FixedOffsetZone from "../zones/fixedOffsetZone.js";
import InvalidZone from "../zones/invalidZone.js";
import { isUndefined, isString, isNumber } from "./util.js";
export function normalizeZone(input, defaultZone) {
let offset;
if (isUndefined(input) || input === null) {
return defaultZone;
} else if (input instanceof Zone) {
return input;
} else if (isString(input)) {
const lowered = input.toLowerCase();
if (lowered === "local") return defaultZone;
else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance;
else if ((offset = IANAZone.parseGMTOffset(input)) != null) {
// handle Etc/GMT-4, which V8 chokes on
return FixedOffsetZone.instance(offset);
} else if (IANAZone.isValidSpecifier(lowered)) return IANAZone.create(input);
else return FixedOffsetZone.parseSpecifier(lowered) || new InvalidZone(input);
} else if (isNumber(input)) {
return FixedOffsetZone.instance(input);
} else if (typeof input === "object" && input.offset && typeof input.offset === "number") {
// This is dumb, but the instanceof check above doesn't seem to really work
// so we're duck checking it
return input;
} else {
return new InvalidZone(input);
}
}
import DateTime from "./datetime.js";
import Settings from "./settings.js";
import Locale from "./impl/locale.js";
import IANAZone from "./zones/IANAZone.js";
import { normalizeZone } from "./impl/zoneUtil.js";
import { hasFormatToParts, hasIntl, hasRelative } from "./impl/util.js";
/**
* The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.
*/
export default class Info {
/**
* Return whether the specified zone contains a DST.
* @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.
* @return {boolean}
*/
static hasDST(zone = Settings.defaultZone) {
const proto = DateTime.now()
.setZone(zone)
.set({ month: 12 });
return !zone.universal && proto.offset !== proto.set({ month: 6 }).offset;
}
/**
* Return whether the specified zone is a valid IANA specifier.
* @param {string} zone - Zone to check
* @return {boolean}
*/
static isValidIANAZone(zone) {
return IANAZone.isValidSpecifier(zone) && IANAZone.isValidZone(zone);
}
/**
* Converts the input into a {@link Zone} instance.
*
* * If `input` is already a Zone instance, it is returned unchanged.
* * If `input` is a string containing a valid time zone name, a Zone instance
* with that name is returned.
* * If `input` is a string that doesn't refer to a known time zone, a Zone
* instance with {@link Zone.isValid} == false is returned.
* * If `input is a number, a Zone instance with the specified fixed offset
* in minutes is returned.
* * If `input` is `null` or `undefined`, the default zone is returned.
* @param {string|Zone|number} [input] - the value to be converted
* @return {Zone}
*/
static normalizeZone(input) {
return normalizeZone(input, Settings.defaultZone);
}
/**
* Return an array of standalone month names.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
* @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @param {string} [opts.numberingSystem=null] - the numbering system
* @param {string} [opts.locObj=null] - an existing locale object to use
* @param {string} [opts.outputCalendar='gregory'] - the calendar
* @example Info.months()[0] //=> 'January'
* @example Info.months('short')[0] //=> 'Jan'
* @example Info.months('numeric')[0] //=> '1'
* @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'
* @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'
* @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'
* @return {[string]}
*/
static months(
length = "long",
{ locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}
) {
return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);
}
/**
* Return an array of format month names.
* Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that
* changes the string.
* See {@link months}
* @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @param {string} [opts.numberingSystem=null] - the numbering system
* @param {string} [opts.locObj=null] - an existing locale object to use
* @param {string} [opts.outputCalendar='gregory'] - the calendar
* @return {[string]}
*/
static monthsFormat(
length = "long",
{ locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}
) {
return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);
}
/**
* Return an array of standalone week names.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
* @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @param {string} [opts.numberingSystem=null] - the numbering system
* @param {string} [opts.locObj=null] - an existing locale object to use
* @example Info.weekdays()[0] //=> 'Monday'
* @example Info.weekdays('short')[0] //=> 'Mon'
* @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
* @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'
* @return {[string]}
*/
static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) {
return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);
}
/**
* Return an array of format week names.
* Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that
* changes the string.
* See {@link weekdays}
* @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
* @param {Object} opts - options
* @param {string} [opts.locale=null] - the locale code
* @param {string} [opts.numberingSystem=null] - the numbering system
* @param {string} [opts.locObj=null] - an existing locale object to use
* @return {[string]}
*/
static weekdaysFormat(
length = "long",
{ locale = null, numberingSystem = null, locObj = null } = {}
) {
return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);
}
/**
* Return an array of meridiems.
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @example Info.meridiems() //=> [ 'AM', 'PM' ]
* @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]
* @return {[string]}
*/
static meridiems({ locale = null } = {}) {
return Locale.create(locale).meridiems();
}
/**
* Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.
* @param {string} [length='short'] - the length of the era representation, such as "short" or "long".
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @example Info.eras() //=> [ 'BC', 'AD' ]
* @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]
* @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]
* @return {[string]}
*/
static eras(length = "short", { locale = null } = {}) {
return Locale.create(locale, null, "gregory").eras(length);
}
/**
* Return the set of available features in this environment.
* Some features of Luxon are not available in all environments. For example, on older browsers, timezone support is not available. Use this function to figure out if that's the case.
* Keys:
* * `zones`: whether this environment supports IANA timezones
* * `intlTokens`: whether this environment supports internationalized token-based formatting/parsing
* * `intl`: whether this environment supports general internationalization
* * `relative`: whether this environment supports relative time formatting
* @example Info.features() //=> { intl: true, intlTokens: false, zones: true, relative: false }
* @return {Object}
*/
static features() {
let intl = false,
intlTokens = false,
zones = false,
relative = false;
if (hasIntl()) {
intl = true;
intlTokens = hasFormatToParts();
relative = hasRelative();
try {
zones =
new Intl.DateTimeFormat("en", { timeZone: "America/New_York" }).resolvedOptions()
.timeZone === "America/New_York";
} catch (e) {
zones = false;
}
}
return { intl, intlTokens, zones, relative };
}
}
import DateTime, { friendlyDateTime } from "./datetime.js";
import Duration, { friendlyDuration } from "./duration.js";
import Settings from "./settings.js";
import { InvalidArgumentError, InvalidIntervalError } from "./errors.js";
import Invalid from "./impl/invalid.js";
const INVALID = "Invalid Interval";
// checks if the start is equal to or before the end
function validateStartEnd(start, end) {
if (!start || !start.isValid) {
return Interval.invalid("missing or invalid start");
} else if (!end || !end.isValid) {
return Interval.invalid("missing or invalid end");
} else if (end < start) {
return Interval.invalid(
"end before start",
`The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`
);
} else {
return null;
}
}
/**
* An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.
*
* Here is a brief overview of the most commonly used methods and getters in Interval:
*
* * **Creation** To create an Interval, use {@link fromDateTimes}, {@link after}, {@link before}, or {@link fromISO}.
* * **Accessors** Use {@link start} and {@link end} to get the start and end.
* * **Interrogation** To analyze the Interval, use {@link count}, {@link length}, {@link hasSame}, {@link contains}, {@link isAfter}, or {@link isBefore}.
* * **Transformation** To create other Intervals out of this one, use {@link set}, {@link splitAt}, {@link splitBy}, {@link divideEqually}, {@link merge}, {@link xor}, {@link union}, {@link intersection}, or {@link difference}.
* * **Comparison** To compare this Interval to another one, use {@link equals}, {@link overlaps}, {@link abutsStart}, {@link abutsEnd}, {@link engulfs}.
* * **Output** To convert the Interval into other representations, see {@link toString}, {@link toISO}, {@link toISODate}, {@link toISOTime}, {@link toFormat}, and {@link toDuration}.
*/
export default class Interval {
/**
* @private
*/
constructor(config) {
/**
* @access private
*/
this.s = config.start;
/**
* @access private
*/
this.e = config.end;
/**
* @access private
*/
this.invalid = config.invalid || null;
/**
* @access private
*/
this.isLuxonInterval = true;
}
/**
* Create an invalid Interval.
* @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent
* @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
* @return {Interval}
*/
static invalid(reason, explanation = null) {
if (!reason) {
throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
}
const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
if (Settings.throwOnInvalid) {
throw new InvalidIntervalError(invalid);
} else {
return new Interval({ invalid });
}
}
/**
* Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.
* @param {DateTime|Date|Object} start
* @param {DateTime|Date|Object} end
* @return {Interval}
*/
static fromDateTimes(start, end) {
const builtStart = friendlyDateTime(start),
builtEnd = friendlyDateTime(end);
const validateError = validateStartEnd(builtStart, builtEnd);
if (validateError == null) {
return new Interval({
start: builtStart,
end: builtEnd
});
} else {
return validateError;
}
}
/**
* Create an Interval from a start DateTime and a Duration to extend to.
* @param {DateTime|Date|Object} start
* @param {Duration|Object|number} duration - the length of the Interval.
* @return {Interval}
*/
static after(start, duration) {
const dur = friendlyDuration(duration),
dt = friendlyDateTime(start);
return Interval.fromDateTimes(dt, dt.plus(dur));
}
/**
* Create an Interval from an end DateTime and a Duration to extend backwards to.
* @param {DateTime|Date|Object} end
* @param {Duration|Object|number} duration - the length of the Interval.
* @return {Interval}
*/
static before(end, duration) {
const dur = friendlyDuration(duration),
dt = friendlyDateTime(end);
return Interval.fromDateTimes(dt.minus(dur), dt);
}
/**
* Create an Interval from an ISO 8601 string.
* Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats.
* @param {string} text - the ISO string to parse
* @param {Object} [opts] - options to pass {@link DateTime.fromISO} and optionally {@link Duration.fromISO}
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
* @return {Interval}
*/
static fromISO(text, opts) {
const [s, e] = (text || "").split("/", 2);
if (s && e) {
let start, startIsValid;
try {
start = DateTime.fromISO(s, opts);
startIsValid = start.isValid;
} catch (e) {
startIsValid = false;
}
let end, endIsValid;
try {
end = DateTime.fromISO(e, opts);
endIsValid = end.isValid;
} catch (e) {
endIsValid = false;
}
if (startIsValid && endIsValid) {
return Interval.fromDateTimes(start, end);
}
if (startIsValid) {
const dur = Duration.fromISO(e, opts);
if (dur.isValid) {
return Interval.after(start, dur);
}
} else if (endIsValid) {
const dur = Duration.fromISO(s, opts);
if (dur.isValid) {
return Interval.before(end, dur);
}
}
}
return Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
}
/**
* Check if an object is an Interval. Works across context boundaries
* @param {object} o
* @return {boolean}
*/
static isInterval(o) {
return (o && o.isLuxonInterval) || false;
}
/**
* Returns the start of the Interval
* @type {DateTime}
*/
get start() {
return this.isValid ? this.s : null;
}
/**
* Returns the end of the Interval
* @type {DateTime}
*/
get end() {
return this.isValid ? this.e : null;
}
/**
* Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.
* @type {boolean}
*/
get isValid() {
return this.invalidReason === null;
}
/**
* Returns an error code if this Interval is invalid, or null if the Interval is valid
* @type {string}
*/
get invalidReason() {
return this.invalid ? this.invalid.reason : null;
}
/**
* Returns an explanation of why this Interval became invalid, or null if the Interval is valid
* @type {string}
*/
get invalidExplanation() {
return this.invalid ? this.invalid.explanation : null;
}
/**
* Returns the length of the Interval in the specified unit.
* @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.
* @return {number}
*/
length(unit = "milliseconds") {
return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;
}
/**
* Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.
* Unlike {@link length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'
* asks 'what dates are included in this interval?', not 'how many days long is this interval?'
* @param {string} [unit='milliseconds'] - the unit of time to count.
* @return {number}
*/
count(unit = "milliseconds") {
if (!this.isValid) return NaN;
const start = this.start.startOf(unit),
end = this.end.startOf(unit);
return Math.floor(end.diff(start, unit).get(unit)) + 1;
}
/**
* Returns whether this Interval's start and end are both in the same unit of time
* @param {string} unit - the unit of time to check sameness on
* @return {boolean}
*/
hasSame(unit) {
return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;
}
/**
* Return whether this Interval has the same start and end DateTimes.
* @return {boolean}
*/
isEmpty() {
return this.s.valueOf() === this.e.valueOf();
}
/**
* Return whether this Interval's start is after the specified DateTime.
* @param {DateTime} dateTime
* @return {boolean}
*/
isAfter(dateTime) {
if (!this.isValid) return false;
return this.s > dateTime;
}
/**
* Return whether this Interval's end is before the specified DateTime.
* @param {DateTime} dateTime
* @return {boolean}
*/
isBefore(dateTime) {
if (!this.isValid) return false;
return this.e <= dateTime;
}
/**
* Return whether this Interval contains the specified DateTime.
* @param {DateTime} dateTime
* @return {boolean}
*/
contains(dateTime) {
if (!this.isValid) return false;
return this.s <= dateTime && this.e > dateTime;
}
/**
* "Sets" the start and/or end dates. Returns a newly-constructed Interval.
* @param {Object} values - the values to set
* @param {DateTime} values.start - the starting DateTime
* @param {DateTime} values.end - the ending DateTime
* @return {Interval}
*/
set({ start, end } = {}) {
if (!this.isValid) return this;
return Interval.fromDateTimes(start || this.s, end || this.e);
}
/**
* Split this Interval at each of the specified DateTimes
* @param {...[DateTime]} dateTimes - the unit of time to count.
* @return {[Interval]}
*/
splitAt(...dateTimes) {
if (!this.isValid) return [];
const sorted = dateTimes
.map(friendlyDateTime)
.filter(d => this.contains(d))
.sort(),
results = [];
let { s } = this,
i = 0;
while (s < this.e) {
const added = sorted[i] || this.e,
next = +added > +this.e ? this.e : added;
results.push(Interval.fromDateTimes(s, next));
s = next;
i += 1;
}
return results;
}
/**
* Split this Interval into smaller Intervals, each of the specified length.
* Left over time is grouped into a smaller interval
* @param {Duration|Object|number} duration - The length of each resulting interval.
* @return {[Interval]}
*/
splitBy(duration) {
const dur = friendlyDuration(duration);
if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
return [];
}
let { s } = this,
idx = 1,
next;
const results = [];
while (s < this.e) {
const added = this.start.plus(dur.mapUnits(x => x * idx));
next = +added > +this.e ? this.e : added;
results.push(Interval.fromDateTimes(s, next));
s = next;
idx += 1;
}
return results;
}
/**
* Split this Interval into the specified number of smaller intervals.
* @param {number} numberOfParts - The number of Intervals to divide the Interval into.
* @return {[Interval]}
*/
divideEqually(numberOfParts) {
if (!this.isValid) return [];
return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
}
/**
* Return whether this Interval overlaps with the specified Interval
* @param {Interval} other
* @return {boolean}
*/
overlaps(other) {
return this.e > other.s && this.s < other.e;
}
/**
* Return whether this Interval's end is adjacent to the specified Interval's start.
* @param {Interval} other
* @return {boolean}
*/
abutsStart(other) {
if (!this.isValid) return false;
return +this.e === +other.s;
}
/**
* Return whether this Interval's start is adjacent to the specified Interval's end.
* @param {Interval} other
* @return {boolean}
*/
abutsEnd(other) {
if (!this.isValid) return false;
return +other.e === +this.s;
}
/**
* Return whether this Interval engulfs the start and end of the specified Interval.
* @param {Interval} other
* @return {boolean}
*/
engulfs(other) {
if (!this.isValid) return false;
return this.s <= other.s && this.e >= other.e;
}
/**
* Return whether this Interval has the same start and end as the specified Interval.
* @param {Interval} other
* @return {boolean}
*/
equals(other) {
if (!this.isValid || !other.isValid) {
return false;
}
return this.s.equals(other.s) && this.e.equals(other.e);
}
/**
* Return an Interval representing the intersection of this Interval and the specified Interval.
* Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.
* Returns null if the intersection is empty, meaning, the intervals don't intersect.
* @param {Interval} other
* @return {Interval}
*/
intersection(other) {
if (!this.isValid) return this;
const s = this.s > other.s ? this.s : other.s,
e = this.e < other.e ? this.e : other.e;
if (s >= e) {
return null;
} else {
return Interval.fromDateTimes(s, e);
}
}
/**
* Return an Interval representing the union of this Interval and the specified Interval.
* Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.
* @param {Interval} other
* @return {Interval}
*/
union(other) {
if (!this.isValid) return this;
const s = this.s < other.s ? this.s : other.s,
e = this.e > other.e ? this.e : other.e;
return Interval.fromDateTimes(s, e);
}
/**
* Merge an array of Intervals into a equivalent minimal set of Intervals.
* Combines overlapping and adjacent Intervals.
* @param {[Interval]} intervals
* @return {[Interval]}
*/
static merge(intervals) {
const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce(
([sofar, current], item) => {
if (!current) {
return [sofar, item];
} else if (current.overlaps(item) || current.abutsStart(item)) {
return [sofar, current.union(item)];
} else {
return [sofar.concat([current]), item];
}
},
[[], null]
);
if (final) {
found.push(final);
}
return found;
}
/**
* Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.
* @param {[Interval]} intervals
* @return {[Interval]}
*/
static xor(intervals) {
let start = null,
currentCount = 0;
const results = [],
ends = intervals.map(i => [{ time: i.s, type: "s" }, { time: i.e, type: "e" }]),
flattened = Array.prototype.concat(...ends),
arr = flattened.sort((a, b) => a.time - b.time);
for (const i of arr) {
currentCount += i.type === "s" ? 1 : -1;
if (currentCount === 1) {
start = i.time;
} else {
if (start && +start !== +i.time) {
results.push(Interval.fromDateTimes(start, i.time));
}
start = null;
}
}
return Interval.merge(results);
}
/**
* Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.
* @param {...Interval} intervals
* @return {[Interval]}
*/
difference(...intervals) {
return Interval.xor([this].concat(intervals))
.map(i => this.intersection(i))
.filter(i => i && !i.isEmpty());
}
/**
* Returns a string representation of this Interval appropriate for debugging.
* @return {string}
*/
toString() {
if (!this.isValid) return INVALID;
return `[${this.s.toISO()}${this.e.toISO()})`;
}
/**
* Returns an ISO 8601-compliant string representation of this Interval.
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
* @param {Object} opts - The same options as {@link DateTime.toISO}
* @return {string}
*/
toISO(opts) {
if (!this.isValid) return INVALID;
return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;
}
/**
* Returns an ISO 8601-compliant string representation of date of this Interval.
* The time components are ignored.
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
* @return {string}
*/
toISODate() {
if (!this.isValid) return INVALID;
return `${this.s.toISODate()}/${this.e.toISODate()}`;
}
/**
* Returns an ISO 8601-compliant string representation of time of this Interval.
* The date components are ignored.
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
* @param {Object} opts - The same options as {@link DateTime.toISO}
* @return {string}
*/
toISOTime(opts) {
if (!this.isValid) return INVALID;
return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;
}
/**
* Returns a string representation of this Interval formatted according to the specified format string.
* @param {string} dateFormat - the format string. This string formats the start and end time. See {@link DateTime.toFormat} for details.
* @param {Object} opts - options
* @param {string} [opts.separator = ' – '] - a separator to place between the start and end representations
* @return {string}
*/
toFormat(dateFormat, { separator = " – " } = {}) {
if (!this.isValid) return INVALID;
return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;
}
/**
* Return a Duration representing the time spanned by this interval.
* @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.
* @param {Object} opts - options that affect the creation of the Duration
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }
* @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }
* @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }
* @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }
* @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }
* @return {Duration}
*/
toDuration(unit, opts) {
if (!this.isValid) {
return Duration.invalid(this.invalidReason);
}
return this.e.diff(this.s, unit, opts);
}
/**
* Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes
* @param {function} mapFn
* @return {Interval}
* @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())
* @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))
*/
mapEndpoints(mapFn) {
return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
}
}
import DateTime from "./datetime.js";
import Duration from "./duration.js";
import Interval from "./interval.js";
import Info from "./info.js";
import Zone from "./zone.js";
import FixedOffsetZone from "./zones/fixedOffsetZone.js";
import IANAZone from "./zones/IANAZone.js";
import InvalidZone from "./zones/invalidZone.js";
import LocalZone from "./zones/localZone.js";
import Settings from "./settings.js";
const VERSION = "1.27.0";
export {
VERSION,
DateTime,
Duration,
Interval,
Info,
Zone,
FixedOffsetZone,
IANAZone,
InvalidZone,
LocalZone,
Settings
};
/* eslint import/no-extraneous-dependencies: off */
import "core-js/features/symbol";
import "core-js/features/symbol/iterator";
import "core-js/features/object";
import "core-js/features/number/is-nan";
import "core-js/features/array";
import "core-js/features/string/virtual/starts-with";
import "core-js/features/string/virtual/repeat";
import "core-js/features/math/trunc";
import "core-js/features/math/sign";
export * from "./luxon.js";
import LocalZone from "./zones/localZone.js";
import IANAZone from "./zones/IANAZone.js";
import Locale from "./impl/locale.js";
import { normalizeZone } from "./impl/zoneUtil.js";
let now = () => Date.now(),
defaultZone = null, // not setting this directly to LocalZone.instance bc loading order issues
defaultLocale = null,
defaultNumberingSystem = null,
defaultOutputCalendar = null,
throwOnInvalid = false;
/**
* Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.
*/
export default class Settings {
/**
* Get the callback for returning the current timestamp.
* @type {function}
*/
static get now() {
return now;
}
/**
* Set the callback for returning the current timestamp.
* The function should return a number, which will be interpreted as an Epoch millisecond count
* @type {function}
* @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future
* @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time
*/
static set now(n) {
now = n;
}
/**
* Get the default time zone to create DateTimes in.
* @type {string}
*/
static get defaultZoneName() {
return Settings.defaultZone.name;
}
/**
* Set the default time zone to create DateTimes in. Does not affect existing instances.
* @type {string}
*/
static set defaultZoneName(z) {
if (!z) {
defaultZone = null;
} else {
defaultZone = normalizeZone(z);
}
}
/**
* Get the default time zone object to create DateTimes in. Does not affect existing instances.
* @type {Zone}
*/
static get defaultZone() {
return defaultZone || LocalZone.instance;
}
/**
* Get the default locale to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static get defaultLocale() {
return defaultLocale;
}
/**
* Set the default locale to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static set defaultLocale(locale) {
defaultLocale = locale;
}
/**
* Get the default numbering system to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static get defaultNumberingSystem() {
return defaultNumberingSystem;
}
/**
* Set the default numbering system to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static set defaultNumberingSystem(numberingSystem) {
defaultNumberingSystem = numberingSystem;
}
/**
* Get the default output calendar to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static get defaultOutputCalendar() {
return defaultOutputCalendar;
}
/**
* Set the default output calendar to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static set defaultOutputCalendar(outputCalendar) {
defaultOutputCalendar = outputCalendar;
}
/**
* Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
* @type {boolean}
*/
static get throwOnInvalid() {
return throwOnInvalid;
}
/**
* Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
* @type {boolean}
*/
static set throwOnInvalid(t) {
throwOnInvalid = t;
}
/**
* Reset Luxon's global caches. Should only be necessary in testing scenarios.
* @return {void}
*/
static resetCaches() {
Locale.resetCache();
IANAZone.resetCache();
}
}
/* eslint no-unused-vars: "off" */
import { ZoneIsAbstractError } from "./errors.js";
/**
* @interface
*/
export default class Zone {
/**
* The type of zone
* @abstract
* @type {string}
*/
get type() {
throw new ZoneIsAbstractError();
}
/**
* The name of this zone.
* @abstract
* @type {string}
*/
get name() {
throw new ZoneIsAbstractError();
}
/**
* Returns whether the offset is known to be fixed for the whole year.
* @abstract
* @type {boolean}
*/
get universal() {
throw new ZoneIsAbstractError();
}
/**
* Returns the offset's common name (such as EST) at the specified timestamp
* @abstract
* @param {number} ts - Epoch milliseconds for which to get the name
* @param {Object} opts - Options to affect the format
* @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
* @param {string} opts.locale - What locale to return the offset name in.
* @return {string}
*/
offsetName(ts, opts) {
throw new ZoneIsAbstractError();
}
/**
* Returns the offset's value as a string
* @abstract
* @param {number} ts - Epoch milliseconds for which to get the offset
* @param {string} format - What style of offset to return.
* Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
* @return {string}
*/
formatOffset(ts, format) {
throw new ZoneIsAbstractError();
}
/**
* Return the offset in minutes for this zone at the specified timestamp.
* @abstract
* @param {number} ts - Epoch milliseconds for which to compute the offset
* @return {number}
*/
offset(ts) {
throw new ZoneIsAbstractError();
}
/**
* Return whether this Zone is equal to another zone
* @abstract
* @param {Zone} otherZone - the zone to compare
* @return {boolean}
*/
equals(otherZone) {
throw new ZoneIsAbstractError();
}
/**
* Return whether this Zone is valid.
* @abstract
* @type {boolean}
*/
get isValid() {
throw new ZoneIsAbstractError();
}
}
import { formatOffset, parseZoneInfo, isUndefined, ianaRegex, objToLocalTS } from "../impl/util.js";
import Zone from "../zone.js";
const matchingRegex = RegExp(`^${ianaRegex.source}$`);
let dtfCache = {};
function makeDTF(zone) {
if (!dtfCache[zone]) {
dtfCache[zone] = new Intl.DateTimeFormat("en-US", {
hour12: false,
timeZone: zone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
});
}
return dtfCache[zone];
}
const typeToPos = {
year: 0,
month: 1,
day: 2,
hour: 3,
minute: 4,
second: 5
};
function hackyOffset(dtf, date) {
const formatted = dtf.format(date).replace(/\u200E/g, ""),
parsed = /(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(formatted),
[, fMonth, fDay, fYear, fHour, fMinute, fSecond] = parsed;
return [fYear, fMonth, fDay, fHour, fMinute, fSecond];
}
function partsOffset(dtf, date) {
const formatted = dtf.formatToParts(date),
filled = [];
for (let i = 0; i < formatted.length; i++) {
const { type, value } = formatted[i],
pos = typeToPos[type];
if (!isUndefined(pos)) {
filled[pos] = parseInt(value, 10);
}
}
return filled;
}
let ianaZoneCache = {};
/**
* A zone identified by an IANA identifier, like America/New_York
* @implements {Zone}
*/
export default class IANAZone extends Zone {
/**
* @param {string} name - Zone name
* @return {IANAZone}
*/
static create(name) {
if (!ianaZoneCache[name]) {
ianaZoneCache[name] = new IANAZone(name);
}
return ianaZoneCache[name];
}
/**
* Reset local caches. Should only be necessary in testing scenarios.
* @return {void}
*/
static resetCache() {
ianaZoneCache = {};
dtfCache = {};
}
/**
* Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.
* @param {string} s - The string to check validity on
* @example IANAZone.isValidSpecifier("America/New_York") //=> true
* @example IANAZone.isValidSpecifier("Fantasia/Castle") //=> true
* @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false
* @return {boolean}
*/
static isValidSpecifier(s) {
return !!(s && s.match(matchingRegex));
}
/**
* Returns whether the provided string identifies a real zone
* @param {string} zone - The string to check
* @example IANAZone.isValidZone("America/New_York") //=> true
* @example IANAZone.isValidZone("Fantasia/Castle") //=> false
* @example IANAZone.isValidZone("Sport~~blorp") //=> false
* @return {boolean}
*/
static isValidZone(zone) {
try {
new Intl.DateTimeFormat("en-US", { timeZone: zone }).format();
return true;
} catch (e) {
return false;
}
}
// Etc/GMT+8 -> -480
/** @ignore */
static parseGMTOffset(specifier) {
if (specifier) {
const match = specifier.match(/^Etc\/GMT(0|[+-]\d{1,2})$/i);
if (match) {
return -60 * parseInt(match[1]);
}
}
return null;
}
constructor(name) {
super();
/** @private **/
this.zoneName = name;
/** @private **/
this.valid = IANAZone.isValidZone(name);
}
/** @override **/
get type() {
return "iana";
}
/** @override **/
get name() {
return this.zoneName;
}
/** @override **/
get universal() {
return false;
}
/** @override **/
offsetName(ts, { format, locale }) {
return parseZoneInfo(ts, format, locale, this.name);
}
/** @override **/
formatOffset(ts, format) {
return formatOffset(this.offset(ts), format);
}
/** @override **/
offset(ts) {
const date = new Date(ts);
if (isNaN(date)) return NaN;
const dtf = makeDTF(this.name),
[year, month, day, hour, minute, second] = dtf.formatToParts
? partsOffset(dtf, date)
: hackyOffset(dtf, date),
// work around https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat
adjustedHour = hour === 24 ? 0 : hour;
const asUTC = objToLocalTS({
year,
month,
day,
hour: adjustedHour,
minute,
second,
millisecond: 0
});
let asTS = +date;
const over = asTS % 1000;
asTS -= over >= 0 ? over : 1000 + over;
return (asUTC - asTS) / (60 * 1000);
}
/** @override **/
equals(otherZone) {
return otherZone.type === "iana" && otherZone.name === this.name;
}
/** @override **/
get isValid() {
return this.valid;
}
}
import { formatOffset, signedOffset } from "../impl/util.js";
import Zone from "../zone.js";
let singleton = null;
/**
* A zone with a fixed offset (meaning no DST)
* @implements {Zone}
*/
export default class FixedOffsetZone extends Zone {
/**
* Get a singleton instance of UTC
* @return {FixedOffsetZone}
*/
static get utcInstance() {
if (singleton === null) {
singleton = new FixedOffsetZone(0);
}
return singleton;
}
/**
* Get an instance with a specified offset
* @param {number} offset - The offset in minutes
* @return {FixedOffsetZone}
*/
static instance(offset) {
return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);
}
/**
* Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
* @param {string} s - The offset string to parse
* @example FixedOffsetZone.parseSpecifier("UTC+6")
* @example FixedOffsetZone.parseSpecifier("UTC+06")
* @example FixedOffsetZone.parseSpecifier("UTC-6:00")
* @return {FixedOffsetZone}
*/
static parseSpecifier(s) {
if (s) {
const r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
if (r) {
return new FixedOffsetZone(signedOffset(r[1], r[2]));
}
}
return null;
}
constructor(offset) {
super();
/** @private **/
this.fixed = offset;
}
/** @override **/
get type() {
return "fixed";
}
/** @override **/
get name() {
return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`;
}
/** @override **/
offsetName() {
return this.name;
}
/** @override **/
formatOffset(ts, format) {
return formatOffset(this.fixed, format);
}
/** @override **/
get universal() {
return true;
}
/** @override **/
offset() {
return this.fixed;
}
/** @override **/
equals(otherZone) {
return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
}
/** @override **/
get isValid() {
return true;
}
}
import Zone from "../zone.js";
/**
* A zone that failed to parse. You should never need to instantiate this.
* @implements {Zone}
*/
export default class InvalidZone extends Zone {
constructor(zoneName) {
super();
/** @private */
this.zoneName = zoneName;
}
/** @override **/
get type() {
return "invalid";
}
/** @override **/
get name() {
return this.zoneName;
}
/** @override **/
get universal() {
return false;
}
/** @override **/
offsetName() {
return null;
}
/** @override **/
formatOffset() {
return "";
}
/** @override **/
offset() {
return NaN;
}
/** @override **/
equals() {
return false;
}
/** @override **/
get isValid() {
return false;
}
}
import { formatOffset, parseZoneInfo, hasIntl } from "../impl/util.js";
import Zone from "../zone.js";
let singleton = null;
/**
* Represents the local zone for this JavaScript environment.
* @implements {Zone}
*/
export default class LocalZone extends Zone {
/**
* Get a singleton instance of the local zone
* @return {LocalZone}
*/
static get instance() {
if (singleton === null) {
singleton = new LocalZone();
}
return singleton;
}
/** @override **/
get type() {
return "local";
}
/** @override **/
get name() {
if (hasIntl()) {
return new Intl.DateTimeFormat().resolvedOptions().timeZone;
} else return "local";
}
/** @override **/
get universal() {
return false;
}
/** @override **/
offsetName(ts, { format, locale }) {
return parseZoneInfo(ts, format, locale);
}
/** @override **/
formatOffset(ts, format) {
return formatOffset(this.offset(ts), format);
}
/** @override **/
offset(ts) {
return -new Date(ts).getTimezoneOffset();
}
/** @override **/
equals(otherZone) {
return otherZone.type === "local";
}
/** @override **/
get isValid() {
return true;
}
}
# Master (Unreleased)
# 2.0.0 - 01 February, 2021
### Breaking changes:
- Drop support for Node < 6
- Remove support for job objects. See `UPGRADING.md` for more details. #557
### New features:
- Introduce compatibility with browsers and Electron #553
### Bug fixes:
- Avoid leaking memory on one-off jobs #581
- Address anonymous job id collision problem to ensure that node-schedule could run with the unlimited uptime #582
### Internal changes:
- Bump cron-parser from 2.18.0 to 3.1.0 #562
- Bump sinon from 1.17.7 to 9.2.4 #566
- Switch to nyc from istanbul #574
- Convert tests from nodeunit to Tape #575
- Replace var with let/const #577
- Execute airtap tests on a headless Chromium #578
- Make structure more modular #579
Copyright (C) 2015 Matt Patenaude.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# Node Schedule
[![NPM version](http://img.shields.io/npm/v/node-schedule.svg)](https://www.npmjs.com/package/node-schedule)
[![Downloads](https://img.shields.io/npm/dm/node-schedule.svg)](https://www.npmjs.com/package/node-schedule)
[![Build Status](https://github.com/node-schedule/node-schedule/workflows/ci/badge.svg)](https://github.com/node-schedule/node-schedule/actions)
[![Coverage Status](https://coveralls.io/repos/node-schedule/node-schedule/badge.svg?branch=master)](https://coveralls.io/r/node-schedule/node-schedule?branch=master)
[![Join the chat at https://gitter.im/node-schedule/node-schedule](https://img.shields.io/badge/gitter-chat-green.svg)](https://gitter.im/node-schedule/node-schedule?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![NPM](https://nodei.co/npm/node-schedule.png?downloads=true)](https://nodei.co/npm/node-schedule/)
Node Schedule is a flexible cron-like and not-cron-like job scheduler for Node.js.
It allows you to schedule jobs (arbitrary functions) for execution at
specific dates, with optional recurrence rules. It only uses a single timer
at any given time (rather than reevaluating upcoming jobs every second/minute).
Node 6+ is supported.
## Overview
Node Schedule is for time-based scheduling, not interval-based scheduling.
While you can easily bend it to your will, if you only want to do something like
"run this function every 5 minutes", [toad-scheduler](https://github.com/kibertoad/toad-scheduler) would be a better choice. But if you want to, say, "run this function at the :20
and :50 of every hour on the third Tuesday of every month," you'll find that
Node Schedule suits your needs better. Additionally, Node Schedule has Windows
support, unlike true `cron`, since the node runtime is now fully supported.
Note that Node Schedule is designed for in-process scheduling, i.e. scheduled jobs
will only fire as long as your script is running, and the schedule will disappear
when execution completes. If you need to schedule jobs that will persist even when
your script *isn't* running, consider using actual [cron].
In case you need durable jobs that persist across restarts and lock system compatible with multi-node deployments,
try [agenda](https://github.com/agenda/agenda) or [bree](https://github.com/breejs/bree).
## Usage
### Installation
You can install using [npm](https://www.npmjs.com/package/node-schedule).
```
npm install node-schedule
```
### Jobs and Scheduling
Every scheduled job in Node Schedule is represented by a `Job` object. You can
create jobs manually, then execute the `schedule()` method to apply a schedule,
or use the convenience function `scheduleJob()` as demonstrated below.
`Job` objects are `EventEmitter`s, and emit the following events:
* A `run` event after each execution.
* A `scheduled` event each time they're scheduled to run.
* A `canceled` event when an invocation is canceled before it's executed.
Note that `canceled` is the single-L American spelling.
* An `error` event when a job invocation triggered by a schedule throws or returns
a rejected `Promise`.
(Both the `scheduled` and `canceled` events receive a JavaScript date object as
a parameter).
Note that jobs are scheduled the first time immediately, so if you create a job
using the `scheduleJob()` convenience method, you'll miss the first `scheduled`
event, but you can query the invocation manually (see below).
### Cron-style Scheduling
The cron format consists of:
```
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ │
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
```
Examples with the cron format:
```js
const schedule = require('node-schedule');
const job = schedule.scheduleJob('42 * * * *', function(){
console.log('The answer to life, the universe, and everything!');
});
```
Execute a cron job when the minute is 42 (e.g. 19:42, 20:42, etc.).
And:
```js
const job = schedule.scheduleJob('0 17 ? * 0,4-6', function(){
console.log('Today is recognized by Rebecca Black!');
});
```
Execute a cron job every 5 Minutes = */5 * * * *
You can also get when it is scheduled to run for every invocation of the job:
```js
const job = schedule.scheduleJob('0 1 * * *', function(fireDate){
console.log('This job was supposed to run at ' + fireDate + ', but actually ran at ' + new Date());
});
```
This is useful when you need to check if there is a delay of the job invocation when the system is busy, or save a record of all invocations of a job for audit purpose.
#### Unsupported Cron Features
Currently, `W` (nearest weekday) and `L` (last day of month/week) are not supported.
Most other features supported by popular cron implementations should work just fine,
including `#` (nth weekday of the month).
[cron-parser] is used to parse crontab instructions.
### Date-based Scheduling
Say you very specifically want a function to execute at 5:30am on December 21, 2012.
Remember - in JavaScript - 0 - January, 11 - December.
```js
const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);
const job = schedule.scheduleJob(date, function(){
console.log('The world is going to end today.');
});
```
To use current data in the future you can use binding:
```js
const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);
const x = 'Tada!';
const job = schedule.scheduleJob(date, function(y){
console.log(y);
}.bind(null,x));
x = 'Changing Data';
```
This will log 'Tada!' when the scheduled Job runs, rather than 'Changing Data',
which x changes to immediately after scheduling.
### Recurrence Rule Scheduling
You can build recurrence rules to specify when a job should recur. For instance,
consider this rule, which executes the function every hour at 42 minutes after the hour:
```js
const schedule = require('node-schedule');
const rule = new schedule.RecurrenceRule();
rule.minute = 42;
const job = schedule.scheduleJob(rule, function(){
console.log('The answer to life, the universe, and everything!');
});
```
You can also use arrays to specify a list of acceptable values, and the `Range`
object to specify a range of start and end values, with an optional step parameter.
For instance, this will print a message on Thursday, Friday, Saturday, and Sunday at 5pm:
```js
const rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(4, 6)];
rule.hour = 17;
rule.minute = 0;
const job = schedule.scheduleJob(rule, function(){
console.log('Today is recognized by Rebecca Black!');
});
```
Timezones are also supported. Here is an example of executing at the start of every day in the UTC timezone.
```js
const rule = new schedule.RecurrenceRule();
rule.hour = 0;
rule.tz = 'Etc/UTC';
const job = schedule.scheduleJob(rule, function(){
console.log('A new day has begun in the UTC timezone!');
});
```
A list of acceptable tz (timezone) values can be found at <https://en.wikipedia.org/wiki/List_of_tz_database_time_zones>
#### RecurrenceRule properties
- `second (0-59)`
- `minute (0-59)`
- `hour (0-23)`
- `date (1-31)`
- `month (0-11)`
- `year`
- `dayOfWeek (0-6) Starting with Sunday`
- `tz`
> **Note**: It's worth noting that the default value of a component of a recurrence rule is
> `null` (except for second, which is 0 for familiarity with cron). *If we did not
> explicitly set `minute` to 0 above, the message would have instead been logged at
> 5:00pm, 5:01pm, 5:02pm, ..., 5:59pm.* Probably not what you want.
#### Object Literal Syntax
To make things a little easier, an object literal syntax is also supported, like
in this example which will log a message every Sunday at 2:30pm:
```js
const job = schedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, function(){
console.log('Time for tea!');
});
```
#### Set StartTime and EndTime
It will run after 5 seconds and stop after 10 seconds in this example.
The ruledat supports the above.
```js
const startTime = new Date(Date.now() + 5000);
const endTime = new Date(startTime.getTime() + 5000);
const job = schedule.scheduleJob({ start: startTime, end: endTime, rule: '*/1 * * * * *' }, function(){
console.log('Time for tea!');
});
```
### Handle Jobs and Job Invocations
There are some function to get information for a Job and to handle the Job and
Invocations.
#### job.cancel(reschedule)
You can invalidate any job with the `cancel()` method:
```js
j.cancel();
```
All planned invocations will be canceled. When you set the parameter ***reschedule***
to true then the Job is newly scheduled afterwards.
#### job.cancelNext(reschedule)
This method invalidates the next planned invocation or the job.
When you set the parameter ***reschedule*** to true then the Job is newly scheduled
afterwards.
#### job.reschedule(spec)
This method cancels all pending invocation and registers the Job completely new again using the given specification.
Return true/false on success/failure.
#### job.nextInvocation()
This method returns a Date object for the planned next Invocation for this Job. If no invocation is planned the method returns null.
## Contributing
This module was originally developed by [Matt Patenaude] who eventually passed over maintainer's mantle over to [Tejas Manohar].
Currently it is being maintained by [Igor Savin] and [our amazing community].
We'd love to get your contributions. Individuals making significant and valuable
contributions are given commit-access to the project to contribute as they see fit.
Before jumping in, check out our [Contributing] page guide!
## Copyright and license
Copyright 2015 Matt Patenaude.
Licensed under the **[MIT License] [license]**.
[cron]: http://unixhelp.ed.ac.uk/CGI/man-cgi?crontab+5
[Contributing]: https://github.com/node-schedule/node-schedule/blob/master/CONTRIBUTING.md
[Matt Patenaude]: https://github.com/mattpat
[Tejas Manohar]: http://tejas.io
[Igor Savin]: https://twitter.com/kibertoad
[license]: https://github.com/node-schedule/node-schedule/blob/master/LICENSE
[Tejas Manohar]: https://github.com/tejasmanohar
[our amazing community]: https://github.com/node-schedule/node-schedule/graphs/contributors
[cron-parser]: https://github.com/harrisiirak/cron-parser
## Upgrading to new node-schedule versions
### Upgrading to version 2.0.0+
* Node.js versions older than 6 are no longer supported, please update your environment before upgrading.
* In order to prevent memory leaks, one-off jobs (targeted to be executed at an exact date) cannot be rescheduled by name, as reference to them is no longer stored indefinitely. If you want to keep rescheduling them, make sure to store reference to the initial job.
* The `scheduleJob()` method no longer supports passing an object with the job method. If you were using an object, pass the job method directly.
E.g. code that previously looked like this:
```javascript
const obj = {
execute() {}
};
Scheduler.scheduleJob(obj);
```
should be changed to something like this:
```javascript
function execute() {}
Scheduler.scheduleJob(execute);
```
'use strict';
const { cancelJob, rescheduleJob, scheduledJobs, scheduleJob} = require('./lib/schedule')
const { Invocation, RecurrenceRule, Range} = require('./lib/Invocation')
const { Job } = require('./lib/Job')
module.exports = {
Job,
Invocation,
Range,
RecurrenceRule,
cancelJob,
rescheduleJob,
scheduledJobs,
scheduleJob
}
'use strict';
const lt = require('long-timeout')
const CronDate = require('cron-parser/lib/date')
const sorted = require('sorted-array-functions')
const invocations = [];
let currentInvocation = null;
/* DoesntRecur rule */
const DoesntRecur = new RecurrenceRule();
DoesntRecur.recurs = false;
/* Invocation object */
function Invocation(job, fireDate, recurrenceRule, endDate) {
this.job = job;
this.fireDate = fireDate;
this.endDate = endDate;
this.recurrenceRule = recurrenceRule || DoesntRecur;
this.timerID = null;
}
function sorter(a, b) {
return (a.fireDate.getTime() - b.fireDate.getTime());
}
/* Range object */
function Range(start, end, step) {
this.start = start || 0;
this.end = end || 60;
this.step = step || 1;
}
Range.prototype.contains = function(val) {
if (this.step === null || this.step === 1) {
return (val >= this.start && val <= this.end);
} else {
for (let i = this.start; i < this.end; i += this.step) {
if (i === val) {
return true;
}
}
return false;
}
};
/* RecurrenceRule object */
/*
Interpreting each property:
null - any value is valid
number - fixed value
Range - value must fall in range
array - value must validate against any item in list
NOTE: Cron months are 1-based, but RecurrenceRule months are 0-based.
*/
function RecurrenceRule(year, month, date, dayOfWeek, hour, minute, second) {
this.recurs = true;
this.year = (year == null) ? null : year;
this.month = (month == null) ? null : month;
this.date = (date == null) ? null : date;
this.dayOfWeek = (dayOfWeek == null) ? null : dayOfWeek;
this.hour = (hour == null) ? null : hour;
this.minute = (minute == null) ? null : minute;
this.second = (second == null) ? 0 : second;
}
RecurrenceRule.prototype.isValid = function() {
function isValidType(num) {
if (Array.isArray(num) || (num instanceof Array)) {
return num.every(function(e) {
return isValidType(e);
});
}
return !(Number.isNaN(Number(num)) && !(num instanceof Range));
}
if (this.month !== null && (this.month < 0 || this.month > 11 || !isValidType(this.month))) {
return false;
}
if (this.dayOfWeek !== null && (this.dayOfWeek < 0 || this.dayOfWeek > 6 || !isValidType(this.dayOfWeek))) {
return false;
}
if (this.hour !== null && (this.hour < 0 || this.hour > 23 || !isValidType(this.hour))) {
return false;
}
if (this.minute !== null && (this.minute < 0 || this.minute > 59 || !isValidType(this.minute))) {
return false;
}
if (this.second !== null && (this.second < 0 || this.second > 59 || !isValidType(this.second))) {
return false;
}
if (this.date !== null) {
if(!isValidType(this.date)) {
return false;
}
switch (this.month) {
case 3:
case 5:
case 8:
case 10:
if (this.date < 1 || this. date > 30) {
return false;
}
break;
case 1:
if (this.date < 1 || this. date > 29) {
return false;
}
break;
default:
if (this.date < 1 || this. date > 31) {
return false;
}
}
}
return true;
};
RecurrenceRule.prototype.nextInvocationDate = function(base) {
const next = this._nextInvocationDate(base);
return next ? next.toDate() : null;
};
RecurrenceRule.prototype._nextInvocationDate = function(base) {
base = ((base instanceof CronDate) || (base instanceof Date)) ? base : (new Date());
if (!this.recurs) {
return null;
}
if(!this.isValid()) {
return null;
}
const now = new CronDate(Date.now(), this.tz);
let fullYear = now.getFullYear();
if ((this.year !== null) &&
(typeof this.year == 'number') &&
(this.year < fullYear)) {
return null;
}
let next = new CronDate(base.getTime(), this.tz);
next.addSecond();
while (true) {
if (this.year !== null) {
fullYear = next.getFullYear();
if ((typeof this.year == 'number') && (this.year < fullYear)) {
next = null;
break;
}
if (!recurMatch(fullYear, this.year)) {
next.addYear();
next.setMonth(0);
next.setDate(1);
next.setHours(0);
next.setMinutes(0);
next.setSeconds(0);
continue;
}
}
if (this.month != null && !recurMatch(next.getMonth(), this.month)) {
next.addMonth();
continue;
}
if (this.date != null && !recurMatch(next.getDate(), this.date)) {
next.addDay();
continue;
}
if (this.dayOfWeek != null && !recurMatch(next.getDay(), this.dayOfWeek)) {
next.addDay();
continue;
}
if (this.hour != null && !recurMatch(next.getHours(), this.hour)) {
next.addHour();
continue;
}
if (this.minute != null && !recurMatch(next.getMinutes(), this.minute)) {
next.addMinute();
continue;
}
if (this.second != null && !recurMatch(next.getSeconds(), this.second)) {
next.addSecond();
continue;
}
break;
}
return next;
};
function recurMatch(val, matcher) {
if (matcher == null) {
return true;
}
if (typeof matcher === 'number') {
return (val === matcher);
} else if(typeof matcher === 'string') {
return (val === Number(matcher));
} else if (matcher instanceof Range) {
return matcher.contains(val);
} else if (Array.isArray(matcher) || (matcher instanceof Array)) {
for (let i = 0; i < matcher.length; i++) {
if (recurMatch(val, matcher[i])) {
return true;
}
}
}
return false;
}
/* Date-based scheduler */
function runOnDate(date, job) {
const now = Date.now();
const then = date.getTime();
return lt.setTimeout(function() {
if (then > Date.now())
runOnDate(date, job);
else
job();
}, (then < now ? 0 : then - now));
}
function scheduleInvocation(invocation) {
sorted.add(invocations, invocation, sorter);
prepareNextInvocation();
const date = invocation.fireDate instanceof CronDate ? invocation.fireDate.toDate() : invocation.fireDate;
invocation.job.emit('scheduled', date);
}
function prepareNextInvocation() {
if (invocations.length > 0 && currentInvocation !== invocations[0]) {
if (currentInvocation !== null) {
lt.clearTimeout(currentInvocation.timerID);
currentInvocation.timerID = null;
currentInvocation = null;
}
currentInvocation = invocations[0];
const job = currentInvocation.job;
const cinv = currentInvocation;
currentInvocation.timerID = runOnDate(currentInvocation.fireDate, function() {
currentInvocationFinished();
if (job.callback) {
job.callback();
}
if (cinv.recurrenceRule.recurs || cinv.recurrenceRule._endDate === null) {
const inv = scheduleNextRecurrence(cinv.recurrenceRule, cinv.job, cinv.fireDate, cinv.endDate);
if (inv !== null) {
inv.job.trackInvocation(inv);
}
}
job.stopTrackingInvocation(cinv);
try {
const result = job.invoke(cinv.fireDate instanceof CronDate ? cinv.fireDate.toDate() : cinv.fireDate);
job.emit('run');
if (result instanceof Promise) {
result.catch(function (err) {
job.emit('error', err);
});
}
} catch (err) {
job.emit('error', err);
}
if (job.isOneTimeJob) {
job.deleteFromSchedule();
}
});
}
}
function currentInvocationFinished() {
invocations.shift();
currentInvocation = null;
prepareNextInvocation();
}
function cancelInvocation(invocation) {
const idx = invocations.indexOf(invocation);
if (idx > -1) {
invocations.splice(idx, 1);
if (invocation.timerID !== null) {
lt.clearTimeout(invocation.timerID);
}
if (currentInvocation === invocation) {
currentInvocation = null;
}
invocation.job.emit('canceled', invocation.fireDate);
prepareNextInvocation();
}
}
/* Recurrence scheduler */
function scheduleNextRecurrence(rule, job, prevDate, endDate) {
prevDate = (prevDate instanceof CronDate) ? prevDate : new CronDate();
const date = (rule instanceof RecurrenceRule) ? rule._nextInvocationDate(prevDate) : rule.next();
if (date === null) {
return null;
}
if ((endDate instanceof CronDate) && date.getTime() > endDate.getTime()) {
return null;
}
const inv = new Invocation(job, date, rule, endDate);
scheduleInvocation(inv);
return inv;
}
module.exports = {
Range,
RecurrenceRule,
Invocation,
cancelInvocation,
scheduleInvocation,
scheduleNextRecurrence,
sorter,
_invocations: invocations
}
'use strict';
const events = require('events')
const cronParser = require('cron-parser')
const CronDate = require('cron-parser/lib/date')
const sorted = require('sorted-array-functions')
const { scheduleNextRecurrence, scheduleInvocation, cancelInvocation, RecurrenceRule, sorter, Invocation } = require('./Invocation')
const { isValidDate } = require('./utils/dateUtils')
const scheduledJobs = {};
let anonJobCounter = 0;
function resolveAnonJobName() {
const now = new Date()
if (anonJobCounter === Number.MAX_SAFE_INTEGER) {
anonJobCounter = 0
}
anonJobCounter++
return `<Anonymous Job ${anonJobCounter} ${now.toISOString()}>`
}
function Job(name, job, callback) {
// setup a private pendingInvocations variable
this.pendingInvocations = [];
//setup a private number of invocations variable
let triggeredJobs = 0;
// Set scope vars
const jobName = name && typeof name === 'string' ? name : resolveAnonJobName();
this.job = name && typeof name === 'function' ? name : job;
// Make sure callback is actually a callback
if (this.job === name) {
// Name wasn't provided and maybe a callback is there
this.callback = typeof job === 'function' ? job : false;
} else {
// Name was provided, and maybe a callback is there
this.callback = typeof callback === 'function' ? callback : false;
}
// Check for generator
if (typeof this.job === 'function' &&
this.job.prototype &&
this.job.prototype.next) {
this.job = function() {
return this.next().value;
}.bind(this.job.call(this));
}
// define properties
Object.defineProperty(this, 'name', {
value: jobName,
writable: false,
enumerable: true
});
// method that require private access
this.trackInvocation = function(invocation) {
// add to our invocation list
sorted.add(this.pendingInvocations, invocation, sorter);
return true;
};
this.stopTrackingInvocation = function(invocation) {
const invIdx = this.pendingInvocations.indexOf(invocation);
if (invIdx > -1) {
this.pendingInvocations.splice(invIdx, 1);
return true;
}
return false;
};
this.triggeredJobs = function() {
return triggeredJobs;
};
this.setTriggeredJobs = function(triggeredJob) {
triggeredJobs = triggeredJob;
};
this.deleteFromSchedule = function() {
deleteScheduledJob(this.name)
};
this.cancel = function(reschedule) {
reschedule = (typeof reschedule == 'boolean') ? reschedule : false;
let inv, newInv;
const newInvs = [];
for (let j = 0; j < this.pendingInvocations.length; j++) {
inv = this.pendingInvocations[j];
cancelInvocation(inv);
if (reschedule && (inv.recurrenceRule.recurs || inv.recurrenceRule.next)) {
newInv = scheduleNextRecurrence(inv.recurrenceRule, this, inv.fireDate, inv.endDate);
if (newInv !== null) {
newInvs.push(newInv);
}
}
}
this.pendingInvocations = [];
for (let k = 0; k < newInvs.length; k++) {
this.trackInvocation(newInvs[k]);
}
// remove from scheduledJobs if reschedule === false
if (!reschedule) {
this.deleteFromSchedule()
}
return true;
};
this.cancelNext = function(reschedule) {
reschedule = (typeof reschedule == 'boolean') ? reschedule : true;
if (!this.pendingInvocations.length) {
return false;
}
let newInv;
const nextInv = this.pendingInvocations.shift();
cancelInvocation(nextInv);
if (reschedule && (nextInv.recurrenceRule.recurs || nextInv.recurrenceRule.next)) {
newInv = scheduleNextRecurrence(nextInv.recurrenceRule, this, nextInv.fireDate, nextInv.endDate);
if (newInv !== null) {
this.trackInvocation(newInv);
}
}
return true;
};
this.reschedule = function(spec) {
let inv;
const invocationsToCancel = this.pendingInvocations.slice();
for (let j = 0; j < invocationsToCancel.length; j++) {
inv = invocationsToCancel[j];
cancelInvocation(inv);
}
this.pendingInvocations = [];
if (this.schedule(spec)) {
this.setTriggeredJobs(0);
return true;
} else {
this.pendingInvocations = invocationsToCancel;
return false;
}
};
this.nextInvocation = function() {
if (!this.pendingInvocations.length) {
return null;
}
return this.pendingInvocations[0].fireDate;
};
}
Object.setPrototypeOf(Job.prototype, events.EventEmitter.prototype);
Job.prototype.invoke = function(fireDate) {
this.setTriggeredJobs(this.triggeredJobs() + 1);
return this.job(fireDate);
};
Job.prototype.runOnDate = function(date) {
return this.schedule(date);
};
Job.prototype.schedule = function(spec) {
const self = this;
let success = false;
let inv;
let start;
let end;
let tz;
// save passed-in value before 'spec' is replaced
if (typeof spec === 'object' && 'tz' in spec) {
tz = spec.tz;
}
if (typeof spec === 'object' && spec.rule) {
start = spec.start || undefined;
end = spec.end || undefined;
spec = spec.rule;
if (start) {
if (!(start instanceof Date)) {
start = new Date(start);
}
start = new CronDate(start, tz);
if (!isValidDate(start) || start.getTime() < Date.now()) {
start = undefined;
}
}
if (end && !(end instanceof Date) && !isValidDate(end = new Date(end))) {
end = undefined;
}
if (end) {
end = new CronDate(end, tz);
}
}
try {
const res = cronParser.parseExpression(spec, {currentDate: start, tz: tz});
inv = scheduleNextRecurrence(res, self, start, end);
if (inv !== null) {
success = self.trackInvocation(inv);
}
} catch (err) {
const type = typeof spec;
if ((type === 'string') || (type === 'number')) {
spec = new Date(spec);
}
if ((spec instanceof Date) && (isValidDate(spec))) {
spec = new CronDate(spec);
self.isOneTimeJob = true;
if (spec.getTime() >= Date.now()) {
inv = new Invocation(self, spec);
scheduleInvocation(inv);
success = self.trackInvocation(inv);
}
} else if (type === 'object') {
self.isOneTimeJob = false;
if (!(spec instanceof RecurrenceRule)) {
const r = new RecurrenceRule();
if ('year' in spec) {
r.year = spec.year;
}
if ('month' in spec) {
r.month = spec.month;
}
if ('date' in spec) {
r.date = spec.date;
}
if ('dayOfWeek' in spec) {
r.dayOfWeek = spec.dayOfWeek;
}
if ('hour' in spec) {
r.hour = spec.hour;
}
if ('minute' in spec) {
r.minute = spec.minute;
}
if ('second' in spec) {
r.second = spec.second;
}
spec = r;
}
spec.tz = tz;
inv = scheduleNextRecurrence(spec, self, start, end);
if (inv !== null) {
success = self.trackInvocation(inv);
}
}
}
scheduledJobs[this.name] = this;
return success;
};
function deleteScheduledJob(name) {
if (name) {
delete scheduledJobs[name];
}
}
module.exports = {
Job,
deleteScheduledJob,
scheduledJobs
}
'use strict';
/*
node-schedule
A cron-like and not-cron-like job scheduler for Node.
*/
const { Job, scheduledJobs } = require('./Job')
/* API
invoke()
runOnDate(date)
schedule(date || recurrenceRule || cronstring)
cancel(reschedule = false)
cancelNext(reschedule = true)
Property constraints
name: readonly
job: readwrite
*/
/* Convenience methods */
function scheduleJob() {
if (arguments.length < 2) {
throw new RangeError('Invalid number of arguments');
}
const name = (arguments.length >= 3 && typeof arguments[0] === 'string') ? arguments[0] : null;
const spec = name ? arguments[1] : arguments[0];
const method = name ? arguments[2] : arguments[1];
const callback = name ? arguments[3] : arguments[2];
if (typeof method !== 'function') {
throw new RangeError('The job method must be a function.');
}
const job = new Job(name, method, callback);
if (job.schedule(spec)) {
return job;
}
return null;
}
function rescheduleJob(job, spec) {
if (job instanceof Job) {
if (job.reschedule(spec)) {
return job;
}
} else if (typeof job === 'string') {
if (scheduledJobs.hasOwnProperty(job)) {
if (scheduledJobs[job].reschedule(spec)) {
return scheduledJobs[job];
}
} else {
throw new Error('Cannot reschedule one-off job by name, pass job reference instead')
}
}
return null;
}
function cancelJob(job) {
let success = false;
if (job instanceof Job) {
success = job.cancel();
} else if (typeof job == 'string' || job instanceof String) {
if (job in scheduledJobs && scheduledJobs.hasOwnProperty(job)) {
success = scheduledJobs[job].cancel();
}
}
return success;
}
/* Public API */
module.exports = {
scheduleJob,
rescheduleJob,
scheduledJobs,
cancelJob
}
'use strict';
function isValidDate(date) {
// Taken from http://stackoverflow.com/a/12372720/1562178
// If getTime() returns NaN it'll return false anyway
return date.getTime() === date.getTime();
}
module.exports = {
isValidDate
}
{
"name": "node-schedule",
"version": "2.0.0",
"description": "A cron-like and not-cron-like job scheduler for Node.",
"keywords": [
"schedule",
"task",
"job",
"cron",
"recurrent",
"in-memory"
],
"license": "MIT",
"main": "index.js",
"scripts": {
"test": "tape test/*.js",
"test:browser": "airtap test/cancel-long-running-jobs.js test/convenience-method-test.js test/date-convenience-methods-test.js test/range-test.js test/recurrence-rule-test.js test/schedule-cron-jobs.js test/start-end-test.js",
"coveralls": "nyc report --reporter=lcov",
"test:coverage": "nyc tape test/*.js",
"lint": "eslint lib test",
"lint:fix": "eslint --fix lib test"
},
"author": {
"name": "Matt Patenaude",
"email": "matt@mattpatenaude.com",
"url": "http://mattpatenaude.com"
},
"contributors": [
{
"name": "Igor Savin",
"email": "kibertoad@gmail.com"
}
],
"repository": {
"type": "git",
"url": "https://github.com/node-schedule/node-schedule.git"
},
"dependencies": {
"cron-parser": "^3.1.0",
"long-timeout": "0.1.1",
"sorted-array-functions": "^1.3.0"
},
"devDependencies": {
"airtap": "^4.0.1",
"eslint": "^7.18.0",
"nyc": "^15.1.0",
"sinon": "^9.2.4",
"tape": "^5.1.1"
},
"engines": {
"node": ">=6"
},
"files": [
"CHANGELOG.md",
"README.md",
"UPGRADING.md",
"LICENSE",
"lib/*"
]
}
root = true
[*]
indent_style = tab;
insert_final_newline = true;
quote_type = auto;
space_after_anonymous_functions = true;
space_after_control_statements = true;
spaces_around_operators = true;
trim_trailing_whitespace = true;
spaces_in_brackets = false;
end_of_line = lf;
{
"root": true,
"extends": "@ljharb",
"rules": {
"complexity": [2, 23],
"id-length": [2, { "min": 1, "max": 40 }],
"max-params": [2, 3],
"max-statements": [2, 23],
"max-statements-per-line": [2, { "max": 2 }],
"no-extra-parens": [1],
"no-invalid-this": [1],
"no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "LabeledStatement", "WithStatement"],
"operator-linebreak": [2, "after"]
}
}
language: node_js
os:
- linux
node_js:
- "11.8"
- "10.15"
- "9.11"
- "8.15"
- "7.10"
- "6.16"
- "5.12"
- "4.9"
- "iojs-v3.3"
- "iojs-v2.5"
- "iojs-v1.8"
- "0.12"
- "0.10"
- "0.8"
before_install:
- 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac'
- 'nvm install-latest-npm'
install:
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;'
script:
- 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi'
- 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi'
- 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi'
- 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi'
sudo: false
env:
- TEST=true
matrix:
fast_finish: true
include:
- node_js: "lts/*"
env: PRETEST=true
- node_js: "lts/*"
env: POSTTEST=true
- node_js: "4"
env: COVERAGE=true
- node_js: "11.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "11.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "11.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "11.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "11.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "11.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "11.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "11.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.14"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.13"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.12"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.14"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.13"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.12"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.15"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.14"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.13"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.12"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.4"
env: TEST=true ALLOW_FAILURE=true
allow_failures:
- os: osx
- env: TEST=true ALLOW_FAILURE=true
- env: COVERAGE=true
- env: POSTTEST=true
1.1.1 / 2019-04-06
=================
* [Fix] exclude deprecated Firefox keys (#53)
1.1.0 / 2019-02-10
=================
* [New] [Refactor] move full implementation to `implementation` entry point
* [Refactor] only evaluate the implementation if `Object.keys` is not present
* [Tests] up to `node` `v11.8`, `v10.15`, `v8.15`, `v6.16`
* [Tests] remove jscs
* [Tests] switch to `npm audit` from `nsp`
1.0.12 / 2018-06-18
=================
* [Fix] avoid accessing `window.applicationCache`, to avoid issues with latest Chrome on HTTP (#46)
1.0.11 / 2016-07-05
=================
* [Fix] exclude keys regarding the style (eg. `pageYOffset`) on `window` to avoid reflow (#32)
1.0.10 / 2016-07-04
=================
* [Fix] exclude `height` and `width` keys on `window` to avoid reflow (#31)
* [Fix] In IE 6, `window.external` makes `Object.keys` throw
* [Tests] up to `node` `v6.2`, `v5.10`, `v4.4`
* [Tests] use pretest/posttest for linting/security
* [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`
* [Dev Deps] remove unused eccheck script + dep
1.0.9 / 2015-10-19
=================
* [Fix] Blacklist 'frame' property on window (#16, #17)
* [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config`
1.0.8 / 2015-10-14
=================
* [Fix] wrap automation equality bug checking in try/catch, per [es5-shim#327](https://github.com/es-shims/es5-shim/issues/327)
* [Fix] Blacklist 'window.frameElement' per [es5-shim#322](https://github.com/es-shims/es5-shim/issues/322)
* [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG
* [Tests] up to `io.js` `v3.3`, `node` `v4.2`
* [Dev Deps] update `eslint`, `tape`, `@ljharb/eslint-config`, `jscs`
1.0.7 / 2015-07-18
=================
* [Fix] A proper fix for 176f03335e90d5c8d0d8125a99f27819c9b9cdad / https://github.com/es-shims/es5-shim/issues/275 that doesn't break dontEnum/constructor fixes in IE 8.
* [Fix] Remove deprecation message in Chrome by touching deprecated window properties (#15)
* [Tests] Improve test output for automation equality bugfix
* [Tests] Test on `io.js` `v2.4`
1.0.6 / 2015-07-09
=================
* [Fix] Use an object lookup rather than ES5's `indexOf` (#14)
* [Tests] ES3 browsers don't have `Array.isArray`
* [Tests] Fix `no-shadow` rule, as well as an IE 8 bug caused by engine NFE shadowing bugs.
1.0.5 / 2015-07-03
=================
* [Fix] Fix a flabbergasting IE 8 bug where `localStorage.constructor.prototype === localStorage` throws
* [Tests] Test up to `io.js` `v2.3`
* [Dev Deps] Update `nsp`, `eslint`
1.0.4 / 2015-05-23
=================
* Fix a Safari 5.0 bug with `Object.keys` not working with `arguments`
* Test on latest `node` and `io.js`
* Update `jscs`, `tape`, `eslint`, `nsp`, `is`, `editorconfig-tools`, `covert`
1.0.3 / 2015-01-06
=================
* Revert "Make `object-keys` more robust against later environment tampering" to maintain ES3 compliance
1.0.2 / 2014-12-28
=================
* Update lots of dev dependencies
* Tweaks to README
* Make `object-keys` more robust against later environment tampering
1.0.1 / 2014-09-03
=================
* Update URLs and badges in README
1.0.0 / 2014-08-26
=================
* v1.0.0
0.6.1 / 2014-08-25
=================
* v0.6.1
* Updating dependencies (tape, covert, is)
* Update badges in readme
* Use separate var statements
0.6.0 / 2014-04-23
=================
* v0.6.0
* Updating dependencies (tape, covert)
* Make sure boxed primitives, and arguments objects, work properly in ES3 browsers
* Improve test matrix: test all node versions, but only latest two stables are a failure
* Remove internal foreach shim.
0.5.1 / 2014-03-09
=================
* 0.5.1
* Updating dependencies (tape, covert, is)
* Removing forEach from the module (but keeping it in tests)
0.5.0 / 2014-01-30
=================
* 0.5.0
* Explicitly returning the shim, instead of returning native Object.keys when present
* Adding a changelog.
* Cleaning up IIFE wrapping
* Testing on node 0.4 through 0.11
0.4.0 / 2013-08-14
==================
* v0.4.0
* In Chrome 4-10 and Safari 4, typeof (new RegExp) === 'function'
* If it's a string, make sure to use charAt instead of brackets.
* Only use Function#call if necessary.
* Making sure the context tests actually run.
* Better function detection
* Adding the android browser
* Fixing testling files
* Updating tape
* Removing the "is" dependency.
* Making an isArguments shim.
* Adding a local forEach shim and tests.
* Updating paths.
* Moving the shim test.
* v0.3.0
0.3.0 / 2013-05-18
==================
* README tweak.
* Fixing constructor enum issue. Fixes [#5](https://github.com/ljharb/object-keys/issues/5).
* Adding a test for [#5](https://github.com/ljharb/object-keys/issues/5)
* Updating readme.
* Updating dependencies.
* Giving credit to lodash.
* Make sure that a prototype's constructor property is not enumerable. Fixes [#3](https://github.com/ljharb/object-keys/issues/3).
* Adding additional tests to handle arguments objects, and to skip "prototype" in functions. Fixes [#2](https://github.com/ljharb/object-keys/issues/2).
* Fixing a typo on this test for [#3](https://github.com/ljharb/object-keys/issues/3).
* Adding node 0.10 to travis.
* Adding an IE < 9 test per [#3](https://github.com/ljharb/object-keys/issues/3)
* Adding an iOS 5 mobile Safari test per [#2](https://github.com/ljharb/object-keys/issues/2)
* Moving "indexof" and "is" to be dev dependencies.
* Making sure the shim works with functions.
* Flattening the tests.
0.2.0 / 2013-05-10
==================
* v0.2.0
* Object.keys should work with arrays.
0.1.8 / 2013-05-10
==================
* v0.1.8
* Upgrading dependencies.
* Using a simpler check.
* Fixing a bug in hasDontEnumBug browsers.
* Using the newest tape!
* Fixing this error test.
* "undefined" is probably a reserved word in ES3.
* Better test message.
0.1.7 / 2013-04-17
==================
* Upgrading "is" once more.
* The key "null" is breaking some browsers.
0.1.6 / 2013-04-17
==================
* v0.1.6
* Upgrading "is"
0.1.5 / 2013-04-14
==================
* Bumping version.
* Adding more testling browsers.
* Updating "is"
0.1.4 / 2013-04-08
==================
* Using "is" instead of "is-extended".
0.1.3 / 2013-04-07
==================
* Using "foreach" instead of my own shim.
* Removing "tap"; I'll just wait for "tape" to fix its node 0.10 bug.
0.1.2 / 2013-04-03
==================
* Adding dependency status; moving links to an index at the bottom.
* Upgrading is-extended; version 0.1.2
* Adding an npm version badge.
0.1.1 / 2013-04-01
==================
* Adding Travis CI.
* Bumping the version.
* Adding indexOf since IE sucks.
* Adding a forEach shim since older browsers don't have Array#forEach.
* Upgrading tape - 0.3.2 uses Array#map
* Using explicit end instead of plan.
* Can't test with Array.isArray in older browsers.
* Using is-extended.
* Fixing testling files.
* JSHint/JSLint-ing.
* Removing an unused object.
* Using strict mode.
0.1.0 / 2013-03-30
==================
* Changing the exports should have meant a higher version bump.
* Oops, fixing the repo URL.
* Adding more tests.
* 0.0.2
* Merge branch 'export_one_thing'; closes [#1](https://github.com/ljharb/object-keys/issues/1)
* Move shim export to a separate file.
The MIT License (MIT)
Copyright (C) 2013 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
#object-keys <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![Build Status][travis-svg]][travis-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
[![browser support][testling-svg]][testling-url]
An Object.keys shim. Invoke its "shim" method to shim Object.keys if it is unavailable.
Most common usage:
```js
var keys = Object.keys || require('object-keys');
```
## Example
```js
var keys = require('object-keys');
var assert = require('assert');
var obj = {
a: true,
b: true,
c: true
};
assert.deepEqual(keys(obj), ['a', 'b', 'c']);
```
```js
var keys = require('object-keys');
var assert = require('assert');
/* when Object.keys is not present */
delete Object.keys;
var shimmedKeys = keys.shim();
assert.equal(shimmedKeys, keys);
assert.deepEqual(Object.keys(obj), keys(obj));
```
```js
var keys = require('object-keys');
var assert = require('assert');
/* when Object.keys is present */
var shimmedKeys = keys.shim();
assert.equal(shimmedKeys, Object.keys);
assert.deepEqual(Object.keys(obj), keys(obj));
```
## Source
Implementation taken directly from [es5-shim][es5-shim-url], with modifications, including from [lodash][lodash-url].
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[package-url]: https://npmjs.org/package/object-keys
[npm-version-svg]: http://versionbadg.es/ljharb/object-keys.svg
[travis-svg]: https://travis-ci.org/ljharb/object-keys.svg
[travis-url]: https://travis-ci.org/ljharb/object-keys
[deps-svg]: https://david-dm.org/ljharb/object-keys.svg
[deps-url]: https://david-dm.org/ljharb/object-keys
[dev-deps-svg]: https://david-dm.org/ljharb/object-keys/dev-status.svg
[dev-deps-url]: https://david-dm.org/ljharb/object-keys#info=devDependencies
[testling-svg]: https://ci.testling.com/ljharb/object-keys.png
[testling-url]: https://ci.testling.com/ljharb/object-keys
[es5-shim-url]: https://github.com/es-shims/es5-shim/blob/master/es5-shim.js#L542-589
[lodash-url]: https://github.com/lodash/lodash
[npm-badge-png]: https://nodei.co/npm/object-keys.png?downloads=true&stars=true
[license-image]: http://img.shields.io/npm/l/object-keys.svg
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/object-keys.svg
[downloads-url]: http://npm-stat.com/charts.html?package=object-keys
'use strict';
var keysShim;
if (!Object.keys) {
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var isArgs = require('./isArguments'); // eslint-disable-line global-require
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$applicationCache: true,
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$onmozfullscreenchange: true,
$onmozfullscreenerror: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
}
module.exports = keysShim;
'use strict';
var slice = Array.prototype.slice;
var isArgs = require('./isArguments');
var origKeys = Object.keys;
var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation');
var originalKeys = Object.keys;
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
var args = Object.keys(arguments);
return args && args.length === arguments.length;
}(1, 2));
if (!keysWorksWithArguments) {
Object.keys = function keys(object) { // eslint-disable-line func-name-matching
if (isArgs(object)) {
return originalKeys(slice.call(object));
}
return originalKeys(object);
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
'use strict';
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
{
"name": "object-keys",
"version": "1.1.1",
"author": {
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
},
"contributors": [
{
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
},
{
"name": "Raynos",
"email": "raynos2@gmail.com"
},
{
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net"
},
{
"name": "Ivan Starkov",
"email": "istarkov@gmail.com"
},
{
"name": "Gary Katsevman",
"email": "git@gkatsev.com"
}
],
"description": "An Object.keys replacement, in case Object.keys is not available. From https://github.com/es-shims/es5-shim",
"license": "MIT",
"main": "index.js",
"scripts": {
"pretest": "npm run --silent lint",
"test": "npm run --silent tests-only",
"posttest": "npm run --silent audit",
"tests-only": "node test/index.js",
"coverage": "covert test/*.js",
"coverage-quiet": "covert test/*.js --quiet",
"lint": "eslint .",
"preaudit": "npm install --package-lock --package-lock-only",
"audit": "npm audit",
"postaudit": "rm package-lock.json"
},
"repository": {
"type": "git",
"url": "git://github.com/ljharb/object-keys.git"
},
"keywords": [
"Object.keys",
"keys",
"ES5",
"shim"
],
"dependencies": {},
"devDependencies": {
"@ljharb/eslint-config": "^13.1.1",
"covert": "^1.1.1",
"eslint": "^5.13.0",
"foreach": "^2.0.5",
"indexof": "^0.0.1",
"is": "^3.3.0",
"tape": "^4.9.2"
},
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
}
}
'use strict';
require('./isArguments');
require('./shim');
language: node_js
node_js:
- '0.10'
- '0.12'
- '4'
- '6'
The MIT License (MIT)
Copyright (c) 2016 Mathias Buus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# sorted-array-functions
Maintain and search through a sorted array using some low level functions
```
npm install sorted-array-functions
```
[![build status](http://img.shields.io/travis/mafintosh/sorted-array-functions.svg?style=flat)](http://travis-ci.org/mafintosh/sorted-array-functions)
## Usage
``` js
var sorted = require('sorted-array-functions')
var list = []
sorted.add(list, 1)
sorted.add(list, 4)
sorted.add(list, 2)
console.log(list) // prints out [1, 2, 4]
console.log(sorted.has(list, 2)) // returns true
console.log(sorted.has(list, 3)) // returns false
console.log(sorted.eq(list, 2)) // returns 1 (the index)
console.log(sorted.gt(list, 2)) // returns 2
console.log(sorted.gt(list, 4)) // returns -1
```
## API
#### `sorted.add(list, value, [compare])`
Insert a new value into the list sorted.
Optionally you can use a custom compare function that returns, `compare(a, b)` that returns 1 if `a > b`, 0 if `a === b` and -1 if `a < b`.
#### `sorted.addFromFront(list, value, [compare])`
Inserts a new value (same result as `sorted.add()`) optimized for prepend.
#### `var bool = sorted.remove(list, value, [compare])`
Remove a value. Returns true if the value was in the list.
#### `var bool = sorted.has(list, value, [compare])`
Check if a value is in the list.
#### `var index = sorted.eq(list, value, [compare])`
Get the index of a value in the list (uses binary search).
If the value could not be found -1 is returned.
#### `var index = sorted.gte(list, value, [compare])`
Get the index of the first value that is `>=`.
If the value could not be found -1 is returned.
#### `var index = sorted.gt(list, value, [compare])`
Get the index of the first value that is `>`.
If the value could not be found -1 is returned.
#### `var index = sorted.lte(list, value, [compare])`
Get the index of the first value that is `<=`.
If the value could not be found -1 is returned.
#### `var index = sorted.lt(list, value, [compare])`
Get the index of the first value that is `<`.
If the value could not be found -1 is returned.
## License
MIT
var sorted = require('./')
var list = []
sorted.add(list, 1)
sorted.add(list, 4)
sorted.add(list, 2)
console.log(list) // prints out [1, 2, 4]
console.log(sorted.has(list, 2)) // returns true
console.log(sorted.has(list, 3)) // returns false
console.log(sorted.eq(list, 2)) // returns 1 (the index)
console.log(sorted.gt(list, 2)) // returns 2
console.log(sorted.gt(list, 4)) // returns -1
exports.add = add
exports.addFromFront = addFromFront
exports.remove = remove
exports.has = has
exports.eq = eq
exports.lte = lte
exports.lt = lt
exports.gte = gte
exports.gt = gt
exports.nearest = nearest
function defaultCmp (a, b) {
if (a === b) return 0
return a < b ? -1 : 1
}
function add (list, value, cmp) {
if (!cmp) cmp = defaultCmp
var top = list.push(value) - 1
while (top) {
if (cmp(list[top - 1], value) < 0) return
list[top] = list[top - 1]
list[top - 1] = value
top--
}
}
function addFromFront (list, value, cmp) {
if (!cmp) cmp = defaultCmp
var top = list.unshift(value) - 1
for (var i = 0; i < top; i++) {
if (cmp(value, list[i + 1]) < 0) return
list[i] = list[i + 1]
list[i + 1] = value
}
}
function lte (list, value, cmp) {
if (!cmp) cmp = defaultCmp
var i = indexOf(list, value, cmp)
if (i === -1) return -1
for (; i >= 0; i--) {
var c = cmp(list[i], value)
if (c <= 0) return i
}
return -1
}
function lt (list, value, cmp) {
if (!cmp) cmp = defaultCmp
var i = indexOf(list, value, cmp)
if (i === -1) return -1
for (; i >= 0; i--) {
var c = cmp(list[i], value)
if (c < 0) return i
}
return -1
}
function gte (list, value, cmp) {
if (!cmp) cmp = defaultCmp
var i = indexOf(list, value, cmp)
if (i === -1) return -1
for (; i < list.length; i++) {
var c = cmp(list[i], value)
if (c >= 0) return i
}
return -1
}
function gt (list, value, cmp) {
if (!cmp) cmp = defaultCmp
var i = indexOf(list, value, cmp)
if (i === -1) return -1
for (; i < list.length; i++) {
var c = cmp(list[i], value)
if (c > 0) return i
}
return -1
}
function eq (list, value, cmp) {
if (!cmp) cmp = defaultCmp
var i = indexOf(list, value, cmp)
if (i === -1) return -1
return cmp(list[i], value) === 0 ? i : -1
}
function nearest (list, value, cmp) {
if (!cmp) cmp = defaultCmp
var len = list.length
var top = len - 1
var btm = 0
var mid = -1
var trending = 1 // 0 = down, 2 = up
while (top >= btm && btm >= 0 && top < len) {
mid = Math.floor((top + btm) / 2)
var c = cmp(list[mid], value)
if (c === 0) return mid
if (c >= 0) {
if (trending === 1) trending = 0
else if (trending === 2) {
if (Math.abs(list[mid] - value) > Math.abs(list[mid - 1] - value)) return mid - 1
return mid
}
top = mid - 1
} else {
if (trending === 1) trending = 2
else if (trending === 0) return mid
btm = mid + 1
}
}
return mid
}
function indexOf (list, value, cmp) {
if (!cmp) cmp = defaultCmp
var len = list.length
var top = len - 1
var btm = 0
var mid = -1
while (top >= btm && btm >= 0 && top < len) {
mid = Math.floor((top + btm) / 2)
var c = cmp(list[mid], value)
if (c === 0) return mid
if (c >= 0) {
top = mid - 1
} else {
btm = mid + 1
}
}
return mid
}
function has (list, value, cmp) {
return eq(list, value, cmp) > -1
}
function remove (list, value, cmp) {
var i = eq(list, value, cmp)
if (i === -1) return false
list.splice(i, 1)
return true
}
{
"name": "sorted-array-functions",
"version": "1.3.0",
"description": "Maintain and search through a sorted array using some low level functions",
"main": "index.js",
"dependencies": {},
"devDependencies": {
"standard": "^8.4.0",
"tape": "^4.6.2"
},
"scripts": {
"test": "standard && tape test.js"
},
"repository": {
"type": "git",
"url": "https://github.com/mafintosh/sorted-array-functions.git"
},
"author": "Mathias Buus (@mafintosh)",
"license": "MIT",
"bugs": {
"url": "https://github.com/mafintosh/sorted-array-functions/issues"
},
"homepage": "https://github.com/mafintosh/sorted-array-functions"
}
var tape = require('tape')
var sorted = require('./')
tape('add', function (t) {
var list = []
sorted.add(list, 3)
sorted.add(list, 4)
sorted.add(list, 3)
sorted.add(list, 9)
sorted.add(list, 0)
sorted.add(list, 5)
sorted.add(list, 8)
t.same(list, [0, 3, 3, 4, 5, 8, 9])
t.end()
})
tape('addFromFront', function (t) {
var list = []
sorted.addFromFront(list, 3)
sorted.addFromFront(list, 4)
sorted.addFromFront(list, 3)
sorted.addFromFront(list, 9)
sorted.addFromFront(list, 0)
sorted.addFromFront(list, 5)
sorted.addFromFront(list, 8)
t.same(list, [0, 3, 3, 4, 5, 8, 9])
t.end()
})
tape('remove', function (t) {
var list = []
sorted.add(list, 3)
sorted.add(list, 4)
sorted.add(list, 3)
sorted.add(list, 9)
sorted.add(list, 0)
sorted.add(list, 5)
sorted.add(list, 8)
sorted.remove(list, 3)
sorted.remove(list, 5)
sorted.remove(list, 6)
t.same(list, [0, 3, 4, 8, 9])
t.end()
})
tape('has', function (t) {
var list = []
sorted.add(list, 3)
t.same(sorted.has(list, 3), true)
t.same(sorted.has(list, 2), false)
sorted.add(list, 5)
t.same(sorted.has(list, 5), true)
t.same(sorted.has(list, 3), true)
t.same(sorted.has(list, 2), false)
sorted.add(list, 1)
t.same(sorted.has(list, 1), true)
t.same(sorted.has(list, 5), true)
t.same(sorted.has(list, 3), true)
t.same(sorted.has(list, 2), false)
t.same(sorted.has(list, 8), false)
t.end()
})
tape('eq', function (t) {
var list = []
sorted.add(list, 3)
t.same(sorted.eq(list, 3), 0)
t.same(sorted.eq(list, 2), -1)
sorted.add(list, 5)
t.same(sorted.eq(list, 5), 1)
t.same(sorted.eq(list, 3), 0)
t.same(sorted.eq(list, 2), -1)
sorted.add(list, 1)
t.same(sorted.eq(list, 1), 0)
t.same(sorted.eq(list, 5), 2)
t.same(sorted.eq(list, 3), 1)
t.same(sorted.eq(list, 2), -1)
t.same(sorted.eq(list, 8), -1)
t.end()
})
tape('gte', function (t) {
var list = []
sorted.add(list, 3)
t.same(sorted.gte(list, 3), 0)
t.same(sorted.gte(list, 2), 0)
sorted.add(list, 5)
t.same(sorted.gte(list, 5), 1)
t.same(sorted.gte(list, 3), 0)
t.same(sorted.gte(list, 2), 0)
sorted.add(list, 1)
t.same(sorted.gte(list, 1), 0)
t.same(sorted.gte(list, 5), 2)
t.same(sorted.gte(list, 3), 1)
t.same(sorted.gte(list, 2), 1)
t.same(sorted.gte(list, 8), -1)
t.end()
})
tape('gt', function (t) {
var list = []
sorted.add(list, 3)
t.same(sorted.gt(list, 3), -1)
t.same(sorted.gt(list, 2), 0)
sorted.add(list, 5)
t.same(sorted.gt(list, 5), -1)
t.same(sorted.gt(list, 3), 1)
t.same(sorted.gt(list, 2), 0)
sorted.add(list, 1)
t.same(sorted.gt(list, 1), 1)
t.same(sorted.gt(list, 5), -1)
t.same(sorted.gt(list, 3), 2)
t.same(sorted.gt(list, 2), 1)
t.same(sorted.gt(list, 8), -1)
t.end()
})
tape('lte', function (t) {
var list = []
sorted.add(list, 3)
t.same(sorted.lte(list, 3), 0)
t.same(sorted.lte(list, 2), -1)
sorted.add(list, 5)
t.same(sorted.lte(list, 6), 1)
t.same(sorted.lte(list, 5), 1)
t.same(sorted.lte(list, 3), 0)
t.same(sorted.lte(list, 2), -1)
sorted.add(list, 1)
t.same(sorted.lte(list, 1), 0)
t.same(sorted.lte(list, 5), 2)
t.same(sorted.lte(list, 3), 1)
t.same(sorted.lte(list, 2), 0)
t.same(sorted.lte(list, 8), 2)
t.end()
})
tape('lt', function (t) {
var list = []
sorted.add(list, 3)
t.same(sorted.lt(list, 3), -1)
t.same(sorted.lt(list, 2), -1)
t.same(sorted.lt(list, 4), 0)
sorted.add(list, 5)
t.same(sorted.lt(list, 6), 1)
t.same(sorted.lt(list, 5), 0)
t.same(sorted.lt(list, 3), -1)
t.same(sorted.lt(list, 2), -1)
sorted.add(list, 1)
t.same(sorted.lt(list, 1), -1)
t.same(sorted.lt(list, 5), 1)
t.same(sorted.lt(list, 3), 0)
t.same(sorted.lt(list, 2), 0)
t.same(sorted.lt(list, 8), 2)
t.end()
})
tape('custom compare add', function (t) {
var list = []
sorted.add(list, {foo: 3}, cmp)
sorted.add(list, {foo: 4}, cmp)
sorted.add(list, {foo: 3}, cmp)
sorted.add(list, {foo: 9}, cmp)
sorted.add(list, {foo: 0}, cmp)
sorted.add(list, {foo: 5}, cmp)
sorted.add(list, {foo: 8}, cmp)
t.same(list, [{foo: 0}, {foo: 3}, {foo: 3}, {foo: 4}, {foo: 5}, {foo: 8}, {foo: 9}])
t.end()
})
tape('custom compare remove', function (t) {
var list = []
sorted.add(list, {foo: 3}, cmp)
sorted.add(list, {foo: 4}, cmp)
sorted.add(list, {foo: 3}, cmp)
sorted.add(list, {foo: 9}, cmp)
sorted.add(list, {foo: 0}, cmp)
sorted.add(list, {foo: 5}, cmp)
sorted.add(list, {foo: 8}, cmp)
sorted.remove(list, {foo: 3}, cmp)
sorted.remove(list, {foo: 5}, cmp)
sorted.remove(list, {foo: 6}, cmp)
t.same(list, [{foo: 0}, {foo: 3}, {foo: 4}, {foo: 8}, {foo: 9}])
t.end()
})
tape('custom compare has', function (t) {
var list = []
sorted.add(list, {foo: 3}, cmp)
t.same(sorted.has(list, {foo: 3}, cmp), true)
t.same(sorted.has(list, {foo: 2}, cmp), false)
sorted.add(list, {foo: 5}, cmp)
t.same(sorted.has(list, {foo: 5}, cmp), true)
t.same(sorted.has(list, {foo: 3}, cmp), true)
t.same(sorted.has(list, {foo: 2}, cmp), false)
sorted.add(list, {foo: 1}, cmp)
t.same(sorted.has(list, {foo: 1}, cmp), true)
t.same(sorted.has(list, {foo: 5}, cmp), true)
t.same(sorted.has(list, {foo: 3}, cmp), true)
t.same(sorted.has(list, {foo: 2}, cmp), false)
t.same(sorted.has(list, {foo: 8}, cmp), false)
t.end()
})
tape('custom compare eq', function (t) {
var list = []
sorted.add(list, {foo: 3}, cmp)
t.same(sorted.eq(list, {foo: 3}, cmp), 0)
t.same(sorted.eq(list, {foo: 2}, cmp), -1)
sorted.add(list, {foo: 5}, cmp)
t.same(sorted.eq(list, {foo: 5}, cmp), 1)
t.same(sorted.eq(list, {foo: 3}, cmp), 0)
t.same(sorted.eq(list, {foo: 2}, cmp), -1)
sorted.add(list, {foo: 1}, cmp)
t.same(sorted.eq(list, {foo: 1}, cmp), 0)
t.same(sorted.eq(list, {foo: 5}, cmp), 2)
t.same(sorted.eq(list, {foo: 3}, cmp), 1)
t.same(sorted.eq(list, {foo: 2}, cmp), -1)
t.same(sorted.eq(list, {foo: 8}, cmp), -1)
t.end()
})
tape('custom compare gte', function (t) {
var list = []
sorted.add(list, {foo: 3}, cmp)
t.same(sorted.gte(list, {foo: 3}, cmp), 0)
t.same(sorted.gte(list, {foo: 2}, cmp), 0)
sorted.add(list, {foo: 5}, cmp)
t.same(sorted.gte(list, {foo: 5}, cmp), 1)
t.same(sorted.gte(list, {foo: 3}, cmp), 0)
t.same(sorted.gte(list, {foo: 2}, cmp), 0)
sorted.add(list, {foo: 1}, cmp)
t.same(sorted.gte(list, {foo: 1}, cmp), 0)
t.same(sorted.gte(list, {foo: 5}, cmp), 2)
t.same(sorted.gte(list, {foo: 3}, cmp), 1)
t.same(sorted.gte(list, {foo: 2}, cmp), 1)
t.same(sorted.gte(list, {foo: 8}, cmp), -1)
t.end()
})
tape('custom compare gt', function (t) {
var list = []
sorted.add(list, {foo: 3}, cmp)
t.same(sorted.gt(list, {foo: 3}, cmp), -1)
t.same(sorted.gt(list, {foo: 2}, cmp), 0)
sorted.add(list, {foo: 5}, cmp)
t.same(sorted.gt(list, {foo: 5}, cmp), -1)
t.same(sorted.gt(list, {foo: 3}, cmp), 1)
t.same(sorted.gt(list, {foo: 2}, cmp), 0)
sorted.add(list, {foo: 1}, cmp)
t.same(sorted.gt(list, {foo: 1}, cmp), 1)
t.same(sorted.gt(list, {foo: 5}, cmp), -1)
t.same(sorted.gt(list, {foo: 3}, cmp), 2)
t.same(sorted.gt(list, {foo: 2}, cmp), 1)
t.same(sorted.gt(list, {foo: 8}, cmp), -1)
t.end()
})
tape('custom compare lte', function (t) {
var list = []
sorted.add(list, {foo: 3}, cmp)
t.same(sorted.lte(list, {foo: 3}, cmp), 0)
t.same(sorted.lte(list, {foo: 2}, cmp), -1)
sorted.add(list, {foo: 5}, cmp)
t.same(sorted.lte(list, {foo: 6}, cmp), 1)
t.same(sorted.lte(list, {foo: 5}, cmp), 1)
t.same(sorted.lte(list, {foo: 3}, cmp), 0)
t.same(sorted.lte(list, {foo: 2}, cmp), -1)
sorted.add(list, {foo: 1}, cmp)
t.same(sorted.lte(list, {foo: 1}, cmp), 0)
t.same(sorted.lte(list, {foo: 5}, cmp), 2)
t.same(sorted.lte(list, {foo: 3}, cmp), 1)
t.same(sorted.lte(list, {foo: 2}, cmp), 0)
t.same(sorted.lte(list, {foo: 8}, cmp), 2)
t.end()
})
tape('custom compare lt', function (t) {
var list = []
sorted.add(list, {foo: 3}, cmp)
t.same(sorted.lt(list, {foo: 3}, cmp), -1)
t.same(sorted.lt(list, {foo: 2}, cmp), -1)
t.same(sorted.lt(list, {foo: 4}, cmp), 0)
sorted.add(list, {foo: 5}, cmp)
t.same(sorted.lt(list, {foo: 6}, cmp), 1)
t.same(sorted.lt(list, {foo: 5}, cmp), 0)
t.same(sorted.lt(list, {foo: 3}, cmp), -1)
t.same(sorted.lt(list, {foo: 2}, cmp), -1)
sorted.add(list, {foo: 1}, cmp)
t.same(sorted.lt(list, {foo: 1}, cmp), -1)
t.same(sorted.lt(list, {foo: 5}, cmp), 1)
t.same(sorted.lt(list, {foo: 3}, cmp), 0)
t.same(sorted.lt(list, {foo: 2}, cmp), 0)
t.same(sorted.lt(list, {foo: 8}, cmp), 2)
t.end()
})
tape('find nearest value', function (t) {
var list = []
sorted.add(list, 0.001)
sorted.add(list, 10)
sorted.add(list, 20)
sorted.add(list, 30)
sorted.add(list, 40)
sorted.add(list, 50)
sorted.add(list, 70)
t.equal(sorted.nearest(list, 66), 6)
t.equal(sorted.nearest(list, 51), 5)
t.equal(sorted.nearest(list, 1), 0)
t.equal(sorted.nearest(list, 0), 0)
t.equal(sorted.nearest(list, 69.999), 6)
t.equal(sorted.nearest(list, 72), 6)
t.end()
})
function cmp (a, b) {
return a.foo - b.foo
}
......@@ -11,6 +11,7 @@
"dependencies": {
"cheerio": "^1.0.0-rc.9",
"express": "^4.17.1",
"node-schedule": "^2.0.0",
"puppeteer": "^9.1.1",
"sanitize-html": "^2.3.3"
}
......@@ -191,6 +192,18 @@
"node": ">= 0.8"
}
},
"node_modules/call-bind": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
"integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==",
"dependencies": {
"function-bind": "^1.1.1",
"get-intrinsic": "^1.0.2"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/cheerio": {
"version": "1.0.0-rc.9",
"resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.9.tgz",
......@@ -273,6 +286,18 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
},
"node_modules/cron-parser": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-3.5.0.tgz",
"integrity": "sha512-wyVZtbRs6qDfFd8ap457w3XVntdvqcwBGxBoTvJQH9KGVKL/fB+h2k3C8AqiVxvUQKN1Ps/Ns46CNViOpVDhfQ==",
"dependencies": {
"is-nan": "^1.3.2",
"luxon": "^1.26.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/css-select": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/css-select/-/css-select-4.1.2.tgz",
......@@ -315,6 +340,17 @@
"node": ">=0.10.0"
}
},
"node_modules/define-properties": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz",
"integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==",
"dependencies": {
"object-keys": "^1.0.12"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
......@@ -581,6 +617,24 @@
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8="
},
"node_modules/function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
"integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A=="
},
"node_modules/get-intrinsic": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz",
"integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==",
"dependencies": {
"function-bind": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.1"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-stream": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
......@@ -614,6 +668,28 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/has": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
"integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
"dependencies": {
"function-bind": "^1.1.1"
},
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/has-symbols": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz",
"integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/htmlparser2": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-6.1.0.tgz",
......@@ -732,6 +808,21 @@
"node": ">= 0.10"
}
},
"node_modules/is-nan": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/is-nan/-/is-nan-1.3.2.tgz",
"integrity": "sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w==",
"dependencies": {
"call-bind": "^1.0.0",
"define-properties": "^1.1.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-plain-object": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
......@@ -759,6 +850,19 @@
"node": ">=8"
}
},
"node_modules/long-timeout": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/long-timeout/-/long-timeout-0.1.1.tgz",
"integrity": "sha1-lyHXiLR+C8taJMLivuGg2lXatRQ="
},
"node_modules/luxon": {
"version": "1.27.0",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-1.27.0.tgz",
"integrity": "sha512-VKsFsPggTA0DvnxtJdiExAucKdAnwbCCNlMM5ENvHlxubqWd0xhZcdb4XgZ7QFNhaRhilXCFxHuoObP5BNA4PA==",
"engines": {
"node": "*"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
......@@ -858,6 +962,19 @@
"node": "4.x || >=6.0.0"
}
},
"node_modules/node-schedule": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/node-schedule/-/node-schedule-2.0.0.tgz",
"integrity": "sha512-cHc9KEcfiuXxYDU+HjsBVo2FkWL1jRAUoczFoMIzRBpOA4p/NRHuuLs85AWOLgKsHtSPjN8csvwIxc2SqMv+CQ==",
"dependencies": {
"cron-parser": "^3.1.0",
"long-timeout": "0.1.1",
"sorted-array-functions": "^1.3.0"
},
"engines": {
"node": ">=6"
}
},
"node_modules/nth-check": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.0.0.tgz",
......@@ -869,6 +986,14 @@
"url": "https://github.com/fb55/nth-check?sponsor=1"
}
},
"node_modules/object-keys": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
......@@ -1207,6 +1332,11 @@
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
"integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw=="
},
"node_modules/sorted-array-functions": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/sorted-array-functions/-/sorted-array-functions-1.3.0.tgz",
"integrity": "sha512-2sqgzeFlid6N4Z2fUQ1cvFmTOLRi/sEDzSQ0OKYchqgoPmQBVyM3959qYx3fpS6Esef80KjmpgPeEr028dP3OA=="
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
......@@ -1509,6 +1639,15 @@
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
"integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg=="
},
"call-bind": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
"integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==",
"requires": {
"function-bind": "^1.1.1",
"get-intrinsic": "^1.0.2"
}
},
"cheerio": {
"version": "1.0.0-rc.9",
"resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.9.tgz",
......@@ -1573,6 +1712,15 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
},
"cron-parser": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-3.5.0.tgz",
"integrity": "sha512-wyVZtbRs6qDfFd8ap457w3XVntdvqcwBGxBoTvJQH9KGVKL/fB+h2k3C8AqiVxvUQKN1Ps/Ns46CNViOpVDhfQ==",
"requires": {
"is-nan": "^1.3.2",
"luxon": "^1.26.0"
}
},
"css-select": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/css-select/-/css-select-4.1.2.tgz",
......@@ -1603,6 +1751,14 @@
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz",
"integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg=="
},
"define-properties": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz",
"integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==",
"requires": {
"object-keys": "^1.0.12"
}
},
"depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
......@@ -1803,6 +1959,21 @@
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8="
},
"function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
"integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A=="
},
"get-intrinsic": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz",
"integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==",
"requires": {
"function-bind": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.1"
}
},
"get-stream": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
......@@ -1824,6 +1995,19 @@
"path-is-absolute": "^1.0.0"
}
},
"has": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
"integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
"requires": {
"function-bind": "^1.1.1"
}
},
"has-symbols": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz",
"integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw=="
},
"htmlparser2": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-6.1.0.tgz",
......@@ -1903,6 +2087,15 @@
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="
},
"is-nan": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/is-nan/-/is-nan-1.3.2.tgz",
"integrity": "sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w==",
"requires": {
"call-bind": "^1.0.0",
"define-properties": "^1.1.3"
}
},
"is-plain-object": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
......@@ -1921,6 +2114,16 @@
"p-locate": "^4.1.0"
}
},
"long-timeout": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/long-timeout/-/long-timeout-0.1.1.tgz",
"integrity": "sha1-lyHXiLR+C8taJMLivuGg2lXatRQ="
},
"luxon": {
"version": "1.27.0",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-1.27.0.tgz",
"integrity": "sha512-VKsFsPggTA0DvnxtJdiExAucKdAnwbCCNlMM5ENvHlxubqWd0xhZcdb4XgZ7QFNhaRhilXCFxHuoObP5BNA4PA=="
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
......@@ -1987,6 +2190,16 @@
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz",
"integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw=="
},
"node-schedule": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/node-schedule/-/node-schedule-2.0.0.tgz",
"integrity": "sha512-cHc9KEcfiuXxYDU+HjsBVo2FkWL1jRAUoczFoMIzRBpOA4p/NRHuuLs85AWOLgKsHtSPjN8csvwIxc2SqMv+CQ==",
"requires": {
"cron-parser": "^3.1.0",
"long-timeout": "0.1.1",
"sorted-array-functions": "^1.3.0"
}
},
"nth-check": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.0.0.tgz",
......@@ -1995,6 +2208,11 @@
"boolbase": "^1.0.0"
}
},
"object-keys": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="
},
"on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
......@@ -2261,6 +2479,11 @@
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
"integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw=="
},
"sorted-array-functions": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/sorted-array-functions/-/sorted-array-functions-1.3.0.tgz",
"integrity": "sha512-2sqgzeFlid6N4Z2fUQ1cvFmTOLRi/sEDzSQ0OKYchqgoPmQBVyM3959qYx3fpS6Esef80KjmpgPeEr028dP3OA=="
},
"source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
......
......@@ -16,6 +16,7 @@
"dependencies": {
"cheerio": "^1.0.0-rc.9",
"express": "^4.17.1",
"node-schedule": "^2.0.0",
"puppeteer": "^9.1.1",
"sanitize-html": "^2.3.3"
}
......