@octane-xplat/geolocation 0.14.0 → 0.16.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 CHANGED
@@ -6,7 +6,8 @@ pnpm add @octane-xplat/geolocation
6
6
 
7
7
  Device geolocation behind one capability object. iOS and Android run
8
8
  `@nativescript/geolocation`; web uses `navigator.geolocation`; the macOS
9
- AppKit dev host reports `supported: false` (no CoreLocation bridge).
9
+ AppKit target uses Core Location through a package-owned native facade. Hosts
10
+ without that facade or location purpose strings report `supported: false`.
10
11
 
11
12
  ```ts
12
13
  import { geolocation } from '@octane-xplat/geolocation'
@@ -23,7 +24,74 @@ implementation exists on this target, `ensure()` resolves
23
24
  defers the prompt), and `impl` is the service once usable. Nullable
24
25
  `altitude`/`heading`/`speed` mean the platform did not report them.
25
26
 
26
- Guide: [Using device features](../../docs/platform/platform-services.md);
27
- per-target availability: [platform notes](../../docs/notes/platform-notes.md).
27
+ On iOS and Android, position failures preserve the plugin's original error;
28
+ a numeric `code` is not guaranteed. Web and macOS failures use codes 1
29
+ (denied), 2 (unavailable), and 3 (timeout). Handle an unclassified failure too:
30
+
31
+ ```ts
32
+ import { geolocation } from '@octane-xplat/geolocation'
33
+
34
+ if ((await geolocation.ensure()) === 'granted') {
35
+ try {
36
+ const position = await geolocation.impl!.getCurrentPosition()
37
+ console.log(position.latitude, position.longitude)
38
+ } catch (error) {
39
+ const code = (error as { code?: number }).code
40
+ console.log(code === undefined ? 'Location failed' : `Location failed: ${code}`)
41
+ }
42
+ }
43
+ ```
44
+
45
+ Guide: [Using device features](../../docs/platform/platform-services.md)
46
+ per-target availability: [platform notes](../../.agents/docs/notes/platform-notes.md).
28
47
  Exercised by the harness `Services` screen
29
48
  ([`packages/app/src/Services.tsrx`](../app/src/Services.tsrx)).
49
+
50
+ ## macOS host setup
51
+
52
+ The existing Xplat native build discovers this package's `platforms/macos`
53
+ sources and links CoreLocation. Add both purpose strings to the application
54
+ Info.plist before requesting permission. An unsigned command-line host without
55
+ an application bundle remains unsupported.
56
+
57
+ ```xml
58
+ <key>NSLocationUsageDescription</key>
59
+ <string>Show places near your current location.</string>
60
+ <key>NSLocationWhenInUseUsageDescription</key>
61
+ <string>Show places near your current location while you use the app.</string>
62
+ ```
63
+
64
+ Sandboxed applications also need the location entitlement in their signing
65
+ entitlements file. The application owns its purpose text and signing settings.
66
+
67
+ ```xml
68
+ <key>com.apple.security.personal-information.location</key>
69
+ <true/>
70
+ ```
71
+
72
+ Location denial or disabled system Location Services returns `denied`. A
73
+ permission request with no decision after 30 seconds returns `unsupported`
74
+ and can be retried. Position failures reject with code 1 (denied), 2
75
+ (unavailable), or 3 (timeout). Times are milliseconds; omitted timeout waits
76
+ without a deadline, and omitted maximumAge requires a fresh fix.
77
+
78
+ ```ts
79
+ import { geolocation } from '@octane-xplat/geolocation'
80
+
81
+ if ((await geolocation.ensure()) === 'granted') {
82
+ try {
83
+ const position = await geolocation.impl!.getCurrentPosition({
84
+ enableHighAccuracy: true,
85
+ timeout: 10000,
86
+ maximumAge: 5000,
87
+ })
88
+ console.log(position.latitude, position.longitude)
89
+ } catch (error) {
90
+ console.log('Location failed', (error as { code?: number }).code)
91
+ }
92
+ }
93
+ ```
94
+
95
+ Automated coverage checks native delegate cleanup and the service adapter.
96
+ Real AppKit permission prompts, signed/sandboxed delivery, and physical location
97
+ accuracy still require the manual test plan in the implementation commit.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octane-xplat/geolocation",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Device geolocation for Octane xplat — matching web + NativeScript implementations",
5
5
  "keywords": [
6
6
  "android",
@@ -22,15 +22,30 @@
22
22
  "directory": "packages/geolocation"
23
23
  },
24
24
  "files": [
25
- "src"
25
+ "src",
26
+ "platforms",
27
+ "types",
28
+ "!src/**/*.test.*",
29
+ "!src/**/*.spec.*"
26
30
  ],
27
31
  "type": "module",
28
32
  "exports": {
29
33
  ".": {
30
- "macos": "./src/index.macos.ts",
34
+ "macos": {
35
+ "types": "./types/generated/index.macos.d.ts",
36
+ "default": "./src/index.macos.ts"
37
+ },
38
+ "types": "./types/generated/index.d.ts",
31
39
  "default": "./src/index.ts"
32
40
  },
33
- "./*": "./src/*"
41
+ "./*": {
42
+ "types": "./types/generated/*.d.ts",
43
+ "default": "./src/*"
44
+ },
45
+ "./*.ts": {
46
+ "types": "./types/generated/*.d.ts",
47
+ "default": "./src/*.ts"
48
+ }
34
49
  },
35
50
  "publishConfig": {
36
51
  "access": "public"
@@ -39,9 +54,13 @@
39
54
  "@nativescript/geolocation": "9.0.0"
40
55
  },
41
56
  "devDependencies": {
42
- "@nativescript-community/octane": "0.2.4",
57
+ "@nativescript-community/octane": "0.2.5",
43
58
  "@nativescript/core": "9.1.3",
44
- "octane": "0.11.0"
59
+ "@nativescript/types": "9.1.4",
60
+ "@tsrx/typescript-plugin": "0.4.11",
61
+ "octane": "0.11.0",
62
+ "tsrx-typegen": "0.3.1",
63
+ "typescript": "5.9.3"
45
64
  },
46
65
  "peerDependencies": {
47
66
  "@nativescript-community/octane": ">=0.2.1 <1",
@@ -62,7 +81,19 @@
62
81
  "ios": "9.1.0"
63
82
  }
64
83
  },
84
+ "xplat": {
85
+ "macos": {
86
+ "frameworks": [
87
+ "Foundation",
88
+ "CoreLocation"
89
+ ]
90
+ }
91
+ },
65
92
  "scripts": {
66
- "test:packed": "node tests/packed-consumer.mjs"
93
+ "test:packed": "node tests/packed-consumer.mjs",
94
+ "test": "node --experimental-strip-types --test tests/geolocation.macos.test.ts",
95
+ "test:macos": "node tests/verify-macos.mjs && node tests/verify-host.mjs",
96
+ "typegen": "tsrx-typegen --project tsconfig.types.json",
97
+ "pack:check": "tsrx-typegen --pack-check"
67
98
  }
68
99
  }
@@ -0,0 +1,8 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ @interface XplatGeolocation : NSObject
4
+ + (BOOL)isAvailable;
5
+ + (void)ensure:(void (^)(NSString *result))completion;
6
+ + (void)position:(BOOL)highAccuracy timeout:(double)timeout maximumAge:(double)maximumAge
7
+ completion:(void (^)(NSString *positionJSON, NSInteger code, NSString *message))completion;
8
+ @end
@@ -0,0 +1,125 @@
1
+ #import "XplatGeolocation.h"
2
+ #import <CoreLocation/CoreLocation.h>
3
+
4
+ // Each operation owns its manager/delegate until completion. All access and JS
5
+ // callbacks occur on the main queue; concurrent callers cannot replace callbacks.
6
+ @interface XplatLocationRequest : NSObject <CLLocationManagerDelegate>
7
+ @property(nonatomic, strong) CLLocationManager *manager;
8
+ @property(nonatomic, copy) void (^permission)(NSString *);
9
+ @property(nonatomic, copy) void (^position)(NSString *, NSInteger, NSString *);
10
+ @property(nonatomic) BOOL finished;
11
+ @property(nonatomic) BOOL started;
12
+ @property(nonatomic) double maximumAge;
13
+ @property(nonatomic, strong) NSDate *startedAt;
14
+ - (void)authorization;
15
+ - (void)finish:(CLLocation *)location code:(NSInteger)code message:(NSString *)message;
16
+ @end
17
+
18
+ static NSMutableSet<XplatLocationRequest *> *requests;
19
+ static CLLocation *cachedLocation;
20
+
21
+ @implementation XplatLocationRequest
22
+ - (void)finish:(CLLocation *)location code:(NSInteger)code message:(NSString *)message {
23
+ if (self.finished) return;
24
+ self.finished = YES;
25
+ [self.manager stopUpdatingLocation];
26
+ self.manager.delegate = nil;
27
+ NSDictionary *value = nil;
28
+ if (location) {
29
+ cachedLocation = location;
30
+ value = @{@"latitude": @(location.coordinate.latitude), @"longitude": @(location.coordinate.longitude),
31
+ @"accuracy": @(location.horizontalAccuracy),
32
+ @"altitude": location.verticalAccuracy >= 0 ? @(location.altitude) : NSNull.null,
33
+ @"heading": location.course >= 0 ? @(location.course) : NSNull.null,
34
+ @"speed": location.speed >= 0 ? @(location.speed) : NSNull.null,
35
+ @"timestamp": @(location.timestamp.timeIntervalSince1970 * 1000)};
36
+ }
37
+ if (self.permission) self.permission(code == 0 ? @"granted" : code == 1 ? @"denied" : @"unsupported");
38
+ NSString *json = value ? [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:value options:0 error:nil] encoding:NSUTF8StringEncoding] : nil;
39
+ if (self.position) self.position(json, code, message ?: @"");
40
+ self.permission = nil;
41
+ self.position = nil;
42
+ [requests removeObject:self];
43
+ }
44
+ - (void)authorization {
45
+ if (self.finished) return;
46
+ CLAuthorizationStatus status = self.manager.authorizationStatus;
47
+ if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted ||
48
+ !CLLocationManager.locationServicesEnabled) {
49
+ [self finish:nil code:1 message:@"Location permission denied or services disabled"];
50
+ } else if (status == kCLAuthorizationStatusAuthorizedAlways) {
51
+ if (self.permission) {
52
+ [self finish:nil code:0 message:nil];
53
+ } else if (!self.started) {
54
+ self.started = YES;
55
+ double age = -cachedLocation.timestamp.timeIntervalSinceNow * 1000;
56
+ if (cachedLocation && self.maximumAge > 0 && age >= 0 && age <= self.maximumAge) {
57
+ [self finish:cachedLocation code:0 message:nil];
58
+ } else {
59
+ [self.manager startUpdatingLocation];
60
+ }
61
+ }
62
+ }
63
+ }
64
+ - (void)locationManagerDidChangeAuthorization:(CLLocationManager *)manager { [self authorization]; }
65
+ - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
66
+ CLLocation *location = locations.lastObject;
67
+ if (!location || location.horizontalAccuracy < 0) return;
68
+ double age = -location.timestamp.timeIntervalSinceNow * 1000;
69
+ // A zero maximumAge must not reuse a fix obtained before this request.
70
+ if (self.maximumAge > 0 ? age > self.maximumAge : [location.timestamp compare:self.startedAt] == NSOrderedAscending) return;
71
+ [self finish:location code:0 message:nil];
72
+ }
73
+ - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
74
+ if ([error.domain isEqualToString:kCLErrorDomain] && error.code == kCLErrorLocationUnknown) return;
75
+ NSInteger code = [error.domain isEqualToString:kCLErrorDomain] && error.code == kCLErrorDenied ? 1 : 2;
76
+ [self finish:nil code:code message:code == 1 ? @"Location permission denied" : @"Location unavailable"];
77
+ }
78
+ @end
79
+
80
+ @implementation XplatGeolocation
81
+ + (BOOL)isAvailable {
82
+ NSBundle *bundle = NSBundle.mainBundle;
83
+ NSString *purpose = [bundle objectForInfoDictionaryKey:@"NSLocationUsageDescription"];
84
+ NSString *whenInUse = [bundle objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"];
85
+ return bundle.bundleIdentifier.length > 0 && [purpose isKindOfClass:NSString.class] && purpose.length > 0 &&
86
+ [whenInUse isKindOfClass:NSString.class] && whenInUse.length > 0;
87
+ }
88
+ + (void)begin:(BOOL)high timeout:(double)timeout maximumAge:(double)maximumAge
89
+ permission:(void (^)(NSString *))permission position:(void (^)(NSString *, NSInteger, NSString *))position {
90
+ dispatch_async(dispatch_get_main_queue(), ^{
91
+ if (![self isAvailable]) {
92
+ if (permission) permission(@"unsupported");
93
+ if (position) position(nil, 2, @"Location host is not configured");
94
+ return;
95
+ }
96
+ if (!requests) requests = NSMutableSet.new;
97
+ XplatLocationRequest *request = XplatLocationRequest.new;
98
+ request.permission = permission;
99
+ request.position = position;
100
+ request.maximumAge = maximumAge;
101
+ request.startedAt = NSDate.date;
102
+ request.manager = CLLocationManager.new;
103
+ request.manager.desiredAccuracy = high ? kCLLocationAccuracyBest : kCLLocationAccuracyThreeKilometers;
104
+ [requests addObject:request];
105
+ request.manager.delegate = request;
106
+ [request authorization];
107
+ if (request.finished) return;
108
+ if (request.manager.authorizationStatus == kCLAuthorizationStatusNotDetermined) {
109
+ [request.manager requestWhenInUseAuthorization];
110
+ }
111
+ if (timeout >= 0) {
112
+ __weak XplatLocationRequest *weakRequest = request;
113
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MIN(timeout, (double)INT64_MAX / NSEC_PER_MSEC) * NSEC_PER_MSEC)),
114
+ dispatch_get_main_queue(), ^{ [weakRequest finish:nil code:3 message:@"Location request timed out"]; });
115
+ }
116
+ });
117
+ }
118
+ + (void)ensure:(void (^)(NSString *))completion {
119
+ [self begin:NO timeout:30000 maximumAge:0 permission:completion position:nil];
120
+ }
121
+ + (void)position:(BOOL)highAccuracy timeout:(double)timeout maximumAge:(double)maximumAge
122
+ completion:(void (^)(NSString *, NSInteger, NSString *))completion {
123
+ [self begin:highAccuracy timeout:timeout maximumAge:maximumAge permission:nil position:completion];
124
+ }
125
+ @end
@@ -1,8 +1,71 @@
1
- // Geolocation — AppKit host leaf. CoreLocation is not bridged on the dev host.
2
- import type { Capability, GeolocationImpl } from './types'
1
+ // Package-owned Core Location facade, loaded by the existing macOS native graph.
2
+ import type { Capability, GeolocationImpl, GeolocationPosition, PermissionResult } from './types'
3
+
4
+ declare const XplatGeolocation: {
5
+ isAvailable(): boolean
6
+ ensure(completion: (result: PermissionResult) => void): void
7
+ positionTimeoutMaximumAgeCompletion(
8
+ highAccuracy: boolean,
9
+ timeout: number,
10
+ maximumAge: number,
11
+ completion: (positionJSON: string | null, code: number, message: string) => void,
12
+ ): void
13
+ }
14
+
15
+ const available = () => typeof XplatGeolocation !== 'undefined' && XplatGeolocation.isAvailable()
16
+
17
+ const milliseconds = (value: number | undefined, fallback: number) =>
18
+ value === undefined || Number.isNaN(value) ? fallback : Math.max(0, value)
19
+
20
+ const impl: GeolocationImpl = {
21
+ getCurrentPosition(options) {
22
+ return new Promise((resolve, reject) => {
23
+ if (!available()) {
24
+ reject(Object.assign(new Error('Location host unavailable'), { code: 2 }))
25
+
26
+ return
27
+ }
28
+
29
+ const timeout = milliseconds(options?.timeout, Infinity)
30
+ XplatGeolocation.positionTimeoutMaximumAgeCompletion(
31
+ options?.enableHighAccuracy ?? false,
32
+ timeout === Infinity ? -1 : timeout,
33
+ milliseconds(options?.maximumAge, 0),
34
+ (positionJSON, code, message) => {
35
+ if (code === 0 && positionJSON) {
36
+ try {
37
+ resolve(JSON.parse(positionJSON) as GeolocationPosition)
38
+ } catch (error) {
39
+ reject(error)
40
+ }
41
+ } else {
42
+ reject(
43
+ Object.assign(new Error(message || 'Location unavailable'), {
44
+ code: code || 2,
45
+ }),
46
+ )
47
+ }
48
+ },
49
+ )
50
+ })
51
+ },
52
+ }
3
53
 
4
54
  export const geolocation: Capability<GeolocationImpl> = {
5
- supported: false,
6
- ensure: async () => 'unsupported',
7
- impl: null,
55
+ get supported() {
56
+ return available()
57
+ },
58
+ async ensure() {
59
+ if (!available()) {
60
+ return 'unsupported'
61
+ }
62
+
63
+ return new Promise<PermissionResult>((resolve) => XplatGeolocation.ensure(resolve))
64
+ },
65
+ get impl() {
66
+ return available() ? impl : null
67
+ },
8
68
  }
69
+
70
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
71
+ permissionOwners.location = () => geolocation.ensure()
@@ -5,13 +5,21 @@ import { CoreTypes } from '@nativescript/core'
5
5
  import type { Capability, GeolocationImpl, GeolocationPosition } from './types'
6
6
 
7
7
  function asPosition(nativeLocation: any): GeolocationPosition {
8
+ const android = nativeLocation.android
9
+ const ios = nativeLocation.ios
10
+ const heading = nativeLocation.direction ?? nativeLocation.heading
11
+ const speed = nativeLocation.speed
8
12
  return {
9
13
  latitude: nativeLocation.latitude,
10
14
  longitude: nativeLocation.longitude,
11
- accuracy: nativeLocation.horizontalAccuracy ?? nativeLocation.accuracy ?? 0,
12
- altitude: nativeLocation.altitude ?? null,
13
- heading: nativeLocation.direction ?? nativeLocation.heading ?? null,
14
- speed: nativeLocation.speed ?? null,
15
+ accuracy: Math.max(0, nativeLocation.horizontalAccuracy ?? nativeLocation.accuracy ?? 0),
16
+ // Altitude itself can be negative; iOS validity uses verticalAccuracy.
17
+ altitude:
18
+ (android && !android.hasAltitude()) || (ios && ios.verticalAccuracy < 0)
19
+ ? null
20
+ : (nativeLocation.altitude ?? null),
21
+ heading: (android && !android.hasBearing()) || heading == null || heading < 0 ? null : heading,
22
+ speed: (android && !android.hasSpeed()) || speed == null || speed < 0 ? null : speed,
15
23
  timestamp: Number(nativeLocation.timestamp ?? Date.now()),
16
24
  }
17
25
  }
@@ -43,7 +43,32 @@ export const geolocation: Capability<GeolocationImpl> = {
43
43
  return 'granted'
44
44
  } catch (error) {
45
45
  const code = (error as { code?: number }).code
46
- return code === 1 ? 'denied' : 'unsupported'
46
+ if (code === 1) {
47
+ return 'denied'
48
+ }
49
+
50
+ if (code === 3) {
51
+ return 'granted'
52
+ }
53
+
54
+ // POSITION_UNAVAILABLE can precede authorization (inactive document).
55
+ // Only a permission query can establish access in that case.
56
+ if (code === 2 && navigator.permissions?.query) {
57
+ try {
58
+ const permission = await navigator.permissions.query({ name: 'geolocation' })
59
+ if (permission.state === 'granted') {
60
+ return 'granted'
61
+ }
62
+
63
+ if (permission.state === 'denied') {
64
+ return 'denied'
65
+ }
66
+ } catch {
67
+ // Some browsers expose Permissions but cannot query geolocation.
68
+ }
69
+ }
70
+
71
+ return 'unsupported'
47
72
  }
48
73
  },
49
74
  impl,
@@ -0,0 +1,9 @@
1
+ // Windows leaf — @nativescript/geolocation ships no windows entry, so the
2
+ // capability reports unsupported rather than breaking the import graph.
3
+ import type { Capability, GeolocationImpl } from './types'
4
+
5
+ export const geolocation: Capability<GeolocationImpl> = {
6
+ supported: false,
7
+ ensure: async () => 'unsupported',
8
+ impl: null,
9
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": 1,
3
+ "files": [
4
+ "geolocation.d.ts",
5
+ "geolocation.macos.d.ts",
6
+ "geolocation.web.d.ts",
7
+ "geolocation.windows.d.ts",
8
+ "index.d.ts",
9
+ "index.macos.d.ts",
10
+ "types.d.ts"
11
+ ]
12
+ }
@@ -0,0 +1,2 @@
1
+ import type { Capability, GeolocationImpl } from './types.js';
2
+ export declare const geolocation: Capability<GeolocationImpl>;
@@ -0,0 +1,2 @@
1
+ import type { Capability, GeolocationImpl } from './types.js';
2
+ export declare const geolocation: Capability<GeolocationImpl>;
@@ -0,0 +1,2 @@
1
+ import type { Capability, GeolocationImpl } from './types.js';
2
+ export declare const geolocation: Capability<GeolocationImpl>;
@@ -0,0 +1,2 @@
1
+ import type { Capability, GeolocationImpl } from './types.js';
2
+ export declare const geolocation: Capability<GeolocationImpl>;
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { geolocation } from './geolocation.js';
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { geolocation } from './geolocation.macos.js';
@@ -0,0 +1,25 @@
1
+ /** Optional capability — never throws for absence (docs/platform/platform-services.md). */
2
+ export interface Capability<T> {
3
+ supported: boolean;
4
+ ensure(): Promise<'granted' | 'denied' | 'unsupported'>;
5
+ /** usable iff supported && ensured */
6
+ impl: T | null;
7
+ }
8
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported';
9
+ export interface GeolocationOptions {
10
+ enableHighAccuracy?: boolean;
11
+ timeout?: number;
12
+ maximumAge?: number;
13
+ }
14
+ export interface GeolocationPosition {
15
+ latitude: number;
16
+ longitude: number;
17
+ accuracy: number;
18
+ altitude: number | null;
19
+ heading: number | null;
20
+ speed: number | null;
21
+ timestamp: number;
22
+ }
23
+ export interface GeolocationImpl {
24
+ getCurrentPosition(options?: GeolocationOptions): Promise<GeolocationPosition>;
25
+ }