Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Manc committed May 20, 2021
0 parents commit 1228e4b
Show file tree
Hide file tree
Showing 17 changed files with 4,409 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/node_modules
/dist
/src/zones.ts
9 changes: 9 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
language: node_js
node_js:
- stable
install:
- npm install
before_script:
- npm run build-zones
script:
- npm test
15 changes: 15 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
ISC License

Copyright (c) 2021, Nick Singleton

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
90 changes: 90 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# iCalzone 🗓🌎

[![Build Status][travis-image]][travis-url]
[![NPM version][npm-version-image]][npm-url]
[![Size][min-size-image]][npm-url]
[![MIT License][license-image]][license-url]

**iCalzone** is a light-weight utility written in TypeScript that resolves time zone strings to iCalendar-compatible `VTIMEZONE` components fast.

All time zone information is stored in-memory and rendered on demand.

The time zone data is based on [@touch4it/ical-timezones](https://github.com/touch4it/ical-timezones), but reduced and somewhat compressed. Opposed to **@touch4it/ical-timezones**, this library does not require runtime disk access to look up and parse ICS files, which makes **iCalzone** much faster, although a bit more memory may be used, of course.

To look up a time zone, you must use the [TZ database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with the two-part format `*/*`, such as `America/Los_Angeles` or `Etc/UTC`.


## 📦 Installation

```sh
yarn add icalzone
# or
npm install icalzone
```


## ⚡️ Quick Start

```typescript
import { getZoneLines, getZoneString } from 'icalzone';

const asArray = getZoneLines('Europe/London');
console.log(asArray);
/*
[
'BEGIN:VTIMEZONE',
'TZID:Europe/London',
'BEGIN:STANDARD',
'TZNAME:GMT',
'TZOFFSETFROM:+0100',
'TZOFFSETTO:+0000',
'DTSTART:19701025T020000',
'RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU',
'END:STANDARD',
'BEGIN:DAYLIGHT',
'TZNAME:BST',
'TZOFFSETFROM:+0000',
'TZOFFSETTO:+0100',
'DTSTART:19700329T010000',
'RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU',
'END:DAYLIGHT',
'END:VTIMEZONE'
]
*/

const asString = getZoneString('America/Los_Angeles');
console.log(asString);
/*
BEGIN:VTIMEZONE
TZID:America/Los_Angeles
BEGIN:STANDARD
TZNAME:PST
TZOFFSETFROM:-0700
TZOFFSETTO:-0800
DTSTART:19701101T020000
RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:PDT
TZOFFSETFROM:-0800
TZOFFSETTO:-0700
DTSTART:19700308T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU
END:DAYLIGHT
END:VTIMEZONE
*/
```

> Tip: If you don’t need the opening `BEGIN:VTIMEZONE` and closing `END:VTIMEZONE` lines, set the second optional argument of either function to `false`.

[npm-url]: https://npmjs.org/package/icalzone
[npm-version-image]: https://img.shields.io/npm/v/icalzone.svg?style=flat

[travis-url]: https://travis-ci.org/Manc/icalzone
[travis-image]: https://img.shields.io/travis/Manc/icalzone/master.svg?style=flat

[min-size-image]: https://img.shields.io/bundlephobia/min/icalzone?style=flat

[license-url]: LICENSE
[license-image]: https://img.shields.io/badge/license-ISC-blue.svg?style=flat
4 changes: 4 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
45 changes: 45 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "icalzone",
"version": "0.0.1",
"description": "iCalzone is a light-weight VTIMEZONE provider",
"author": "Nick Singleton",
"license": "ISC",
"private": false,
"scripts": {
"build-zones": "rm ./src/zones.ts ; ts-node --dir ./scripts buildzones",
"build-library": "rm -rf ./dist ; tsc --project tsconfig.build.json",
"build": "yarn run build-zones && yarn run build-library",
"lint": "eslint 'src/**/*.ts'",
"test": "jest"
},
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
"dist/**/*"
],
"repository": {
"url": "https://github.com/Manc/icalzone.git",
"type": "git"
},
"bugs": {
"url": "https://github.com/Manc/icalzone/issues"
},
"homepage": "https://github.com/Manc/icalzone",
"keywords": [
"ical",
"icalendar",
"ics",
"vtimezone",
"timezone",
"rfc5545"
],
"devDependencies": {
"@touch4it/ical-timezones": "^1.6.1",
"@types/jest": "^26.0.23",
"@types/node": "^15.3.0",
"jest": "^26.6.3",
"ts-jest": "^26.5.6",
"ts-node": "^9.1.1",
"typescript": "^4.2.4"
}
}
168 changes: 168 additions & 0 deletions scripts/buildzones.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/// <reference path="../src/global.d.ts" />

import fs from 'fs';
import path from 'path';
import zoneMap from '@touch4it/ical-timezones/zones';


const defaultStart = '19700101T000000';

function loadZoneIcs(filename: string) {
return fs.readFileSync(
path.join(__dirname, '../node_modules/@touch4it/ical-timezones/zones', filename),
'utf8'
);
}

function parseRRuleStr(str: string): ZoneRRule {
// const match = str.match(/FREQ=([A-Z]+);BYMONTH=([0-9]+);BYDAY=(-?[0-9A-Z]+)/);
const match = str.match(/FREQ=YEARLY;BYMONTH=([0-9]+);BYDAY=(-?[0-9A-Z]+)/);
if (!match) {
throw new Error('Unexpected RRULE string. Manually check and adapt code accordingly.');
}
const [, monthStr, dayStr] = match;
return {
// f: 'YEARLY', // "YEARLY" is the implicitly assumed default value
m: parseInt(monthStr, 10),
d: dayStr,
};
}

function extractVTZData(icsContent: string): ZoneData {
const lines = icsContent.substring(
icsContent.indexOf('BEGIN:VTIMEZONE') + 16,
icsContent.indexOf('END:VTIMEZONE') - 1
)
.split('\n')
.filter(l =>
!!l.match(/^(BEGIN:|END:|TZOFFSET|TZNAME:|DTSTART:|RRULE:)/)
)
.map(l => l.trimEnd());


let standard: Partial<ZoneSubData> = {};
let daylight: Partial<ZoneSubData> = {};
let currentObject: Partial<ZoneSubData> | null = null;
lines.forEach(line => {
const [key, value] = line.split(':');
if (key === 'BEGIN') {
if (value === 'STANDARD' || value === 'DAYLIGHT') {
// section = value;
if (value === 'STANDARD') {
currentObject = standard;
} else {
currentObject = daylight;
}
}
return;
}
if (key === 'END') {
currentObject = null;
return;
}
if (currentObject) {
switch (key) {
case 'TZNAME': {
currentObject.n = value;
return;
}
case 'TZOFFSETFROM': {
currentObject.f = value;
return;
}
case 'TZOFFSETTO': {
currentObject.t = value;
return;
}
case 'RRULE': {
currentObject.r = parseRRuleStr(value);
return;
}
case 'DTSTART': {
currentObject.s = value;
return;
}
}
}
});

// Delete redundant `t` properties (TZOFFSETTO).
if (standard.t && standard.t === standard.f) {
delete standard.t;
}
if (daylight.t && daylight.t === daylight.f) {
delete daylight.t;
}

const data: ZoneData = { s: standard as ZoneSubData };
if (Object.keys(daylight).length) {
data.d = daylight as ZoneSubData;
}

return data;
}

const zoneDataMap = new Map<string, ZoneData>();
const statsStart = new Map<string, number>();

const filteredKeys = Object.entries(zoneMap).filter(([key, value]) =>
!!key.match(/^[A-Za-z]+\/.+/)
&& !value.match(/\s/)
&& value?.endsWith('.ics')
).map(([, value]) => value);

filteredKeys
.forEach(zoneFileName => {
const tzData = extractVTZData(loadZoneIcs(zoneFileName));

// Collect data for analysis and remove start date if unnecessary.
const startStandard = tzData.s.s;
if (!startStandard) {
throw new Error('Time zone data has no DTSTART value');
}
const count = statsStart.get(startStandard) || 0;
statsStart.set(startStandard, count + 1);

if (startStandard === defaultStart) {
// Delete attribute from object to safe bytes
delete tzData.s.s;
}

// Do the same for the "daytime" part if it exists.
if (tzData.d) {
const startDaylight = tzData.d.s;
if (!startDaylight) {
throw new Error('Time zone data has no DTSTART value');
}
const count = statsStart.get(startDaylight) || 0;
statsStart.set(startDaylight, count + 1);

if (startDaylight === defaultStart) {
// Delete attribute from object to safe bytes
delete tzData.d.s;
}
}

// Add entry to the map.
zoneDataMap.set(
zoneFileName.replace('.ics', ''),
tzData
);
});

// Analyze the collected DTSTART values and check whether the value
// defined in `defaultStart` really is the most common value.
const statsStartSorted = [...statsStart].sort(([, countA], [, countB]) => countB - countA);
const topStart = statsStartSorted[0][0];
if (topStart !== defaultStart) {
throw new Error('The value of defaultStart does not match the most commonly used DTSTART value.');
}

// Generate and write a TypeScript file.
fs.writeFileSync(
path.join(__dirname, '../src/zones.ts'),
[
`export const defaultStart = "${defaultStart}";`,
`export const zonesMap = new Map<string, ZoneData>(${JSON.stringify([...zoneDataMap], null, '\t')});`
].join('\n')
);
16 changes: 16 additions & 0 deletions scripts/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"strict": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"esModuleInterop": true,
"paths": {
"@touch4it/ical-timezones/zones": ["./types/zones.d.ts"]
}
},
"include": [
"**/*.ts"
]
}
4 changes: 4 additions & 0 deletions scripts/types/zones.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module '@touch4it/ical-timezones/zones' {
const zoneMap: Record<string, string>;
export default zoneMap;
}
28 changes: 28 additions & 0 deletions src/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
type ZoneRRule = {
/** FREQ (default: `YEARLY`) */
f?: string;
/** BYMONTH */
m: number;
/** BYDAY */
d: string;
};

type ZoneSubData = {
/** TZNAME */
n: string;
/** TZOFFSETFROM */
f: string;
/** TZOFFSETTO (default: the value of `f`) */
t?: string;
/** RRULE */
r?: ZoneRRule;
/** DTSTART (default: `19700101T000000`, currently by far the most common value) */
s?: string;
};

type ZoneData = {
/** BEGIN:STANDARD...END:STANDARD */
s: ZoneSubData,
/** BEGIN:DAYLIGHT...END:DAYLIGHT */
d?: ZoneSubData,
};
Loading

0 comments on commit 1228e4b

Please sign in to comment.