@octane-xplat/contacts 0.0.1 → 0.19.0

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,38 @@
1
+ # @octane-xplat/contacts
2
+
3
+ Read the device address book on iOS and Android, or let someone select contacts
4
+ in a browser that supports the Contact Picker API. Native apps can also edit
5
+ contacts. Browser access is read-only and limited to the person's selection.
6
+
7
+ ## Read selected contact fields
8
+
9
+ Install in an existing Xplat app:
10
+
11
+ ```sh
12
+ bun add @octane-xplat/contacts
13
+ ```
14
+
15
+ Configure the native contacts permission and usage description before running.
16
+ Call this function from a **Choose contacts** action; browsers require a user
17
+ action to open their picker:
18
+
19
+ ```ts
20
+ import { contacts } from '@octane-xplat/contacts'
21
+
22
+ export async function chooseContacts() {
23
+ if (!contacts.supported || (await contacts.ensure()) !== 'granted') return []
24
+ return contacts.getAll({ fields: ['name', 'phoneNumbers'], sort: 'lastName' })
25
+ }
26
+ ```
27
+
28
+ On native, the result contains matching address-book entries. In a supported
29
+ browser, it contains only the contacts the person picked. Show an empty state
30
+ when none are returned and distinguish denied access in your screen. Do not
31
+ log contact details while testing; verify a displayed count or a test contact.
32
+
33
+ ID and name lookups and writes are native-only. Android ID lookup reads the
34
+ store and filters it, so avoid repeated lookups for large address books.
35
+ macOS and Windows report unsupported. See the
36
+ [public contract](https://github.com/octane-xplat/octane-xplat/blob/main/packages/contacts/src/types.ts)
37
+ and [device capability handling](https://octane-xplat.goddardai.org/platform-services#the-shared-service-shape)
38
+ for integration boundaries.
package/package.json CHANGED
@@ -1,11 +1,88 @@
1
1
  {
2
2
  "name": "@octane-xplat/contacts",
3
- "version": "0.0.1",
4
- "description": "Placeholder release — no supported API. The first real version publishes via octane-xplat CI.",
3
+ "version": "0.19.0",
4
+ "description": "Device address book for Octane xplat — contact reads and writes on iOS/Android, Contact Picker API on web",
5
+ "keywords": [
6
+ "android",
7
+ "cross-platform",
8
+ "nativescript",
9
+ "octane",
10
+ "xplat",
11
+ "contacts",
12
+ "address-book"
13
+ ],
14
+ "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/contacts",
5
15
  "license": "MIT",
6
16
  "repository": {
7
17
  "type": "git",
8
18
  "url": "https://github.com/octane-xplat/octane-xplat",
9
19
  "directory": "packages/contacts"
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
+ "@nativescript-community/octane": "0.2.5",
58
+ "@nativescript/core": "9.1.3",
59
+ "@nativescript/types": "9.1.4",
60
+ "@tsrx/typescript-plugin": "0.4.11",
61
+ "octane": "0.16.3",
62
+ "tsrx-typegen": "0.5.0",
63
+ "typescript": "5.9.3"
64
+ },
65
+ "peerDependencies": {
66
+ "@nativescript-community/octane": ">=0.2.1 <1",
67
+ "@nativescript/core": ">=9.1.0 <10",
68
+ "octane": ">=0.6.3 <1"
69
+ },
70
+ "peerDependenciesMeta": {
71
+ "@nativescript-community/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
+ "@nativescript/contacts": "3.0.0",
86
+ "@octane-xplat/platform": "0.19.0"
10
87
  }
11
88
  }
@@ -0,0 +1,4 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.READ_CONTACTS" />
3
+ <uses-permission android:name="android.permission.WRITE_CONTACTS" />
4
+ </manifest>
@@ -0,0 +1,8 @@
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>NSContactsUsageDescription</key>
6
+ <string>Contacts access is required to read and write the address book.</string>
7
+ </dict>
8
+ </plist>
@@ -0,0 +1,2 @@
1
+ // Linux's system webview runs the shared web implementation.
2
+ export { contacts } from './contacts.web'
@@ -0,0 +1,344 @@
1
+ // Contacts — AppKit leaf over CNContactStore. The Contacts framework is
2
+ // bridgeable through the JSC host; semantics mirror the iOS leaf.
3
+ // CNContactNoteKey requires a contacts-notes entitlement even on macOS —
4
+ // it is excluded from fetch keys and `note` stays absent unless the store
5
+ // reports the key available.
6
+ import {
7
+ CNContact,
8
+ CNContactFetchRequest,
9
+ CNContactIdentifierKey,
10
+ CNContactEmailAddressesKey,
11
+ CNContactFamilyNameKey,
12
+ CNContactGivenNameKey,
13
+ CNContactImageDataKey,
14
+ CNContactJobTitleKey,
15
+ CNContactMiddleNameKey,
16
+ CNContactNicknameKey,
17
+ CNContactNoteKey,
18
+ CNContactOrganizationNameKey,
19
+ CNContactPhoneNumbersKey,
20
+ CNContactPostalAddressesKey,
21
+ CNContactStore,
22
+ CNContactUrlAddressesKey,
23
+ CNEntityType,
24
+ CNLabeledValue,
25
+ CNMutableContact,
26
+ CNPhoneNumber,
27
+ CNSaveRequest,
28
+ } from '@octane-xplat/platform/macos'
29
+ import type {
30
+ Contact,
31
+ ContactAddress,
32
+ ContactField,
33
+ Contacts,
34
+ GetContactsOptions,
35
+ NewContact,
36
+ PermissionResult,
37
+ } from './types'
38
+
39
+ let store: any = null
40
+ const contactStore = () => {
41
+ if (store) {
42
+ return store
43
+ }
44
+
45
+ try {
46
+ if (typeof CNContactStore?.authorizationStatusForEntityType !== 'function') {
47
+ return null
48
+ }
49
+ return (store = CNContactStore.new())
50
+ } catch {
51
+ return null
52
+ }
53
+ }
54
+
55
+ // CNAuthorizationStatus: 0 notDetermined 1 restricted 2 denied 3 authorized
56
+ const rawStatus = () =>
57
+ Number(CNContactStore.authorizationStatusForEntityType(CNEntityType.CNEntityTypeContacts ?? 0))
58
+
59
+ function ensureAccess(): Promise<PermissionResult> {
60
+ const s = contactStore()
61
+ if (!s) {
62
+ return Promise.resolve('unsupported')
63
+ }
64
+
65
+ const status = rawStatus()
66
+ if (status === 3) {
67
+ return Promise.resolve('granted')
68
+ }
69
+
70
+ if (status === 1 || status === 2) {
71
+ return Promise.resolve('denied')
72
+ }
73
+
74
+ return new Promise((resolve) => {
75
+ s.requestAccessForEntityTypeCompletionHandler(CNEntityType.CNEntityTypeContacts ?? 0, (granted: boolean) =>
76
+ resolve(granted ? 'granted' : 'denied'),
77
+ )
78
+ })
79
+ }
80
+
81
+ const BASE_KEYS = [
82
+ CNContactIdentifierKey,
83
+ CNContactGivenNameKey,
84
+ CNContactMiddleNameKey,
85
+ CNContactFamilyNameKey,
86
+ CNContactNicknameKey,
87
+ ]
88
+
89
+ const FIELD_KEYS: Record<Exclude<ContactField, 'name'>, string[]> = {
90
+ emails: [CNContactEmailAddressesKey],
91
+ phoneNumbers: [CNContactPhoneNumbersKey],
92
+ addresses: [CNContactPostalAddressesKey],
93
+ urls: [CNContactUrlAddressesKey],
94
+ company: [CNContactOrganizationNameKey, CNContactJobTitleKey],
95
+ note: [], // entitlement-gated on macOS too — read only when the key is available
96
+ image: [CNContactImageDataKey],
97
+ nickname: [],
98
+ }
99
+
100
+ function fetchKeys(fields?: ContactField[]): string[] {
101
+ const keys = [...BASE_KEYS]
102
+ for (const field of fields ?? (Object.keys(FIELD_KEYS) as ContactField[])) {
103
+ for (const key of FIELD_KEYS[field as keyof typeof FIELD_KEYS] ?? []) {
104
+ if (!keys.includes(key)) {
105
+ keys.push(key)
106
+ }
107
+ }
108
+ }
109
+ return keys
110
+ }
111
+
112
+ const nsarray = (list: any): any[] => {
113
+ if (!list) {
114
+ return []
115
+ }
116
+
117
+ if (Array.isArray(list)) {
118
+ return list
119
+ }
120
+
121
+ const out: any[] = []
122
+ for (let i = 0, count = Number(list.count ?? 0); i < count; i++) {
123
+ out.push(list.objectAtIndex(i))
124
+ }
125
+ return out
126
+ }
127
+
128
+ const labeled = (list: any, value: (entry: any) => unknown) =>
129
+ nsarray(list).map((entry) => ({ label: entry?.label ? String(entry.label) : undefined, value: value(entry) }))
130
+
131
+ function asContact(native: any): Contact {
132
+ const firstName = native?.givenName ? String(native.givenName) : undefined
133
+ const lastName = native?.familyName ? String(native.familyName) : undefined
134
+ const name =
135
+ native?.name && typeof native.name === 'string'
136
+ ? native.name
137
+ : [firstName, lastName].filter(Boolean).join(' ') ||
138
+ (native?.organizationName ? String(native.organizationName) : '')
139
+
140
+ const contact: Contact = {
141
+ id: String(native?.identifier ?? ''),
142
+ name,
143
+ firstName,
144
+ middleName: native?.middleName ? String(native.middleName) : undefined,
145
+ lastName,
146
+ nickname: native?.nickname ? String(native.nickname) : undefined,
147
+ emails: labeled(native?.emailAddresses, (e) => String(e?.value ?? '')).map(
148
+ ({ label, value }) => ({ label, email: value as string }),
149
+ ),
150
+ phoneNumbers: labeled(native?.phoneNumbers, (e) => String(e?.value?.stringValue ?? '')).map(
151
+ ({ label, value }) => ({ label, number: value as string }),
152
+ ),
153
+ addresses: labeled(
154
+ native?.postalAddresses,
155
+ (e): ContactAddress => ({
156
+ street: e?.value?.street ? String(e.value.street) : undefined,
157
+ city: e?.value?.city ? String(e.value.city) : undefined,
158
+ region: e?.value?.state ? String(e.value.state) : undefined,
159
+ postalCode: e?.value?.postalCode ? String(e.value.postalCode) : undefined,
160
+ country: e?.value?.country ? String(e.value.country) : undefined,
161
+ }),
162
+ ).map(({ label, value }) => ({ label, ...(value as ContactAddress) })),
163
+ urls: labeled(native?.urlAddresses, (e) => String(e?.value ?? '')).map(
164
+ ({ label, value }) => ({ label, url: value as string }),
165
+ ),
166
+ company: native?.organizationName ? String(native.organizationName) : undefined,
167
+ jobTitle: native?.jobTitle ? String(native.jobTitle) : undefined,
168
+ }
169
+
170
+ // The notes entitlement is a distribution choice; read it only when the
171
+ // fetched keys already carry it.
172
+ try {
173
+ if (native?.isKeyAvailable?.(CNContactNoteKey) && native?.note) {
174
+ contact.note = String(native.note)
175
+ }
176
+ } catch {
177
+ // A store without the notes entitlement leaves the field absent.
178
+ }
179
+
180
+ try {
181
+ if (native?.imageDataAvailable) {
182
+ const data = native?.imageData
183
+ const base64 = data?.base64EncodedStringWithOptions?.(0)
184
+ if (base64) {
185
+ contact.image = { data: String(base64) }
186
+ }
187
+ }
188
+ } catch {
189
+ // Unfetched or unreadable image data is omitted, never fatal.
190
+ }
191
+
192
+ return contact
193
+ }
194
+
195
+ function applySort(list: Contact[], sort?: GetContactsOptions['sort']): Contact[] {
196
+ if (!sort || sort === 'none') {
197
+ return list
198
+ }
199
+
200
+ const key = sort === 'firstName' ? 'firstName' : 'lastName'
201
+ return [...list].sort((a, b) => (a[key] ?? a.name).localeCompare(b[key] ?? b.name))
202
+ }
203
+
204
+ function applyPage(list: Contact[], options?: GetContactsOptions): Contact[] {
205
+ const start = options?.pageOffset ?? 0
206
+ const size = options?.pageSize
207
+ return size === undefined ? list.slice(start) : list.slice(start, start + size)
208
+ }
209
+
210
+ function requireStore(): any {
211
+ const s = contactStore()
212
+ if (!s) {
213
+ throw new Error('contacts: the Contacts store is unavailable on this host')
214
+ }
215
+ return s
216
+ }
217
+
218
+ function applyNewContact(target: any, source: NewContact): void {
219
+ target.givenName = source.firstName ?? ''
220
+ target.middleName = source.middleName ?? ''
221
+ target.familyName = source.lastName ?? ''
222
+ target.nickname = source.nickname ?? ''
223
+ target.organizationName = source.company ?? ''
224
+ target.jobTitle = source.jobTitle ?? ''
225
+ target.emailAddresses = (source.emails ?? []).map((e) =>
226
+ CNLabeledValue.labeledValueWithLabelValue(e.label ?? null, e.email),
227
+ )
228
+ target.phoneNumbers = (source.phoneNumbers ?? []).map((p) =>
229
+ CNLabeledValue.labeledValueWithLabelValue(
230
+ p.label ?? null,
231
+ CNPhoneNumber.phoneNumberWithStringValue(p.number),
232
+ ),
233
+ )
234
+ }
235
+
236
+ /** Contacts service — system address book. */
237
+ export const contacts: Contacts = {
238
+ get supported() {
239
+ return contactStore() !== null
240
+ },
241
+
242
+ ensure(): Promise<PermissionResult> {
243
+ return ensureAccess()
244
+ },
245
+
246
+ async getAll(options?: GetContactsOptions): Promise<Contact[]> {
247
+ const s = requireStore()
248
+ const request = CNContactFetchRequest.alloc().initWithKeysToFetch(fetchKeys(options?.fields))
249
+ const out: Contact[] = []
250
+ if (
251
+ !s.enumerateContactsWithFetchRequestErrorUsingBlock(request, null, (contact: any) => {
252
+ out.push(asContact(contact))
253
+ })
254
+ ) {
255
+ throw new Error('contacts.getAll: the store refused the fetch request')
256
+ }
257
+
258
+ return applyPage(applySort(out, options?.sort), options)
259
+ },
260
+
261
+ async getByName(predicate: string, fields?: ContactField[]): Promise<Contact[]> {
262
+ const s = requireStore()
263
+ const list = s.unifiedContactsMatchingPredicateKeysToFetchError(
264
+ CNContact.predicateForContactsMatchingName(predicate),
265
+ fetchKeys(fields),
266
+ null,
267
+ )
268
+ return nsarray(list).map(asContact)
269
+ },
270
+
271
+ async getById(id: string, fields?: ContactField[]): Promise<Contact | null> {
272
+ const s = requireStore()
273
+ const native = s.unifiedContactWithIdentifierKeysToFetchError(id, fetchKeys(fields), null)
274
+ return native ? asContact(native) : null
275
+ },
276
+
277
+ async add(contact: NewContact): Promise<string> {
278
+ const s = requireStore()
279
+ const native = CNMutableContact.new()
280
+ applyNewContact(native, contact)
281
+ const request = CNSaveRequest.new()
282
+ request.addContactToContainerWithIdentifier(native, null)
283
+ if (!s.executeSaveRequestError(request, null)) {
284
+ throw new Error('contacts.add: the store refused the save request')
285
+ }
286
+ return String(native.identifier ?? '')
287
+ },
288
+
289
+ async update(id: string, contact: NewContact): Promise<string> {
290
+ const s = requireStore()
291
+ const existing = s.unifiedContactWithIdentifierKeysToFetchError(
292
+ id,
293
+ fetchKeys(),
294
+ null,
295
+ )
296
+ if (!existing) {
297
+ throw new Error(`contacts.update: no contact with id ${id}`)
298
+ }
299
+
300
+ const native = existing.mutableCopy()
301
+ applyNewContact(native, contact)
302
+ const request = CNSaveRequest.new()
303
+ request.updateContact(native)
304
+ if (!s.executeSaveRequestError(request, null)) {
305
+ throw new Error('contacts.update: the store refused the save request')
306
+ }
307
+ return id
308
+ },
309
+
310
+ async remove(id: string): Promise<void> {
311
+ const s = requireStore()
312
+ const existing = s.unifiedContactWithIdentifierKeysToFetchError(id, [CNContactIdentifierKey], null)
313
+ if (!existing) {
314
+ return
315
+ }
316
+
317
+ const request = CNSaveRequest.new()
318
+ request.deleteContact(existing.mutableCopy())
319
+ if (!s.executeSaveRequestError(request, null)) {
320
+ throw new Error('contacts.remove: the store refused the save request')
321
+ }
322
+ },
323
+ }
324
+
325
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
326
+ permissionOwners.contacts = {
327
+ getPermissions: async () => {
328
+ const s = contactStore()
329
+ if (!s) {
330
+ return { status: 'unsupported' as const, granted: false, canAskAgain: false }
331
+ }
332
+
333
+ const status = rawStatus()
334
+ return {
335
+ status: status === 3 ? ('granted' as const) : status === 0 ? ('undetermined' as const) : ('denied' as const),
336
+ granted: status === 3,
337
+ canAskAgain: status === 0 || status === 3,
338
+ }
339
+ },
340
+ requestPermissions: async () => {
341
+ const result = await contacts.ensure()
342
+ return { status: result, granted: result === 'granted', canAskAgain: result === 'granted' }
343
+ },
344
+ }
@@ -0,0 +1,254 @@
1
+ // Contacts — native leaf over @nativescript/contacts. The plugin's worker
2
+ // fetch is normalized into our Expo-shaped Contact; permission goes through
3
+ // the platform primitives directly (same rationale as media's ensureCamera:
4
+ // plugin-side request helpers can't drift).
5
+ import { Application } from '@nativescript/core'
6
+ import { Contact as NativeContact, Contacts as NativeContacts } from '@nativescript/contacts'
7
+ import { android } from '@octane-xplat/platform/android'
8
+ import type {
9
+ Contact,
10
+ ContactAddress,
11
+ ContactField,
12
+ Contacts,
13
+ GetContactsOptions,
14
+ NewContact,
15
+ PermissionResult,
16
+ } from './types'
17
+
18
+ // iOS CNContactStore — outside the @nativescript/types default subset.
19
+ declare const CNContactStore: any
20
+ declare const CNEntityTypeContacts: number | undefined
21
+
22
+ const ALL_FIELDS: ContactField[] = [
23
+ 'name',
24
+ 'emails',
25
+ 'phoneNumbers',
26
+ 'addresses',
27
+ 'urls',
28
+ 'company',
29
+ 'note',
30
+ 'image',
31
+ 'nickname',
32
+ ]
33
+
34
+ // Our field names → the plugin's contactFields vocabulary.
35
+ const PLUGIN_FIELDS: Record<ContactField, string> = {
36
+ name: 'name',
37
+ emails: 'emailAddresses',
38
+ phoneNumbers: 'phoneNumbers',
39
+ addresses: 'postalAddresses',
40
+ urls: 'urls',
41
+ company: 'organization',
42
+ note: 'notes',
43
+ image: 'photo',
44
+ nickname: 'nickname',
45
+ }
46
+
47
+ function pluginFields(fields?: ContactField[]): string[] {
48
+ const wanted = fields ?? ALL_FIELDS
49
+ const mapped = wanted.map((f) => PLUGIN_FIELDS[f])
50
+ // The plugin reads `name` for the display string regardless of selection.
51
+ if (!mapped.includes('name')) {
52
+ mapped.push('name')
53
+ }
54
+ return mapped
55
+ }
56
+
57
+ function iosEnsure(): Promise<PermissionResult> {
58
+ const store = typeof CNContactStore === 'undefined' ? null : CNContactStore.new?.()
59
+ if (!store || typeof CNEntityTypeContacts === 'undefined') {
60
+ return Promise.resolve('unsupported')
61
+ }
62
+ // CNAuthorizationStatus: 0 notDetermined, 1 restricted, 2 denied, 3 authorized
63
+ const status = CNContactStore.authorizationStatusForEntityType(CNEntityTypeContacts)
64
+ if (status === 3) {
65
+ return Promise.resolve('granted')
66
+ }
67
+ if (status === 1 || status === 2) {
68
+ return Promise.resolve('denied')
69
+ }
70
+ return new Promise((resolve) => {
71
+ store.requestAccessForEntityTypeCompletionHandler(CNEntityTypeContacts, (granted: boolean) =>
72
+ resolve(granted ? 'granted' : 'denied'),
73
+ )
74
+ })
75
+ }
76
+
77
+ let contactRequestCode = 7719
78
+
79
+ function androidEnsure(): Promise<PermissionResult> {
80
+ const perm = 'android.permission.READ_CONTACTS'
81
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
82
+ try {
83
+ if (
84
+ activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
85
+ ) {
86
+ return Promise.resolve('granted')
87
+ }
88
+
89
+ if (!activity) {
90
+ return Promise.resolve('denied')
91
+ }
92
+
93
+ return new Promise<PermissionResult>((resolve) => {
94
+ const requestCode = contactRequestCode++
95
+ const event = Application.android.activityRequestPermissionsEvent
96
+ const onResult = (args: any) => {
97
+ if (args.requestCode !== requestCode) {
98
+ return
99
+ }
100
+ Application.android.off(event, onResult)
101
+ resolve(
102
+ args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
103
+ ? 'granted'
104
+ : 'denied',
105
+ )
106
+ }
107
+ Application.android.on(event, onResult)
108
+ try {
109
+ activity.requestPermissions([perm], requestCode)
110
+ } catch {
111
+ Application.android.off(event, onResult)
112
+ resolve('denied')
113
+ }
114
+ })
115
+ } catch {
116
+ return Promise.resolve('denied')
117
+ }
118
+ }
119
+
120
+ function asContact(native: any): Contact {
121
+ const collection = (list: any, key: string) =>
122
+ (list ?? []).map((c: any) => ({ label: c?.label, [key]: c?.value }))
123
+ const address = (list: any): ContactAddress[] =>
124
+ (list ?? []).map((c: any) => {
125
+ const v = c?.value ?? {}
126
+ return {
127
+ label: c?.label,
128
+ street: v.street ?? v.Street,
129
+ city: v.city ?? v.City,
130
+ region: v.state ?? v.State ?? v.region,
131
+ postalCode: v.postalCode ?? v.postcode ?? v.PostalCode,
132
+ country: v.country ?? v.Country,
133
+ }
134
+ })
135
+ const given = native?.name?.given
136
+ const family = native?.name?.family
137
+ return {
138
+ id: String(native?.id ?? ''),
139
+ name: native?.name?.displayname ?? [given, family].filter(Boolean).join(' ') ?? '',
140
+ firstName: given,
141
+ middleName: native?.name?.middle,
142
+ lastName: family,
143
+ nickname: native?.nickname,
144
+ emails: collection(native?.emailAddresses, 'email'),
145
+ phoneNumbers: collection(native?.phoneNumbers, 'number'),
146
+ addresses: address(native?.postalAddresses),
147
+ urls: collection(native?.urls, 'url'),
148
+ company: native?.organization?.name,
149
+ jobTitle: native?.organization?.jobTitle,
150
+ note: native?.notes,
151
+ image: native?.photo,
152
+ }
153
+ }
154
+
155
+ function applySort(list: Contact[], sort?: GetContactsOptions['sort']): Contact[] {
156
+ if (!sort || sort === 'none') {
157
+ return list
158
+ }
159
+ const key = sort === 'firstName' ? 'firstName' : 'lastName'
160
+ return [...list].sort((a, b) => (a[key] ?? a.name).localeCompare(b[key] ?? b.name))
161
+ }
162
+
163
+ function applyPage(list: Contact[], options?: GetContactsOptions): Contact[] {
164
+ const start = options?.pageOffset ?? 0
165
+ const size = options?.pageSize
166
+ return size === undefined ? list.slice(start) : list.slice(start, start + size)
167
+ }
168
+
169
+ function applyNewContact(target: any, source: NewContact): void {
170
+ // The plugin's save() reads every name member incl. phonetic — unset
171
+ // members are native crashes, not omissions.
172
+ target.name = {
173
+ given: source.firstName ?? '',
174
+ middle: source.middleName ?? '',
175
+ family: source.lastName ?? '',
176
+ prefix: '',
177
+ suffix: '',
178
+ phonetic: { given: '', middle: '', family: '' },
179
+ }
180
+ target.nickname = source.nickname
181
+ target.notes = source.note
182
+ if (source.company || source.jobTitle) {
183
+ target.organization = { name: source.company, jobTitle: source.jobTitle }
184
+ }
185
+ target.emailAddresses = (source.emails ?? []).map((e) => ({ label: e.label, value: e.email }))
186
+ target.phoneNumbers = (source.phoneNumbers ?? []).map((p) => ({
187
+ label: p.label,
188
+ value: p.number,
189
+ }))
190
+ // save() also maps postalAddresses/urls unconditionally.
191
+ target.postalAddresses = []
192
+ target.urls = []
193
+ target.photo = null
194
+ }
195
+
196
+ /** Contacts service — system address book. */
197
+ export const contacts: Contacts = {
198
+ supported: true,
199
+
200
+ ensure(): Promise<PermissionResult> {
201
+ return Application.ios ? iosEnsure() : androidEnsure()
202
+ },
203
+
204
+ async getAll(options?: GetContactsOptions): Promise<Contact[]> {
205
+ const result = await NativeContacts.getAllContacts(pluginFields(options?.fields))
206
+ return applyPage(applySort((result?.data ?? []).map(asContact), options?.sort), options)
207
+ },
208
+
209
+ async getByName(predicate: string, fields?: ContactField[]): Promise<Contact[]> {
210
+ const result = await NativeContacts.getContactsByName(predicate, pluginFields(fields))
211
+ return (result?.data ?? []).map(asContact)
212
+ },
213
+
214
+ async getById(id: string, fields?: ContactField[]): Promise<Contact | null> {
215
+ if (Application.ios) {
216
+ const result = await NativeContacts.getContactById(id, pluginFields(fields))
217
+ const native = result?.data ?? result
218
+ return native ? asContact(native) : null
219
+ }
220
+ // Plugin ships getContactById for iOS only — full-store fetch + filter.
221
+ const result = await NativeContacts.getAllContactsWithoutWorker(pluginFields(fields))
222
+ const native = (result?.data ?? []).find((c: any) => String(c?.id) === id)
223
+ return native ? asContact(native) : null
224
+ },
225
+
226
+ async add(contact: NewContact): Promise<string> {
227
+ const native = new (NativeContact as any)()
228
+ applyNewContact(native, contact)
229
+ native.save()
230
+ return String(native.id ?? '')
231
+ },
232
+
233
+ async update(id: string, contact: NewContact): Promise<string> {
234
+ const existing = await contacts.getById(id)
235
+ if (!existing) {
236
+ throw new Error(`contacts.update: no contact with id ${id}`)
237
+ }
238
+ const native = new (NativeContact as any)()
239
+ native.id = id
240
+ applyNewContact(native, contact)
241
+ native.save()
242
+ return id
243
+ },
244
+
245
+ async remove(id: string): Promise<void> {
246
+ const native = new (NativeContact as any)()
247
+ native.id = id
248
+ native.delete()
249
+ },
250
+ }
251
+
252
+ // Register the permission kind this leaf owns for the platform dispatcher.
253
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
254
+ permissionOwners.contacts = () => contacts.ensure()
@@ -0,0 +1,58 @@
1
+ // Contacts — web leaf over the Contact Picker API. Chromium-only, picker UX
2
+ // (the user picks contacts per call — there is no store scan), read-only,
3
+ // and limited to name/email/tel fields. Everything the picker can't express
4
+ // reports unsupported rather than faking a store.
5
+ import type { Contact, Contacts, GetContactsOptions, NewContact, PermissionResult } from './types'
6
+
7
+ interface ContactPicker {
8
+ select(properties: string[], options?: { multiple?: boolean }): Promise<any[]>
9
+ getProperties(): Promise<string[]>
10
+ }
11
+
12
+ const picker = (): ContactPicker | null => {
13
+ const nav = (globalThis as any).navigator
14
+ return typeof nav?.contacts?.select === 'function' ? (nav.contacts as ContactPicker) : null
15
+ }
16
+
17
+ function asContact(native: any): Contact {
18
+ return {
19
+ id: '',
20
+ name: Array.isArray(native?.name) ? native.name.join(' ') : (native?.name ?? ''),
21
+ emails: (native?.email ?? []).map((e: string) => ({ email: e })),
22
+ phoneNumbers: (native?.tel ?? []).map((t: string) => ({ number: t })),
23
+ }
24
+ }
25
+
26
+ const unsupported = (what: string) => () =>
27
+ Promise.reject(
28
+ new Error(`unsupported: contact ${what} is not available through the web Contact Picker`),
29
+ )
30
+
31
+ /** Contacts service — system address book. */
32
+ export const contacts: Contacts = {
33
+ supported: picker() !== null,
34
+
35
+ // The picker has no permission state to query — choosing contacts IS the
36
+ // grant. Report granted when the API exists so apps don't gate on it.
37
+ ensure(): Promise<PermissionResult> {
38
+ return Promise.resolve(picker() ? 'granted' : 'unsupported')
39
+ },
40
+
41
+ async getAll(options?: GetContactsOptions): Promise<Contact[]> {
42
+ const p = picker()
43
+ if (!p) {
44
+ throw new Error('unsupported: navigator.contacts.select is not available')
45
+ }
46
+ const selected = await p.select(['name', 'email', 'tel'], { multiple: true })
47
+ return (selected ?? []).map(asContact)
48
+ },
49
+
50
+ getByName: unsupported('lookup'),
51
+ getById: unsupported('lookup'),
52
+ add: (_contact: NewContact) => unsupported('writes')(),
53
+ update: (_id: string, _contact: NewContact) => unsupported('writes')(),
54
+ remove: unsupported('writes'),
55
+ }
56
+
57
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
58
+ permissionOwners.contacts = () => contacts.ensure()
@@ -0,0 +1,21 @@
1
+ // Windows leaf — @nativescript/contacts ships no windows backend; report
2
+ // unsupported rather than breaking the import graph.
3
+ import type { Contacts, PermissionResult } from './types'
4
+
5
+ const unsupported = () =>
6
+ Promise.reject(new Error('unsupported: contacts is not available on windows'))
7
+
8
+ /** Contacts service — system address book. */
9
+ export const contacts: Contacts = {
10
+ supported: false,
11
+ ensure: async (): Promise<PermissionResult> => 'unsupported',
12
+ getAll: unsupported,
13
+ getByName: unsupported,
14
+ getById: unsupported,
15
+ add: unsupported,
16
+ update: unsupported,
17
+ remove: unsupported,
18
+ }
19
+
20
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
21
+ permissionOwners.contacts = () => contacts.ensure()
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { contacts } from './contacts.macos'
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { contacts } from './contacts'
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { contacts } from './contacts.web'
package/src/types.ts ADDED
@@ -0,0 +1,147 @@
1
+ /** Coarse permission answer; unsupported means no contacts/permission path. */
2
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported'
3
+
4
+ /** Fields the app asks for — a superset is fetched natively, this selects
5
+ * which members are populated on the returned Contact. */
6
+ export type ContactField =
7
+ | 'name'
8
+ | 'emails'
9
+ | 'phoneNumbers'
10
+ | 'addresses'
11
+ | 'urls'
12
+ | 'company'
13
+ | 'note'
14
+ | 'image'
15
+ | 'nickname'
16
+
17
+ /** One labeled email field. */
18
+ export interface ContactEmail {
19
+ /** Free-form label (home/work/custom) as stored. */
20
+ label?: string
21
+ /** Email address value. */
22
+ email: string
23
+ }
24
+
25
+ /** One labeled phone field. */
26
+ export interface ContactPhone {
27
+ /** Free-form label (home/work/custom) as stored. */
28
+ label?: string
29
+ /** Phone number string as stored. */
30
+ number: string
31
+ }
32
+
33
+ /** One labeled postal address. */
34
+ export interface ContactAddress {
35
+ /** Free-form label (home/work/custom) as stored. */
36
+ label?: string
37
+ /** Street line(s). */
38
+ street?: string
39
+ /** City. */
40
+ city?: string
41
+ /** State/province region. */
42
+ region?: string
43
+ /** Postal/ZIP code. */
44
+ postalCode?: string
45
+ /** Country name or code. */
46
+ country?: string
47
+ }
48
+
49
+ /** One labeled URL field. */
50
+ export interface ContactUrl {
51
+ /** Free-form label (home/work/custom) as stored. */
52
+ label?: string
53
+ /** URL value. */
54
+ url: string
55
+ }
56
+
57
+ /** A stored contact record. */
58
+ export interface Contact {
59
+ /** Store-assigned contact id. */
60
+ id: string
61
+ /** Display name — falls back to composed given/family when the store
62
+ * lacks a display string. */
63
+ name: string
64
+ /** Given name. */
65
+ firstName?: string
66
+ /** Middle name(s). */
67
+ middleName?: string
68
+ /** Family name. */
69
+ lastName?: string
70
+ /** Nickname. */
71
+ nickname?: string
72
+ /** Email addresses with labels. */
73
+ emails?: ContactEmail[]
74
+ /** Phone numbers with labels. */
75
+ phoneNumbers?: ContactPhone[]
76
+ /** Postal addresses with labels. */
77
+ addresses?: ContactAddress[]
78
+ /** Associated URLs with labels. */
79
+ urls?: ContactUrl[]
80
+ /** Organization name. */
81
+ company?: string
82
+ /** Role within the organization. */
83
+ jobTitle?: string
84
+ /** Free-text note field. */
85
+ note?: string
86
+ /** Platform image reference when 'image' was requested — a file path or
87
+ * data reference; shape is platform-dependent. */
88
+ image?: unknown
89
+ }
90
+
91
+ /** Contact fields for add/update — no store id. */
92
+ export interface NewContact {
93
+ /** Given name. */
94
+ firstName?: string
95
+ /** Middle name(s). */
96
+ middleName?: string
97
+ /** Family name. */
98
+ lastName?: string
99
+ /** Nickname. */
100
+ nickname?: string
101
+ /** Email addresses with labels. */
102
+ emails?: ContactEmail[]
103
+ /** Phone numbers with labels. */
104
+ phoneNumbers?: ContactPhone[]
105
+ /** Organization name. */
106
+ company?: string
107
+ /** Role within the organization. */
108
+ jobTitle?: string
109
+ /** Free-text note field. */
110
+ note?: string
111
+ }
112
+
113
+ /** Paging options for getAll(). */
114
+ export interface GetContactsOptions {
115
+ /** Restrict which members are populated (all fetched by default). */
116
+ fields?: ContactField[]
117
+ /** Client-side sort — the native stores return an unspecified order. */
118
+ sort?: 'firstName' | 'lastName' | 'none'
119
+ /** Max contacts per page. */
120
+ pageSize?: number
121
+ /** Start offset into the result set. */
122
+ pageOffset?: number
123
+ }
124
+
125
+ /** System address-book facade; false supported off mobile. */
126
+ export interface Contacts {
127
+ /** Whether the system address book is reachable on this target — false off mobile. */
128
+ readonly supported: boolean
129
+ /** Ensure the contacts permission without prompting twice — returns the
130
+ * post-request grant state, 'unsupported' when the store can't be reached. */
131
+ ensure(): Promise<PermissionResult>
132
+ /** Fetch contacts in pages. */
133
+ getAll(options?: GetContactsOptions): Promise<Contact[]>
134
+ /** Substring search over display names. */
135
+ getByName(predicate: string, fields?: ContactField[]): Promise<Contact[]>
136
+ /** iOS: direct id fetch. Android: the plugin ships no id lookup, so this
137
+ * fetches the full store and filters — read-all cost, call sparingly. */
138
+ getById(id: string, fields?: ContactField[]): Promise<Contact | null>
139
+ /** Insert a contact; resolves the store-assigned id. */
140
+ add(contact: NewContact): Promise<string>
141
+ /** Patch fields of an existing contact by id. */
142
+ update(id: string, contact: NewContact): Promise<string>
143
+ /** Delete a contact by id. */
144
+ remove(id: string): Promise<void>
145
+ }
146
+
147
+ export declare const contacts: Contacts
@@ -0,0 +1,14 @@
1
+ {
2
+ "version": 1,
3
+ "files": [
4
+ "contacts.d.ts",
5
+ "contacts.linux.d.ts",
6
+ "contacts.macos.d.ts",
7
+ "contacts.web.d.ts",
8
+ "contacts.windows.d.ts",
9
+ "index.d.ts",
10
+ "index.macos.d.ts",
11
+ "index.web.d.ts",
12
+ "types.d.ts"
13
+ ]
14
+ }
@@ -0,0 +1,3 @@
1
+ import type { Contacts } from './types.js';
2
+ /** Contacts service — system address book. */
3
+ export declare const contacts: Contacts;
@@ -0,0 +1 @@
1
+ export { contacts } from './contacts.web.js';
@@ -0,0 +1,3 @@
1
+ import type { Contacts } from './types.js';
2
+ /** Contacts service — system address book. */
3
+ export declare const contacts: Contacts;
@@ -0,0 +1,3 @@
1
+ import type { Contacts } from './types.js';
2
+ /** Contacts service — system address book. */
3
+ export declare const contacts: Contacts;
@@ -0,0 +1,3 @@
1
+ import type { Contacts } from './types.js';
2
+ /** Contacts service — system address book. */
3
+ export declare const contacts: Contacts;
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { contacts } from './contacts.js';
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { contacts } from './contacts.macos.js';
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { contacts } from './contacts.web.js';
@@ -0,0 +1,128 @@
1
+ /** Coarse permission answer; unsupported means no contacts/permission path. */
2
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported';
3
+ /** Fields the app asks for — a superset is fetched natively, this selects
4
+ * which members are populated on the returned Contact. */
5
+ export type ContactField = 'name' | 'emails' | 'phoneNumbers' | 'addresses' | 'urls' | 'company' | 'note' | 'image' | 'nickname';
6
+ /** One labeled email field. */
7
+ export interface ContactEmail {
8
+ /** Free-form label (home/work/custom) as stored. */
9
+ label?: string;
10
+ /** Email address value. */
11
+ email: string;
12
+ }
13
+ /** One labeled phone field. */
14
+ export interface ContactPhone {
15
+ /** Free-form label (home/work/custom) as stored. */
16
+ label?: string;
17
+ /** Phone number string as stored. */
18
+ number: string;
19
+ }
20
+ /** One labeled postal address. */
21
+ export interface ContactAddress {
22
+ /** Free-form label (home/work/custom) as stored. */
23
+ label?: string;
24
+ /** Street line(s). */
25
+ street?: string;
26
+ /** City. */
27
+ city?: string;
28
+ /** State/province region. */
29
+ region?: string;
30
+ /** Postal/ZIP code. */
31
+ postalCode?: string;
32
+ /** Country name or code. */
33
+ country?: string;
34
+ }
35
+ /** One labeled URL field. */
36
+ export interface ContactUrl {
37
+ /** Free-form label (home/work/custom) as stored. */
38
+ label?: string;
39
+ /** URL value. */
40
+ url: string;
41
+ }
42
+ /** A stored contact record. */
43
+ export interface Contact {
44
+ /** Store-assigned contact id. */
45
+ id: string;
46
+ /** Display name — falls back to composed given/family when the store
47
+ * lacks a display string. */
48
+ name: string;
49
+ /** Given name. */
50
+ firstName?: string;
51
+ /** Middle name(s). */
52
+ middleName?: string;
53
+ /** Family name. */
54
+ lastName?: string;
55
+ /** Nickname. */
56
+ nickname?: string;
57
+ /** Email addresses with labels. */
58
+ emails?: ContactEmail[];
59
+ /** Phone numbers with labels. */
60
+ phoneNumbers?: ContactPhone[];
61
+ /** Postal addresses with labels. */
62
+ addresses?: ContactAddress[];
63
+ /** Associated URLs with labels. */
64
+ urls?: ContactUrl[];
65
+ /** Organization name. */
66
+ company?: string;
67
+ /** Role within the organization. */
68
+ jobTitle?: string;
69
+ /** Free-text note field. */
70
+ note?: string;
71
+ /** Platform image reference when 'image' was requested — a file path or
72
+ * data reference; shape is platform-dependent. */
73
+ image?: unknown;
74
+ }
75
+ /** Contact fields for add/update — no store id. */
76
+ export interface NewContact {
77
+ /** Given name. */
78
+ firstName?: string;
79
+ /** Middle name(s). */
80
+ middleName?: string;
81
+ /** Family name. */
82
+ lastName?: string;
83
+ /** Nickname. */
84
+ nickname?: string;
85
+ /** Email addresses with labels. */
86
+ emails?: ContactEmail[];
87
+ /** Phone numbers with labels. */
88
+ phoneNumbers?: ContactPhone[];
89
+ /** Organization name. */
90
+ company?: string;
91
+ /** Role within the organization. */
92
+ jobTitle?: string;
93
+ /** Free-text note field. */
94
+ note?: string;
95
+ }
96
+ /** Paging options for getAll(). */
97
+ export interface GetContactsOptions {
98
+ /** Restrict which members are populated (all fetched by default). */
99
+ fields?: ContactField[];
100
+ /** Client-side sort — the native stores return an unspecified order. */
101
+ sort?: 'firstName' | 'lastName' | 'none';
102
+ /** Max contacts per page. */
103
+ pageSize?: number;
104
+ /** Start offset into the result set. */
105
+ pageOffset?: number;
106
+ }
107
+ /** System address-book facade; false supported off mobile. */
108
+ export interface Contacts {
109
+ /** Whether the system address book is reachable on this target — false off mobile. */
110
+ readonly supported: boolean;
111
+ /** Ensure the contacts permission without prompting twice — returns the
112
+ * post-request grant state, 'unsupported' when the store can't be reached. */
113
+ ensure(): Promise<PermissionResult>;
114
+ /** Fetch contacts in pages. */
115
+ getAll(options?: GetContactsOptions): Promise<Contact[]>;
116
+ /** Substring search over display names. */
117
+ getByName(predicate: string, fields?: ContactField[]): Promise<Contact[]>;
118
+ /** iOS: direct id fetch. Android: the plugin ships no id lookup, so this
119
+ * fetches the full store and filters — read-all cost, call sparingly. */
120
+ getById(id: string, fields?: ContactField[]): Promise<Contact | null>;
121
+ /** Insert a contact; resolves the store-assigned id. */
122
+ add(contact: NewContact): Promise<string>;
123
+ /** Patch fields of an existing contact by id. */
124
+ update(id: string, contact: NewContact): Promise<string>;
125
+ /** Delete a contact by id. */
126
+ remove(id: string): Promise<void>;
127
+ }
128
+ export declare const contacts: Contacts;