@octane-xplat/calendar 0.0.0-nightly.g1b95ef7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @octane-xplat/calendar
2
+
3
+ [Documentation](https://octane-xplat.goddardai.org/package-calendar).
4
+
5
+ [API reference](https://octane-xplat.goddardai.org/api-calendar).
package/package.json ADDED
@@ -0,0 +1,87 @@
1
+ {
2
+ "name": "@octane-xplat/calendar",
3
+ "version": "0.0.0-nightly.g1b95ef7",
4
+ "description": "Device calendar for Octane xplat — event store reads and writes via EventKit/CalendarContract",
5
+ "keywords": [
6
+ "android",
7
+ "cross-platform",
8
+ "nativescript",
9
+ "octane",
10
+ "xplat",
11
+ "calendar",
12
+ "events"
13
+ ],
14
+ "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/calendar",
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/octane-xplat/octane-xplat",
19
+ "directory": "packages/calendar"
20
+ },
21
+ "files": [
22
+ "src",
23
+ "platforms",
24
+ "types",
25
+ "!src/**/*.test.*",
26
+ "!src/**/*.spec.*"
27
+ ],
28
+ "type": "module",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./types/generated/index.d.ts",
32
+ "macos": "./src/index.macos.ts",
33
+ "web": "./src/index.web.ts",
34
+ "native": "./src/index.ts",
35
+ "default": "./src/index.ts"
36
+ },
37
+ "./*": {
38
+ "types": "./types/generated/*.d.ts",
39
+ "default": "./src/*"
40
+ },
41
+ "./*.ts": {
42
+ "types": "./types/generated/*.d.ts",
43
+ "default": "./src/*.ts"
44
+ }
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "scripts": {
50
+ "typegen": "tsrx-typegen --target octane",
51
+ "prepack": "bun run typegen && tsrx-typegen --pack-check",
52
+ "pack:check": "tsrx-typegen --pack-check",
53
+ "typecheck": "node ../../scripts/typecheck.ts",
54
+ "test": "node --test tests/*.test.ts"
55
+ },
56
+ "devDependencies": {
57
+ "@octane-xplat/nativescript-octane": "0.0.0-nightly.g1b95ef7",
58
+ "@nativescript/core": "9.1.3",
59
+ "@nativescript/types": "9.1.4",
60
+ "octane": "0.23.2",
61
+ "tsrx-typegen": "0.6.2",
62
+ "typescript": "7.1.0-dev.20261121.1",
63
+ "@tsrx/content-mapper": "0.1.2"
64
+ },
65
+ "peerDependencies": {
66
+ "@octane-xplat/nativescript-octane": "0.0.0-nightly.g1b95ef7",
67
+ "@nativescript/core": ">=9.1.0 <10",
68
+ "octane": ">=0.6.3 <1"
69
+ },
70
+ "peerDependenciesMeta": {
71
+ "@octane-xplat/nativescript-octane": {
72
+ "optional": true
73
+ },
74
+ "@nativescript/core": {
75
+ "optional": true
76
+ }
77
+ },
78
+ "nativescript": {
79
+ "platforms": {
80
+ "android": "9.1.0",
81
+ "ios": "9.1.0"
82
+ }
83
+ },
84
+ "dependencies": {
85
+ "@octane-xplat/platform": "0.0.0-nightly.g1b95ef7"
86
+ }
87
+ }
@@ -0,0 +1,4 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.READ_CALENDAR" />
3
+ <uses-permission android:name="android.permission.WRITE_CALENDAR" />
4
+ </manifest>
@@ -0,0 +1,10 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>NSCalendarsUsageDescription</key>
6
+ <string>Calendar access is required to read and write events.</string>
7
+ <key>NSCalendarsWriteOnlyAccessUsageDescription</key>
8
+ <string>Calendar access is required to create events.</string>
9
+ </dict>
10
+ </plist>
@@ -0,0 +1,274 @@
1
+ // Calendar — Android leaf, custom bridge (nativescript-calendar is stale).
2
+ // CalendarContract through the content provider.
3
+ import { Application, Utils } from '@nativescript/core'
4
+ import type { PermissionStatus } from '@octane-xplat/platform'
5
+ import { android, java } from '@octane-xplat/platform/android'
6
+ import type { Calendar, CalendarEvent, CalendarInfo, NewEvent, PermissionResult } from './types'
7
+
8
+ let calRequestCode = 7731
9
+
10
+ function androidEnsure(): Promise<PermissionResult> {
11
+ const perm = 'android.permission.READ_CALENDAR'
12
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
13
+
14
+ try {
15
+ if (
16
+ activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
17
+ ) {
18
+ return Promise.resolve('granted')
19
+ }
20
+
21
+ if (!activity) {
22
+ return Promise.resolve('denied')
23
+ }
24
+
25
+ return new Promise<PermissionResult>((resolve) => {
26
+ const requestCode = calRequestCode++
27
+ const event = Application.android.activityRequestPermissionsEvent
28
+ const onResult = (args: any) => {
29
+ if (args.requestCode !== requestCode) {
30
+ return
31
+ }
32
+
33
+ Application.android.off(event, onResult)
34
+ resolve(
35
+ args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
36
+ ? 'granted'
37
+ : 'denied',
38
+ )
39
+ }
40
+
41
+ Application.android.on(event, onResult)
42
+ try {
43
+ activity.requestPermissions([perm, 'android.permission.WRITE_CALENDAR'], requestCode)
44
+ } catch {
45
+ Application.android.off(event, onResult)
46
+ resolve('denied')
47
+ }
48
+ })
49
+ } catch {
50
+ return Promise.resolve('denied')
51
+ }
52
+ }
53
+
54
+ const androidUtils = Utils.android as any
55
+ const resolver = () => androidUtils?.getApplicationContext?.()?.getContentResolver()
56
+
57
+ function androidQuery(
58
+ uri: any,
59
+ projection: string[],
60
+ selection: string,
61
+ args: string[],
62
+ sort: string,
63
+ ): any[] {
64
+ const cursor = resolver()?.query(uri, projection, selection, args, sort)
65
+ const out: any[] = []
66
+
67
+ if (!cursor) {
68
+ return out
69
+ }
70
+
71
+ while (cursor.moveToNext()) {
72
+ const row: Record<string, any> = {}
73
+
74
+ for (let i = 0; i < cursor.getColumnCount(); i++) {
75
+ row[cursor.getColumnName(i)] = cursor.getString(i)
76
+ }
77
+
78
+ out.push(row)
79
+ }
80
+
81
+ cursor.close()
82
+ return out
83
+ }
84
+
85
+ const CAL_URI = () => android.provider.CalendarContract.Calendars.CONTENT_URI
86
+ const EVENTS_URI = () => android.provider.CalendarContract.Events.CONTENT_URI
87
+ const INSTANCES_URI = () => android.provider.CalendarContract.Instances.CONTENT_URI
88
+
89
+ function androidCalendars(): CalendarInfo[] {
90
+ return androidQuery(
91
+ CAL_URI(),
92
+ [
93
+ '_id',
94
+ 'calendar_displayName',
95
+ 'calendar_color',
96
+ 'account_name',
97
+ 'calendar_access_level',
98
+ 'isPrimary',
99
+ ],
100
+ '',
101
+ [],
102
+ 'calendar_displayName ASC',
103
+ ).map((row) => ({
104
+ id: String(row._id),
105
+ title: String(row.calendar_displayName ?? ''),
106
+ color: row.calendar_color,
107
+ source: row.account_name,
108
+ allowsModifications: Number(row.calendar_access_level) >= 500,
109
+ isPrimary: row.isPrimary === '1' || row.isPrimary === 'true',
110
+ }))
111
+ }
112
+
113
+ function androidEvent(row: any): CalendarEvent {
114
+ return {
115
+ id: String(row._id ?? row.event_id ?? ''),
116
+ calendarId: row.calendar_id ? String(row.calendar_id) : undefined,
117
+ title: String(row.title ?? ''),
118
+ startDate: new Date(Number(row.dtstart ?? row.begin ?? 0)),
119
+ endDate: new Date(Number(row.dtend ?? row.end ?? 0)),
120
+ allDay: row.allDay === '1' || row.allDay === 1,
121
+ location: row.eventLocation,
122
+ notes: row.description,
123
+ }
124
+ }
125
+
126
+ /** Calendar service — CalendarContract. */
127
+ export const calendar: Calendar = {
128
+ supported: true,
129
+
130
+ ensure(): Promise<PermissionResult> {
131
+ return androidEnsure()
132
+ },
133
+
134
+ async getCalendars(): Promise<CalendarInfo[]> {
135
+ return androidCalendars()
136
+ },
137
+
138
+ async getDefaultCalendar(): Promise<CalendarInfo | null> {
139
+ return androidCalendars().find((c) => c.isPrimary) ?? androidCalendars()[0] ?? null
140
+ },
141
+
142
+ async getEvents(
143
+ startDate: Date,
144
+ endDate: Date,
145
+ calendarIds?: string[],
146
+ ): Promise<CalendarEvent[]> {
147
+ const selection = calendarIds?.length
148
+ ? `calendar_id IN (${calendarIds.map(() => '?').join(',')})`
149
+ : ''
150
+
151
+ const args = calendarIds ?? []
152
+
153
+ return androidQuery(
154
+ INSTANCES_URI(),
155
+ [
156
+ 'event_id',
157
+ 'calendar_id',
158
+ 'title',
159
+ 'begin',
160
+ 'end',
161
+ 'allDay',
162
+ 'eventLocation',
163
+ 'description',
164
+ ],
165
+ selection,
166
+ args,
167
+ 'begin ASC',
168
+ )
169
+ .map((row) => androidEvent(row))
170
+ .filter((e) => e.startDate <= endDate && e.endDate >= startDate)
171
+ },
172
+
173
+ async getEvent(id: string): Promise<CalendarEvent | null> {
174
+ const rows = androidQuery(
175
+ (android.net.Uri as any).withAppendedId(EVENTS_URI(), Number(id)),
176
+ ['_id', 'calendar_id', 'title', 'dtstart', 'dtend', 'allDay', 'eventLocation', 'description'],
177
+ '',
178
+ [],
179
+ '',
180
+ )
181
+
182
+ return rows.length ? androidEvent(rows[0]) : null
183
+ },
184
+
185
+ async createEvent(calendarId: string | undefined, event: NewEvent): Promise<string> {
186
+ const values = new android.content.ContentValues()
187
+ const def = await calendar.getDefaultCalendar()
188
+
189
+ values.put('calendar_id', java.lang.Long.valueOf(calendarId ?? def?.id ?? '0'))
190
+ values.put('title', event.title)
191
+ values.put('dtstart', java.lang.Long.valueOf(event.startDate.getTime()))
192
+ values.put('dtend', java.lang.Long.valueOf(event.endDate.getTime()))
193
+ values.put('allDay', java.lang.Integer.valueOf(event.allDay ? 1 : 0))
194
+ if (event.location) {
195
+ values.put('eventLocation', event.location)
196
+ }
197
+
198
+ if (event.notes) {
199
+ values.put('description', event.notes)
200
+ }
201
+
202
+ values.put('eventTimezone', event.timeZone ?? 'UTC')
203
+
204
+ const uri = resolver()?.insert(EVENTS_URI(), values)
205
+
206
+ return uri ? String(uri.getLastPathSegment()) : ''
207
+ },
208
+
209
+ async updateEvent(id: string, patch: Partial<NewEvent>): Promise<string> {
210
+ const values = new android.content.ContentValues()
211
+
212
+ if (patch.title !== undefined) {
213
+ values.put('title', patch.title)
214
+ }
215
+
216
+ if (patch.startDate) {
217
+ values.put('dtstart', java.lang.Long.valueOf(patch.startDate.getTime()))
218
+ }
219
+
220
+ if (patch.endDate) {
221
+ values.put('dtend', java.lang.Long.valueOf(patch.endDate.getTime()))
222
+ }
223
+
224
+ if (patch.location) {
225
+ values.put('eventLocation', patch.location)
226
+ }
227
+
228
+ if (patch.notes !== undefined) {
229
+ values.put('description', patch.notes)
230
+ }
231
+
232
+ resolver()?.update(
233
+ (android.net.Uri as any).withAppendedId(EVENTS_URI(), Number(id)),
234
+ values,
235
+ null,
236
+ null,
237
+ )
238
+
239
+ return id
240
+ },
241
+
242
+ async deleteEvent(id: string): Promise<void> {
243
+ resolver()?.delete(
244
+ (android.net.Uri as any).withAppendedId(EVENTS_URI(), Number(id)),
245
+ null,
246
+ null,
247
+ )
248
+ },
249
+ }
250
+
251
+ // Non-prompting authorization read for the dispatcher's getPermissions.
252
+ // Android can't distinguish never-asked from denied without the rationale
253
+ // hook — report undetermined and let request resolve it.
254
+ function androidStatus(): PermissionStatus {
255
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
256
+
257
+ return activity?.checkSelfPermission?.('android.permission.READ_CALENDAR') ===
258
+ android.content.pm.PackageManager.PERMISSION_GRANTED
259
+ ? 'granted'
260
+ : 'undetermined'
261
+ }
262
+
263
+ const toResponse = (status: PermissionStatus) => ({
264
+ status,
265
+ granted: status === 'granted',
266
+ canAskAgain: status === 'granted' || status === 'undetermined',
267
+ })
268
+
269
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
270
+
271
+ permissionOwners.calendar = {
272
+ getPermissions: async () => toResponse(androidStatus()),
273
+ requestPermissions: async () => toResponse(await calendar.ensure()),
274
+ }
@@ -0,0 +1,233 @@
1
+ // Calendar — iOS leaf, custom bridge (nativescript-calendar is stale).
2
+ // EventKit EKEventStore via declare-const bridging (auth-session pattern).
3
+ import type { PermissionStatus } from '@octane-xplat/platform'
4
+ import type { Calendar, CalendarEvent, CalendarInfo, NewEvent, PermissionResult } from './types'
5
+
6
+ declare const EKEventStore: any
7
+ declare const EKEntityTypeEvent: number | undefined
8
+ declare const EKEvent: any
9
+ declare const NSDate: any
10
+
11
+ let store: any = null
12
+ const eventStore = () => {
13
+ if (!store && typeof EKEventStore !== 'undefined') {
14
+ store = EKEventStore.new()
15
+ }
16
+
17
+ return store
18
+ }
19
+
20
+ function iosEnsure(): Promise<PermissionResult> {
21
+ const s = eventStore()
22
+
23
+ if (!s || typeof EKEntityTypeEvent === 'undefined') {
24
+ return Promise.resolve('unsupported')
25
+ }
26
+
27
+ const status = EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent)
28
+
29
+ // 0 notDetermined 1 restricted 2 denied 3 fullAccess/authorized 4 writeOnly
30
+ if (status === 3 || status === 4) {
31
+ return Promise.resolve('granted')
32
+ }
33
+
34
+ if (status === 1 || status === 2) {
35
+ return Promise.resolve('denied')
36
+ }
37
+
38
+ return new Promise((resolve) => {
39
+ if (typeof s.requestFullAccessToEventsWithCompletion === 'function') {
40
+ s.requestFullAccessToEventsWithCompletion((granted: boolean) =>
41
+ resolve(granted ? 'granted' : 'denied'),
42
+ )
43
+ } else {
44
+ s.requestAccessToEntityTypeCompletion(EKEntityTypeEvent, (granted: boolean) =>
45
+ resolve(granted ? 'granted' : 'denied'),
46
+ )
47
+ }
48
+ })
49
+ }
50
+
51
+ function iosCalendars(): CalendarInfo[] {
52
+ const s = eventStore()
53
+ const out: CalendarInfo[] = []
54
+ const list = s?.calendarsForEntityType?.(EKEntityTypeEvent ?? 0)
55
+
56
+ for (let i = 0; i < (list?.count ?? 0); i++) {
57
+ const c = list.objectAtIndex(i)
58
+
59
+ out.push({
60
+ id: String(c.calendarIdentifier ?? ''),
61
+ title: String(c.title ?? ''),
62
+ color: c.CGColor ? String(c.CGColor) : undefined,
63
+ source: c.source?.title ? String(c.source.title) : undefined,
64
+ allowsModifications: !!c.allowsContentModifications,
65
+ isPrimary: false,
66
+ })
67
+ }
68
+
69
+ return out
70
+ }
71
+
72
+ function iosEvent(e: any): CalendarEvent {
73
+ return {
74
+ id: String(e.eventIdentifier ?? ''),
75
+ calendarId: e.calendar?.calendarIdentifier ? String(e.calendar.calendarIdentifier) : undefined,
76
+ title: String(e.title ?? ''),
77
+ startDate: new Date((e.startDate?.timeIntervalSince1970 ?? 0) * 1000),
78
+ endDate: new Date((e.endDate?.timeIntervalSince1970 ?? 0) * 1000),
79
+ allDay: !!e.allDay,
80
+ location: e.location ? String(e.location) : undefined,
81
+ notes: e.notes ? String(e.notes) : undefined,
82
+ timeZone: e.timeZone?.name ? String(e.timeZone.name) : undefined,
83
+ }
84
+ }
85
+
86
+ /** Calendar service — EventKit. */
87
+ export const calendar: Calendar = {
88
+ supported: typeof EKEventStore !== 'undefined',
89
+
90
+ ensure(): Promise<PermissionResult> {
91
+ return iosEnsure()
92
+ },
93
+
94
+ async getCalendars(): Promise<CalendarInfo[]> {
95
+ return iosCalendars()
96
+ },
97
+
98
+ async getDefaultCalendar(): Promise<CalendarInfo | null> {
99
+ const s = eventStore()
100
+ const def = s?.defaultCalendarForNewEvents
101
+
102
+ return def
103
+ ? {
104
+ id: String(def.calendarIdentifier),
105
+ title: String(def.title ?? ''),
106
+ allowsModifications: !!def.allowsContentModifications,
107
+ }
108
+ : null
109
+ },
110
+
111
+ async getEvents(
112
+ startDate: Date,
113
+ endDate: Date,
114
+ calendarIds?: string[],
115
+ ): Promise<CalendarEvent[]> {
116
+ const s = eventStore()
117
+ const begin = NSDate.dateWithTimeIntervalSince1970(startDate.getTime() / 1000)
118
+ const end = NSDate.dateWithTimeIntervalSince1970(endDate.getTime() / 1000)
119
+ const predicate = s.predicateForEventsWithStartDateEndDateCalendars(begin, end, null)
120
+ const list = s.eventsMatchingPredicate(predicate)
121
+ const out: CalendarEvent[] = []
122
+
123
+ for (let i = 0; i < (list?.count ?? 0); i++) {
124
+ const e = iosEvent(list.objectAtIndex(i))
125
+
126
+ if (!calendarIds?.length || calendarIds.includes(e.calendarId ?? '')) {
127
+ out.push(e)
128
+ }
129
+ }
130
+
131
+ return out
132
+ },
133
+
134
+ async getEvent(id: string): Promise<CalendarEvent | null> {
135
+ const e = eventStore()?.eventWithIdentifier?.(id)
136
+
137
+ return e ? iosEvent(e) : null
138
+ },
139
+
140
+ async createEvent(calendarId: string | undefined, event: NewEvent): Promise<string> {
141
+ const s = eventStore()
142
+ const e = EKEvent.eventWithEventStore(s)
143
+
144
+ e.title = event.title
145
+ e.startDate = NSDate.dateWithTimeIntervalSince1970(event.startDate.getTime() / 1000)
146
+ e.endDate = NSDate.dateWithTimeIntervalSince1970(event.endDate.getTime() / 1000)
147
+ e.allDay = !!event.allDay
148
+ e.location = event.location
149
+ e.notes = event.notes
150
+ e.calendar = calendarId
151
+ ? (s.calendarWithIdentifier?.(calendarId) ?? s.defaultCalendarForNewEvents)
152
+ : s.defaultCalendarForNewEvents
153
+
154
+ if (!s.saveEventSpanError(e, 0, null)) {
155
+ throw new Error('calendar.createEvent: EKEventStore.saveEvent failed')
156
+ }
157
+
158
+ return String(e.eventIdentifier ?? '')
159
+ },
160
+
161
+ async updateEvent(id: string, patch: Partial<NewEvent>): Promise<string> {
162
+ const s = eventStore()
163
+ const e = s.eventWithIdentifier?.(id)
164
+
165
+ if (!e) {
166
+ throw new Error(`calendar.updateEvent: no event ${id}`)
167
+ }
168
+
169
+ if (patch.title !== undefined) {
170
+ e.title = patch.title
171
+ }
172
+
173
+ if (patch.startDate) {
174
+ e.startDate = NSDate.dateWithTimeIntervalSince1970(patch.startDate.getTime() / 1000)
175
+ }
176
+
177
+ if (patch.endDate) {
178
+ e.endDate = NSDate.dateWithTimeIntervalSince1970(patch.endDate.getTime() / 1000)
179
+ }
180
+
181
+ if (patch.allDay !== undefined) {
182
+ e.allDay = patch.allDay
183
+ }
184
+
185
+ if (patch.location !== undefined) {
186
+ e.location = patch.location
187
+ }
188
+
189
+ if (patch.notes !== undefined) {
190
+ e.notes = patch.notes
191
+ }
192
+
193
+ s.saveEventSpanError(e, 0, null)
194
+ return id
195
+ },
196
+
197
+ async deleteEvent(id: string): Promise<void> {
198
+ const s = eventStore()
199
+ const e = s.eventWithIdentifier?.(id)
200
+
201
+ if (e) {
202
+ s.removeEventSpanError(e, 0, null)
203
+ }
204
+ },
205
+ }
206
+
207
+ // Non-prompting authorization read for the dispatcher's getPermissions.
208
+ function iosStatus(): PermissionStatus {
209
+ const s = eventStore()
210
+
211
+ if (!s || typeof EKEntityTypeEvent === 'undefined') {
212
+ return 'unsupported'
213
+ }
214
+
215
+ // EKAuthorizationStatus: 0 notDetermined, 1 restricted, 2 denied,
216
+ // 3 fullAccess/authorized, 4 writeOnly
217
+ const status = EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent)
218
+
219
+ return status === 3 || status === 4 ? 'granted' : status === 0 ? 'undetermined' : 'denied'
220
+ }
221
+
222
+ const toResponse = (status: PermissionStatus) => ({
223
+ status,
224
+ granted: status === 'granted',
225
+ canAskAgain: status === 'granted' || status === 'undetermined',
226
+ })
227
+
228
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
229
+
230
+ permissionOwners.calendar = {
231
+ getPermissions: async () => toResponse(iosStatus()),
232
+ requestPermissions: async () => toResponse(await calendar.ensure()),
233
+ }
@@ -0,0 +1 @@
1
+ export { calendar } from './calendar.web'
@@ -0,0 +1,259 @@
1
+ // Calendar — AppKit leaf over EventKit. EKEventStore is bridgeable through
2
+ // the JSC host; the API mirrors the iOS leaf's surface (same store class,
3
+ // same entity type). Metadata targets macOS 11, so the deprecated
4
+ // requestAccessToEntityTypeCompletion is the bound request entry point —
5
+ // on macOS 14+ it still performs the full-access events prompt.
6
+ import { EKEntityType, EKEvent, EKEventStore, EKSpan, NSDate } from '@octane-xplat/platform/macos'
7
+ import type { Calendar, CalendarEvent, CalendarInfo, NewEvent, PermissionResult } from './types'
8
+
9
+ let store: any = null
10
+ const eventStore = () => {
11
+ if (store) {
12
+ return store
13
+ }
14
+
15
+ try {
16
+ if (typeof EKEventStore?.authorizationStatusForEntityType !== 'function') {
17
+ return null
18
+ }
19
+
20
+ return (store = EKEventStore.new())
21
+ } catch {
22
+ return null
23
+ }
24
+ }
25
+
26
+ // EKAuthorizationStatus: 0 notDetermined 1 restricted 2 denied
27
+ // 3 fullAccess/authorized 4 writeOnly
28
+ const rawStatus = () =>
29
+ Number(EKEventStore.authorizationStatusForEntityType(EKEntityType.Event ?? 0))
30
+
31
+ function ensureAccess(): Promise<PermissionResult> {
32
+ const s = eventStore()
33
+
34
+ if (!s) {
35
+ return Promise.resolve('unsupported')
36
+ }
37
+
38
+ const status = rawStatus()
39
+
40
+ if (status === 3 || status === 4) {
41
+ return Promise.resolve('granted')
42
+ }
43
+
44
+ if (status === 1 || status === 2) {
45
+ return Promise.resolve('denied')
46
+ }
47
+
48
+ return new Promise((resolve) => {
49
+ s.requestAccessToEntityTypeCompletion(EKEntityType.Event ?? 0, (granted: boolean) =>
50
+ resolve(granted ? 'granted' : 'denied'),
51
+ )
52
+ })
53
+ }
54
+
55
+ const permissionResponse = () => {
56
+ const s = eventStore()
57
+
58
+ if (!s) {
59
+ return { status: 'unsupported' as const, granted: false, canAskAgain: false }
60
+ }
61
+
62
+ const status = rawStatus()
63
+
64
+ return {
65
+ status:
66
+ status === 3 || status === 4
67
+ ? ('granted' as const)
68
+ : status === 0
69
+ ? ('undetermined' as const)
70
+ : ('denied' as const),
71
+ granted: status === 3 || status === 4,
72
+ canAskAgain: status === 0 || status === 3 || status === 4,
73
+ }
74
+ }
75
+
76
+ function calendars(): CalendarInfo[] {
77
+ const s = eventStore()
78
+ const out: CalendarInfo[] = []
79
+ const list = s?.calendarsForEntityType?.(EKEntityType.Event ?? 0)
80
+
81
+ for (let i = 0; i < (list?.count ?? 0); i++) {
82
+ const c = list.objectAtIndex(i)
83
+
84
+ out.push({
85
+ id: String(c.calendarIdentifier ?? ''),
86
+ title: String(c.title ?? ''),
87
+ color: c.CGColor ? String(c.CGColor) : undefined,
88
+ source: c.source?.title ? String(c.source.title) : undefined,
89
+ allowsModifications: !!c.allowsContentModifications,
90
+ isPrimary: false,
91
+ })
92
+ }
93
+
94
+ return out
95
+ }
96
+
97
+ function asEvent(e: any): CalendarEvent {
98
+ return {
99
+ id: String(e.eventIdentifier ?? ''),
100
+ calendarId: e.calendar?.calendarIdentifier ? String(e.calendar.calendarIdentifier) : undefined,
101
+ title: String(e.title ?? ''),
102
+ startDate: new Date((e.startDate?.timeIntervalSince1970 ?? 0) * 1000),
103
+ endDate: new Date((e.endDate?.timeIntervalSince1970 ?? 0) * 1000),
104
+ allDay: !!e.allDay,
105
+ location: e.location ? String(e.location) : undefined,
106
+ notes: e.notes ? String(e.notes) : undefined,
107
+ timeZone: e.timeZone?.name ? String(e.timeZone.name) : undefined,
108
+ }
109
+ }
110
+
111
+ const toNSDate = (date: Date) => NSDate.dateWithTimeIntervalSince1970(date.getTime() / 1000)
112
+
113
+ /** Calendar service — EventKit/CalendarContract. */
114
+ export const calendar: Calendar = {
115
+ get supported() {
116
+ return eventStore() !== null
117
+ },
118
+
119
+ ensure(): Promise<PermissionResult> {
120
+ return ensureAccess()
121
+ },
122
+
123
+ async getCalendars(): Promise<CalendarInfo[]> {
124
+ return calendars()
125
+ },
126
+
127
+ async getDefaultCalendar(): Promise<CalendarInfo | null> {
128
+ const def = eventStore()?.defaultCalendarForNewEvents
129
+
130
+ return def
131
+ ? {
132
+ id: String(def.calendarIdentifier),
133
+ title: String(def.title ?? ''),
134
+ allowsModifications: !!def.allowsContentModifications,
135
+ }
136
+ : null
137
+ },
138
+
139
+ async getEvents(
140
+ startDate: Date,
141
+ endDate: Date,
142
+ calendarIds?: string[],
143
+ ): Promise<CalendarEvent[]> {
144
+ const s = eventStore()
145
+ const wanted = calendarIds?.length
146
+ ? calendarIds.map((id) => s?.calendarWithIdentifier?.(id)).filter((c: any) => c != null)
147
+ : null
148
+
149
+ const predicate = s?.predicateForEventsWithStartDateEndDateCalendars(
150
+ toNSDate(startDate),
151
+ toNSDate(endDate),
152
+ wanted?.length ? wanted : null,
153
+ )
154
+
155
+ const list = s?.eventsMatchingPredicate?.(predicate)
156
+ const out: CalendarEvent[] = []
157
+
158
+ for (let i = 0; i < (list?.count ?? 0); i++) {
159
+ const e = asEvent(list.objectAtIndex(i))
160
+
161
+ if (!calendarIds?.length || calendarIds.includes(e.calendarId ?? '')) {
162
+ out.push(e)
163
+ }
164
+ }
165
+
166
+ return out
167
+ },
168
+
169
+ async getEvent(id: string): Promise<CalendarEvent | null> {
170
+ const e = eventStore()?.eventWithIdentifier?.(id)
171
+
172
+ return e ? asEvent(e) : null
173
+ },
174
+
175
+ async createEvent(calendarId: string | undefined, event: NewEvent): Promise<string> {
176
+ const s = eventStore()
177
+
178
+ if (!s) {
179
+ throw new Error('calendar.createEvent: EventKit is unavailable on this host')
180
+ }
181
+
182
+ const e = EKEvent.eventWithEventStore(s)
183
+
184
+ e.title = event.title
185
+ e.startDate = toNSDate(event.startDate)
186
+ e.endDate = toNSDate(event.endDate)
187
+ e.allDay = !!event.allDay
188
+ e.location = (event.location ?? null) as string
189
+ e.notes = (event.notes ?? null) as string
190
+ e.calendar = calendarId
191
+ ? (s.calendarWithIdentifier?.(calendarId) ?? s.defaultCalendarForNewEvents)
192
+ : s.defaultCalendarForNewEvents
193
+
194
+ if (!s.saveEventSpanError(e, EKSpan.ThisEvent ?? 0, null)) {
195
+ throw new Error('calendar.createEvent: EKEventStore.saveEvent failed')
196
+ }
197
+
198
+ return String(e.eventIdentifier ?? '')
199
+ },
200
+
201
+ async updateEvent(id: string, patch: Partial<NewEvent>): Promise<string> {
202
+ const s = eventStore()
203
+ const e = s?.eventWithIdentifier?.(id)
204
+
205
+ if (!e) {
206
+ throw new Error(`calendar.updateEvent: no event ${id}`)
207
+ }
208
+
209
+ if (patch.title !== undefined) {
210
+ e.title = patch.title
211
+ }
212
+
213
+ if (patch.startDate) {
214
+ e.startDate = toNSDate(patch.startDate)
215
+ }
216
+
217
+ if (patch.endDate) {
218
+ e.endDate = toNSDate(patch.endDate)
219
+ }
220
+
221
+ if (patch.allDay !== undefined) {
222
+ e.allDay = patch.allDay
223
+ }
224
+
225
+ if (patch.location !== undefined) {
226
+ e.location = patch.location
227
+ }
228
+
229
+ if (patch.notes !== undefined) {
230
+ e.notes = patch.notes
231
+ }
232
+
233
+ if (!s.saveEventSpanError(e, EKSpan.ThisEvent ?? 0, null)) {
234
+ throw new Error('calendar.updateEvent: EKEventStore.saveEvent failed')
235
+ }
236
+
237
+ return id
238
+ },
239
+
240
+ async deleteEvent(id: string): Promise<void> {
241
+ const s = eventStore()
242
+ const e = s?.eventWithIdentifier?.(id)
243
+
244
+ if (e && !s.removeEventSpanError(e, EKSpan.ThisEvent ?? 0, null)) {
245
+ throw new Error('calendar.deleteEvent: EKEventStore.removeEvent failed')
246
+ }
247
+ },
248
+ }
249
+
250
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
251
+
252
+ permissionOwners.calendar = {
253
+ getPermissions: async () => permissionResponse(),
254
+ requestPermissions: async () => {
255
+ const result = await calendar.ensure()
256
+
257
+ return { status: result, granted: result === 'granted', canAskAgain: result === 'granted' }
258
+ },
259
+ }
@@ -0,0 +1,31 @@
1
+ // Calendar — no web calendar API exists; .ics generation is userland/library
2
+ // territory. Honest unsupported leaf.
3
+ import type { Calendar, PermissionResult } from './types'
4
+
5
+ const unsupported = () => Promise.reject(new Error('unsupported: no calendar API on web'))
6
+
7
+ /** Calendar service — EventKit/CalendarContract. */
8
+ export const calendar: Calendar = {
9
+ supported: false,
10
+ ensure: async (): Promise<PermissionResult> => 'unsupported',
11
+ getCalendars: unsupported,
12
+ getDefaultCalendar: unsupported,
13
+ getEvents: unsupported,
14
+ getEvent: unsupported,
15
+ createEvent: unsupported,
16
+ updateEvent: unsupported,
17
+ deleteEvent: unsupported,
18
+ }
19
+
20
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
21
+
22
+ const toResponse = (status: PermissionResult) => ({
23
+ status,
24
+ granted: status === 'granted',
25
+ canAskAgain: status === 'granted',
26
+ })
27
+
28
+ permissionOwners.calendar = {
29
+ getPermissions: async () => toResponse(await calendar.ensure()),
30
+ requestPermissions: async () => toResponse(await calendar.ensure()),
31
+ }
@@ -0,0 +1,17 @@
1
+ import type { Calendar, PermissionResult } from './types'
2
+
3
+ const unsupported = () =>
4
+ Promise.reject(new Error('unsupported: calendar is not wired on this platform'))
5
+
6
+ /** Calendar service — EventKit/CalendarContract. */
7
+ export const calendar: Calendar = {
8
+ supported: false,
9
+ ensure: async (): Promise<PermissionResult> => 'unsupported',
10
+ getCalendars: unsupported,
11
+ getDefaultCalendar: unsupported,
12
+ getEvents: unsupported,
13
+ getEvent: unsupported,
14
+ createEvent: unsupported,
15
+ updateEvent: unsupported,
16
+ deleteEvent: unsupported,
17
+ }
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { calendar } from './calendar.macos'
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { calendar } from './calendar'
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { calendar } from './calendar.web'
package/src/types.ts ADDED
@@ -0,0 +1,84 @@
1
+ /** Coarse permission answer; 'unsupported' means the platform has no
2
+ * calendar/permission path. */
3
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported'
4
+
5
+ /** One calendar account-local store. */
6
+ export interface CalendarInfo {
7
+ /** Store-assigned id — pass to getEvents/createEvent. */
8
+ id: string
9
+ /** Display name. */
10
+ title: string
11
+ /** Display color (CSS color where the store exposes one). */
12
+ color?: string
13
+ /** Originating account/source name (iCloud, local, Exchange, …). */
14
+ source?: string
15
+ /** False for read-only stores (subscribed/Birthdays calendars). */
16
+ allowsModifications?: boolean
17
+ /** The store's default calendar. */
18
+ isPrimary?: boolean
19
+ }
20
+
21
+ /** A stored calendar event. */
22
+ export interface CalendarEvent {
23
+ /** Store-assigned id — pass to getEvent/updateEvent/deleteEvent. */
24
+ id: string
25
+ /** The owning CalendarInfo.id; absent where the store doesn't report it. */
26
+ calendarId?: string
27
+ /** Display title. */
28
+ title: string
29
+ /** Start instant. */
30
+ startDate: Date
31
+ /** End instant. */
32
+ endDate: Date
33
+ /** All-day flag; all-day dates are date-only values. */
34
+ allDay?: boolean
35
+ /** Free-text location. */
36
+ location?: string
37
+ /** Free-text notes. */
38
+ notes?: string
39
+ /** IANA time-zone name when the store records one. */
40
+ timeZone?: string
41
+ }
42
+
43
+ /** Event fields for createEvent/updateEvent — no store ids. */
44
+ export interface NewEvent {
45
+ /** Display title. */
46
+ title: string
47
+ /** Start instant. */
48
+ startDate: Date
49
+ /** End instant. */
50
+ endDate: Date
51
+ /** All-day flag. */
52
+ allDay?: boolean
53
+ /** Free-text location. */
54
+ location?: string
55
+ /** Free-text notes. */
56
+ notes?: string
57
+ /** IANA time-zone name. */
58
+ timeZone?: string
59
+ }
60
+
61
+ /** EventCalendar/EventKit calendar façade; false `supported` off mobile. */
62
+ export interface Calendar {
63
+ /** Synchronous fast check — a calendar backend exists. */
64
+ readonly supported: boolean
65
+ /** Ensure calendar permission, prompting if needed. */
66
+ ensure(): Promise<PermissionResult>
67
+ /** Every calendar store visible to the app. */
68
+ getCalendars(): Promise<CalendarInfo[]>
69
+ /** The store's default calendar, or null when none is writable. */
70
+ getDefaultCalendar(): Promise<CalendarInfo | null>
71
+ /** Events overlapping the range, optionally limited to calendar ids. */
72
+ getEvents(startDate: Date, endDate: Date, calendarIds?: string[]): Promise<CalendarEvent[]>
73
+ /** One event by id, or null. */
74
+ getEvent(id: string): Promise<CalendarEvent | null>
75
+ /** Insert an event; resolves the store-assigned event id. Pass
76
+ * undefined calendarId for the default calendar. */
77
+ createEvent(calendarId: string | undefined, event: NewEvent): Promise<string>
78
+ /** Patch fields of an existing event; resolves the event id. */
79
+ updateEvent(id: string, patch: Partial<NewEvent>): Promise<string>
80
+ /** Remove an event by id. */
81
+ deleteEvent(id: string): Promise<void>
82
+ }
83
+
84
+ export declare const calendar: Calendar
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 1,
3
+ "files": [
4
+ "calendar.android.d.ts",
5
+ "calendar.ios.d.ts",
6
+ "calendar.linux.d.ts",
7
+ "calendar.macos.d.ts",
8
+ "calendar.web.d.ts",
9
+ "calendar.windows.d.ts",
10
+ "index.d.ts",
11
+ "types.d.ts"
12
+ ]
13
+ }
@@ -0,0 +1,3 @@
1
+ import type { Calendar } from './types.js';
2
+ /** Calendar service — CalendarContract. */
3
+ export declare const calendar: Calendar;
@@ -0,0 +1,3 @@
1
+ import type { Calendar } from './types.js';
2
+ /** Calendar service — EventKit. */
3
+ export declare const calendar: Calendar;
@@ -0,0 +1 @@
1
+ export { calendar } from './calendar.web.js';
@@ -0,0 +1,3 @@
1
+ import type { Calendar } from './types.js';
2
+ /** Calendar service — EventKit/CalendarContract. */
3
+ export declare const calendar: Calendar;
@@ -0,0 +1,3 @@
1
+ import type { Calendar } from './types.js';
2
+ /** Calendar service — EventKit/CalendarContract. */
3
+ export declare const calendar: Calendar;
@@ -0,0 +1,3 @@
1
+ import type { Calendar } from './types.js';
2
+ /** Calendar service — EventKit/CalendarContract. */
3
+ export declare const calendar: Calendar;
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { calendar } from './calendar';
@@ -0,0 +1,79 @@
1
+ /** Coarse permission answer; 'unsupported' means the platform has no
2
+ * calendar/permission path. */
3
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported';
4
+ /** One calendar account-local store. */
5
+ export interface CalendarInfo {
6
+ /** Store-assigned id — pass to getEvents/createEvent. */
7
+ id: string;
8
+ /** Display name. */
9
+ title: string;
10
+ /** Display color (CSS color where the store exposes one). */
11
+ color?: string;
12
+ /** Originating account/source name (iCloud, local, Exchange, …). */
13
+ source?: string;
14
+ /** False for read-only stores (subscribed/Birthdays calendars). */
15
+ allowsModifications?: boolean;
16
+ /** The store's default calendar. */
17
+ isPrimary?: boolean;
18
+ }
19
+ /** A stored calendar event. */
20
+ export interface CalendarEvent {
21
+ /** Store-assigned id — pass to getEvent/updateEvent/deleteEvent. */
22
+ id: string;
23
+ /** The owning CalendarInfo.id; absent where the store doesn't report it. */
24
+ calendarId?: string;
25
+ /** Display title. */
26
+ title: string;
27
+ /** Start instant. */
28
+ startDate: Date;
29
+ /** End instant. */
30
+ endDate: Date;
31
+ /** All-day flag; all-day dates are date-only values. */
32
+ allDay?: boolean;
33
+ /** Free-text location. */
34
+ location?: string;
35
+ /** Free-text notes. */
36
+ notes?: string;
37
+ /** IANA time-zone name when the store records one. */
38
+ timeZone?: string;
39
+ }
40
+ /** Event fields for createEvent/updateEvent — no store ids. */
41
+ export interface NewEvent {
42
+ /** Display title. */
43
+ title: string;
44
+ /** Start instant. */
45
+ startDate: Date;
46
+ /** End instant. */
47
+ endDate: Date;
48
+ /** All-day flag. */
49
+ allDay?: boolean;
50
+ /** Free-text location. */
51
+ location?: string;
52
+ /** Free-text notes. */
53
+ notes?: string;
54
+ /** IANA time-zone name. */
55
+ timeZone?: string;
56
+ }
57
+ /** EventCalendar/EventKit calendar façade; false `supported` off mobile. */
58
+ export interface Calendar {
59
+ /** Synchronous fast check — a calendar backend exists. */
60
+ readonly supported: boolean;
61
+ /** Ensure calendar permission, prompting if needed. */
62
+ ensure(): Promise<PermissionResult>;
63
+ /** Every calendar store visible to the app. */
64
+ getCalendars(): Promise<CalendarInfo[]>;
65
+ /** The store's default calendar, or null when none is writable. */
66
+ getDefaultCalendar(): Promise<CalendarInfo | null>;
67
+ /** Events overlapping the range, optionally limited to calendar ids. */
68
+ getEvents(startDate: Date, endDate: Date, calendarIds?: string[]): Promise<CalendarEvent[]>;
69
+ /** One event by id, or null. */
70
+ getEvent(id: string): Promise<CalendarEvent | null>;
71
+ /** Insert an event; resolves the store-assigned event id. Pass
72
+ * undefined calendarId for the default calendar. */
73
+ createEvent(calendarId: string | undefined, event: NewEvent): Promise<string>;
74
+ /** Patch fields of an existing event; resolves the event id. */
75
+ updateEvent(id: string, patch: Partial<NewEvent>): Promise<string>;
76
+ /** Remove an event by id. */
77
+ deleteEvent(id: string): Promise<void>;
78
+ }
79
+ export declare const calendar: Calendar;