@octane-xplat/contacts 0.18.0 → 0.20.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/src/contacts.ts CHANGED
@@ -6,13 +6,13 @@ import { Application } from '@nativescript/core'
6
6
  import { Contact as NativeContact, Contacts as NativeContacts } from '@nativescript/contacts'
7
7
  import { android } from '@octane-xplat/platform/android'
8
8
  import type {
9
- Contact,
10
- ContactAddress,
11
- ContactField,
12
- Contacts,
13
- GetContactsOptions,
14
- NewContact,
15
- PermissionResult,
9
+ Contact,
10
+ ContactAddress,
11
+ ContactField,
12
+ Contacts,
13
+ GetContactsOptions,
14
+ NewContact,
15
+ PermissionResult,
16
16
  } from './types'
17
17
 
18
18
  // iOS CNContactStore — outside the @nativescript/types default subset.
@@ -20,232 +20,266 @@ declare const CNContactStore: any
20
20
  declare const CNEntityTypeContacts: number | undefined
21
21
 
22
22
  const ALL_FIELDS: ContactField[] = [
23
- 'name',
24
- 'emails',
25
- 'phoneNumbers',
26
- 'addresses',
27
- 'urls',
28
- 'company',
29
- 'note',
30
- 'image',
31
- 'nickname',
23
+ 'name',
24
+ 'emails',
25
+ 'phoneNumbers',
26
+ 'addresses',
27
+ 'urls',
28
+ 'company',
29
+ 'note',
30
+ 'image',
31
+ 'nickname',
32
32
  ]
33
33
 
34
34
  // Our field names → the plugin's contactFields vocabulary.
35
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',
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
45
  }
46
46
 
47
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
48
+ const wanted = fields ?? ALL_FIELDS
49
+ const mapped = wanted.map((f) => PLUGIN_FIELDS[f])
50
+
51
+ // The plugin reads `name` for the display string regardless of selection.
52
+ if (!mapped.includes('name')) {
53
+ mapped.push('name')
54
+ }
55
+
56
+ return mapped
55
57
  }
56
58
 
57
59
  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
- })
60
+ const store = typeof CNContactStore === 'undefined' ? null : CNContactStore.new?.()
61
+
62
+ if (!store || typeof CNEntityTypeContacts === 'undefined') {
63
+ return Promise.resolve('unsupported')
64
+ }
65
+
66
+ // CNAuthorizationStatus: 0 notDetermined, 1 restricted, 2 denied, 3 authorized
67
+ const status = CNContactStore.authorizationStatusForEntityType(CNEntityTypeContacts)
68
+
69
+ if (status === 3) {
70
+ return Promise.resolve('granted')
71
+ }
72
+
73
+ if (status === 1 || status === 2) {
74
+ return Promise.resolve('denied')
75
+ }
76
+
77
+ return new Promise((resolve) => {
78
+ store.requestAccessForEntityTypeCompletionHandler(CNEntityTypeContacts, (granted: boolean) =>
79
+ resolve(granted ? 'granted' : 'denied'),
80
+ )
81
+ })
75
82
  }
76
83
 
77
84
  let contactRequestCode = 7719
78
85
 
79
86
  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
- if (!activity) {
89
- return Promise.resolve('denied')
90
- }
91
- return new Promise<PermissionResult>((resolve) => {
92
- const requestCode = contactRequestCode++
93
- const event = Application.android.activityRequestPermissionsEvent
94
- const onResult = (args: any) => {
95
- if (args.requestCode !== requestCode) {
96
- return
97
- }
98
- Application.android.off(event, onResult)
99
- resolve(
100
- args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
101
- ? 'granted'
102
- : 'denied',
103
- )
104
- }
105
- Application.android.on(event, onResult)
106
- try {
107
- activity.requestPermissions([perm], requestCode)
108
- } catch {
109
- Application.android.off(event, onResult)
110
- resolve('denied')
111
- }
112
- })
113
- } catch {
114
- return Promise.resolve('denied')
115
- }
87
+ const perm = 'android.permission.READ_CONTACTS'
88
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
89
+
90
+ try {
91
+ if (
92
+ activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
93
+ ) {
94
+ return Promise.resolve('granted')
95
+ }
96
+
97
+ if (!activity) {
98
+ return Promise.resolve('denied')
99
+ }
100
+
101
+ return new Promise<PermissionResult>((resolve) => {
102
+ const requestCode = contactRequestCode++
103
+ const event = Application.android.activityRequestPermissionsEvent
104
+ const onResult = (args: any) => {
105
+ if (args.requestCode !== requestCode) {
106
+ return
107
+ }
108
+
109
+ Application.android.off(event, onResult)
110
+ resolve(
111
+ args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
112
+ ? 'granted'
113
+ : 'denied',
114
+ )
115
+ }
116
+
117
+ Application.android.on(event, onResult)
118
+ try {
119
+ activity.requestPermissions([perm], requestCode)
120
+ } catch {
121
+ Application.android.off(event, onResult)
122
+ resolve('denied')
123
+ }
124
+ })
125
+ } catch {
126
+ return Promise.resolve('denied')
127
+ }
116
128
  }
117
129
 
118
130
  function asContact(native: any): Contact {
119
- const collection = (list: any, key: string) =>
120
- (list ?? []).map((c: any) => ({ label: c?.label, [key]: c?.value }))
121
- const address = (list: any): ContactAddress[] =>
122
- (list ?? []).map((c: any) => {
123
- const v = c?.value ?? {}
124
- return {
125
- label: c?.label,
126
- street: v.street ?? v.Street,
127
- city: v.city ?? v.City,
128
- region: v.state ?? v.State ?? v.region,
129
- postalCode: v.postalCode ?? v.postcode ?? v.PostalCode,
130
- country: v.country ?? v.Country,
131
- }
132
- })
133
- const given = native?.name?.given
134
- const family = native?.name?.family
135
- return {
136
- id: String(native?.id ?? ''),
137
- name: native?.name?.displayname ?? [given, family].filter(Boolean).join(' ') ?? '',
138
- firstName: given,
139
- middleName: native?.name?.middle,
140
- lastName: family,
141
- nickname: native?.nickname,
142
- emails: collection(native?.emailAddresses, 'email'),
143
- phoneNumbers: collection(native?.phoneNumbers, 'number'),
144
- addresses: address(native?.postalAddresses),
145
- urls: collection(native?.urls, 'url'),
146
- company: native?.organization?.name,
147
- jobTitle: native?.organization?.jobTitle,
148
- note: native?.notes,
149
- image: native?.photo,
150
- }
131
+ const collection = (list: any, key: string) =>
132
+ (list ?? []).map((c: any) => ({ label: c?.label, [key]: c?.value }))
133
+
134
+ const address = (list: any): ContactAddress[] =>
135
+ (list ?? []).map((c: any) => {
136
+ const v = c?.value ?? {}
137
+
138
+ return {
139
+ label: c?.label,
140
+ street: v.street ?? v.Street,
141
+ city: v.city ?? v.City,
142
+ region: v.state ?? v.State ?? v.region,
143
+ postalCode: v.postalCode ?? v.postcode ?? v.PostalCode,
144
+ country: v.country ?? v.Country,
145
+ }
146
+ })
147
+
148
+ const given = native?.name?.given
149
+ const family = native?.name?.family
150
+
151
+ return {
152
+ id: String(native?.id ?? ''),
153
+ name: native?.name?.displayname ?? [given, family].filter(Boolean).join(' ') ?? '',
154
+ firstName: given,
155
+ middleName: native?.name?.middle,
156
+ lastName: family,
157
+ nickname: native?.nickname,
158
+ emails: collection(native?.emailAddresses, 'email'),
159
+ phoneNumbers: collection(native?.phoneNumbers, 'number'),
160
+ addresses: address(native?.postalAddresses),
161
+ urls: collection(native?.urls, 'url'),
162
+ company: native?.organization?.name,
163
+ jobTitle: native?.organization?.jobTitle,
164
+ note: native?.notes,
165
+ image: native?.photo,
166
+ }
151
167
  }
152
168
 
153
169
  function applySort(list: Contact[], sort?: GetContactsOptions['sort']): Contact[] {
154
- if (!sort || sort === 'none') {
155
- return list
156
- }
157
- const key = sort === 'firstName' ? 'firstName' : 'lastName'
158
- return [...list].sort((a, b) => (a[key] ?? a.name).localeCompare(b[key] ?? b.name))
170
+ if (!sort || sort === 'none') {
171
+ return list
172
+ }
173
+
174
+ const key = sort === 'firstName' ? 'firstName' : 'lastName'
175
+
176
+ return [...list].sort((a, b) => (a[key] ?? a.name).localeCompare(b[key] ?? b.name))
159
177
  }
160
178
 
161
179
  function applyPage(list: Contact[], options?: GetContactsOptions): Contact[] {
162
- const start = options?.pageOffset ?? 0
163
- const size = options?.pageSize
164
- return size === undefined ? list.slice(start) : list.slice(start, start + size)
180
+ const start = options?.pageOffset ?? 0
181
+ const size = options?.pageSize
182
+
183
+ return size === undefined ? list.slice(start) : list.slice(start, start + size)
165
184
  }
166
185
 
167
186
  function applyNewContact(target: any, source: NewContact): void {
168
- // The plugin's save() reads every name member incl. phonetic — unset
169
- // members are native crashes, not omissions.
170
- target.name = {
171
- given: source.firstName ?? '',
172
- middle: source.middleName ?? '',
173
- family: source.lastName ?? '',
174
- prefix: '',
175
- suffix: '',
176
- phonetic: { given: '', middle: '', family: '' },
177
- }
178
- target.nickname = source.nickname
179
- target.notes = source.note
180
- if (source.company || source.jobTitle) {
181
- target.organization = { name: source.company, jobTitle: source.jobTitle }
182
- }
183
- target.emailAddresses = (source.emails ?? []).map((e) => ({ label: e.label, value: e.email }))
184
- target.phoneNumbers = (source.phoneNumbers ?? []).map((p) => ({
185
- label: p.label,
186
- value: p.number,
187
- }))
188
- // save() also maps postalAddresses/urls unconditionally.
189
- target.postalAddresses = []
190
- target.urls = []
191
- target.photo = null
187
+ // The plugin's save() reads every name member incl. phonetic — unset
188
+ // members are native crashes, not omissions.
189
+ target.name = {
190
+ given: source.firstName ?? '',
191
+ middle: source.middleName ?? '',
192
+ family: source.lastName ?? '',
193
+ prefix: '',
194
+ suffix: '',
195
+ phonetic: { given: '', middle: '', family: '' },
196
+ }
197
+
198
+ target.nickname = source.nickname
199
+ target.notes = source.note
200
+ if (source.company || source.jobTitle) {
201
+ target.organization = { name: source.company, jobTitle: source.jobTitle }
202
+ }
203
+
204
+ target.emailAddresses = (source.emails ?? []).map((e) => ({ label: e.label, value: e.email }))
205
+ target.phoneNumbers = (source.phoneNumbers ?? []).map((p) => ({
206
+ label: p.label,
207
+ value: p.number,
208
+ }))
209
+
210
+ // save() also maps postalAddresses/urls unconditionally.
211
+ target.postalAddresses = []
212
+ target.urls = []
213
+ target.photo = null
192
214
  }
193
215
 
216
+ /** Contacts service — system address book. */
194
217
  export const contacts: Contacts = {
195
- supported: true,
196
-
197
- ensure(): Promise<PermissionResult> {
198
- return Application.ios ? iosEnsure() : androidEnsure()
199
- },
200
-
201
- async getAll(options?: GetContactsOptions): Promise<Contact[]> {
202
- const result = await NativeContacts.getAllContacts(pluginFields(options?.fields))
203
- return applyPage(applySort((result?.data ?? []).map(asContact), options?.sort), options)
204
- },
205
-
206
- async getByName(predicate: string, fields?: ContactField[]): Promise<Contact[]> {
207
- const result = await NativeContacts.getContactsByName(predicate, pluginFields(fields))
208
- return (result?.data ?? []).map(asContact)
209
- },
210
-
211
- async getById(id: string, fields?: ContactField[]): Promise<Contact | null> {
212
- if (Application.ios) {
213
- const result = await NativeContacts.getContactById(id, pluginFields(fields))
214
- const native = result?.data ?? result
215
- return native ? asContact(native) : null
216
- }
217
- // Plugin ships getContactById for iOS only — full-store fetch + filter.
218
- const result = await NativeContacts.getAllContactsWithoutWorker(pluginFields(fields))
219
- const native = (result?.data ?? []).find((c: any) => String(c?.id) === id)
220
- return native ? asContact(native) : null
221
- },
222
-
223
- async add(contact: NewContact): Promise<string> {
224
- const native = new (NativeContact as any)()
225
- applyNewContact(native, contact)
226
- native.save()
227
- return String(native.id ?? '')
228
- },
229
-
230
- async update(id: string, contact: NewContact): Promise<string> {
231
- const existing = await contacts.getById(id)
232
- if (!existing) {
233
- throw new Error(`contacts.update: no contact with id ${id}`)
234
- }
235
- const native = new (NativeContact as any)()
236
- native.id = id
237
- applyNewContact(native, contact)
238
- native.save()
239
- return id
240
- },
241
-
242
- async remove(id: string): Promise<void> {
243
- const native = new (NativeContact as any)()
244
- native.id = id
245
- native.delete()
246
- },
218
+ supported: true,
219
+
220
+ ensure(): Promise<PermissionResult> {
221
+ return Application.ios ? iosEnsure() : androidEnsure()
222
+ },
223
+
224
+ async getAll(options?: GetContactsOptions): Promise<Contact[]> {
225
+ const result = await NativeContacts.getAllContacts(pluginFields(options?.fields))
226
+
227
+ return applyPage(applySort((result?.data ?? []).map(asContact), options?.sort), options)
228
+ },
229
+
230
+ async getByName(predicate: string, fields?: ContactField[]): Promise<Contact[]> {
231
+ const result = await NativeContacts.getContactsByName(predicate, pluginFields(fields))
232
+
233
+ return (result?.data ?? []).map(asContact)
234
+ },
235
+
236
+ async getById(id: string, fields?: ContactField[]): Promise<Contact | null> {
237
+ if (Application.ios) {
238
+ const result = await NativeContacts.getContactById(id, pluginFields(fields))
239
+ const native = result?.data ?? result
240
+
241
+ return native ? asContact(native) : null
242
+ }
243
+
244
+ // Plugin ships getContactById for iOS only — full-store fetch + filter.
245
+ const result = await NativeContacts.getAllContactsWithoutWorker(pluginFields(fields))
246
+ const native = (result?.data ?? []).find((c: any) => String(c?.id) === id)
247
+
248
+ return native ? asContact(native) : null
249
+ },
250
+
251
+ async add(contact: NewContact): Promise<string> {
252
+ const native = new (NativeContact as any)()
253
+
254
+ applyNewContact(native, contact)
255
+ native.save()
256
+ return String(native.id ?? '')
257
+ },
258
+
259
+ async update(id: string, contact: NewContact): Promise<string> {
260
+ const existing = await contacts.getById(id)
261
+
262
+ if (!existing) {
263
+ throw new Error(`contacts.update: no contact with id ${id}`)
264
+ }
265
+
266
+ const native = new (NativeContact as any)()
267
+
268
+ native.id = id
269
+ applyNewContact(native, contact)
270
+ native.save()
271
+ return id
272
+ },
273
+
274
+ async remove(id: string): Promise<void> {
275
+ const native = new (NativeContact as any)()
276
+
277
+ native.id = id
278
+ native.delete()
279
+ },
247
280
  }
248
281
 
249
282
  // Register the permission kind this leaf owns for the platform dispatcher.
250
283
  const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
284
+
251
285
  permissionOwners.contacts = () => contacts.ensure()
@@ -5,51 +5,59 @@
5
5
  import type { Contact, Contacts, GetContactsOptions, NewContact, PermissionResult } from './types'
6
6
 
7
7
  interface ContactPicker {
8
- select(properties: string[], options?: { multiple?: boolean }): Promise<any[]>
9
- getProperties(): Promise<string[]>
8
+ select(properties: string[], options?: { multiple?: boolean }): Promise<any[]>
9
+ getProperties(): Promise<string[]>
10
10
  }
11
11
 
12
12
  const picker = (): ContactPicker | null => {
13
- const nav = (globalThis as any).navigator
14
- return typeof nav?.contacts?.select === 'function' ? (nav.contacts as ContactPicker) : null
13
+ const nav = (globalThis as any).navigator
14
+
15
+ return typeof nav?.contacts?.select === 'function' ? (nav.contacts as ContactPicker) : null
15
16
  }
16
17
 
17
18
  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
- }
19
+ return {
20
+ id: '',
21
+ name: Array.isArray(native?.name) ? native.name.join(' ') : (native?.name ?? ''),
22
+ emails: (native?.email ?? []).map((e: string) => ({ email: e })),
23
+ phoneNumbers: (native?.tel ?? []).map((t: string) => ({ number: t })),
24
+ }
24
25
  }
25
26
 
26
27
  const unsupported = (what: string) => () =>
27
- Promise.reject(new Error(`unsupported: contact ${what} is not available through the web Contact Picker`))
28
+ Promise.reject(
29
+ new Error(`unsupported: contact ${what} is not available through the web Contact Picker`),
30
+ )
28
31
 
32
+ /** Contacts service — system address book. */
29
33
  export const contacts: Contacts = {
30
- supported: picker() !== null,
31
-
32
- // The picker has no permission state to query — choosing contacts IS the
33
- // grant. Report granted when the API exists so apps don't gate on it.
34
- ensure(): Promise<PermissionResult> {
35
- return Promise.resolve(picker() ? 'granted' : 'unsupported')
36
- },
37
-
38
- async getAll(options?: GetContactsOptions): Promise<Contact[]> {
39
- const p = picker()
40
- if (!p) {
41
- throw new Error('unsupported: navigator.contacts.select is not available')
42
- }
43
- const selected = await p.select(['name', 'email', 'tel'], { multiple: true })
44
- return (selected ?? []).map(asContact)
45
- },
46
-
47
- getByName: unsupported('lookup'),
48
- getById: unsupported('lookup'),
49
- add: (_contact: NewContact) => unsupported('writes')(),
50
- update: (_id: string, _contact: NewContact) => unsupported('writes')(),
51
- remove: unsupported('writes'),
34
+ supported: picker() !== null,
35
+
36
+ // The picker has no permission state to query — choosing contacts IS the
37
+ // grant. Report granted when the API exists so apps don't gate on it.
38
+ ensure(): Promise<PermissionResult> {
39
+ return Promise.resolve(picker() ? 'granted' : 'unsupported')
40
+ },
41
+
42
+ async getAll(options?: GetContactsOptions): Promise<Contact[]> {
43
+ const p = picker()
44
+
45
+ if (!p) {
46
+ throw new Error('unsupported: navigator.contacts.select is not available')
47
+ }
48
+
49
+ const selected = await p.select(['name', 'email', 'tel'], { multiple: true })
50
+
51
+ return (selected ?? []).map(asContact)
52
+ },
53
+
54
+ getByName: unsupported('lookup'),
55
+ getById: unsupported('lookup'),
56
+ add: (_contact: NewContact) => unsupported('writes')(),
57
+ update: (_id: string, _contact: NewContact) => unsupported('writes')(),
58
+ remove: unsupported('writes'),
52
59
  }
53
60
 
54
61
  const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
62
+
55
63
  permissionOwners.contacts = () => contacts.ensure()
@@ -2,18 +2,21 @@
2
2
  // unsupported rather than breaking the import graph.
3
3
  import type { Contacts, PermissionResult } from './types'
4
4
 
5
- const unsupported = () => Promise.reject(new Error('unsupported: contacts is not available on windows'))
5
+ const unsupported = () =>
6
+ Promise.reject(new Error('unsupported: contacts is not available on windows'))
6
7
 
8
+ /** Contacts service — system address book. */
7
9
  export const contacts: Contacts = {
8
- supported: false,
9
- ensure: async (): Promise<PermissionResult> => 'unsupported',
10
- getAll: unsupported,
11
- getByName: unsupported,
12
- getById: unsupported,
13
- add: unsupported,
14
- update: unsupported,
15
- remove: unsupported,
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,
16
18
  }
17
19
 
18
20
  const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
21
+
19
22
  permissionOwners.contacts = () => contacts.ensure()