@superrouteca/sindoor-react-native 0.0.0-stage → 0.1.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.
@@ -0,0 +1,339 @@
1
+ import CoreLocation
2
+ import Foundation
3
+ import SIndoor
4
+
5
+ /// The `Sindoor` TurboModule's work on iOS, over the sIndoor iOS SDK (Swift package product `SIndoor`): sites and
6
+ /// locators as handles, JSON in and out, every error answered as `{"error": {code, message, refs}}` (never thrown),
7
+ /// the phone's sensors and beacons feeding a locator with estimates and problems told through the two callbacks.
8
+ /// Nothing here asks for a permission. Called by RNSindoor.mm.
9
+ @objc(RNSindoorBridge)
10
+ public final class RNSindoorBridge: NSObject {
11
+ private let lock = NSLock()
12
+ private var next: Int64 = 0
13
+ private var sites: [Int64: SindoorSite] = [:]
14
+ private var locators: [Int64: SindoorLocator] = [:]
15
+ #if os(iOS)
16
+ private var sensors: [Int64: SindoorSensors] = [:]
17
+ private var beacons: [Int64: SindoorBeacons] = [:]
18
+ #endif
19
+ private let emitEstimate: (Double, String) -> Void
20
+ private let emitError: (Double, String, String, String) -> Void
21
+
22
+ @objc public init(emitEstimate: @escaping (Double, String) -> Void,
23
+ emitError: @escaping (Double, String, String, String) -> Void) {
24
+ self.emitEstimate = emitEstimate
25
+ self.emitError = emitError
26
+ super.init()
27
+ }
28
+
29
+ // MARK: - JSON and errors
30
+
31
+ /// JSON text of an answer. JSONSerialization raises (an Objective-C exception) on what is not JSON, so containers
32
+ /// are checked first.
33
+ private static func text(_ v: Any) -> String {
34
+ let fragment = v is NSNull || v is String || v is NSNumber
35
+ guard fragment || JSONSerialization.isValidJSONObject(v),
36
+ let d = try? JSONSerialization.data(withJSONObject: v, options: [.fragmentsAllowed]),
37
+ let s = String(data: d, encoding: .utf8) else {
38
+ return #"{"error":{"code":"bad_answer","message":"the engine answered something that is not JSON","refs":[]}}"#
39
+ }
40
+ return s
41
+ }
42
+
43
+ private static func value(_ json: String) throws -> Any {
44
+ guard let d = json.data(using: .utf8),
45
+ let v = try? JSONSerialization.jsonObject(with: d, options: [.fragmentsAllowed]) else {
46
+ throw SindoorError("bad_request", "not JSON")
47
+ }
48
+ return v
49
+ }
50
+
51
+ private static func object(_ json: String) throws -> [String: Any] {
52
+ if json.trimmingCharacters(in: .whitespaces).isEmpty { return [:] }
53
+ guard let o = try value(json) as? [String: Any] else { throw SindoorError("bad_request", "expected a JSON object") }
54
+ return o
55
+ }
56
+
57
+ private static func error(_ code: String, _ message: String, refs: [String] = []) -> String {
58
+ text(["error": ["code": code, "message": message.isEmpty ? code : message, "refs": refs]])
59
+ }
60
+
61
+ /// Runs an engine call; any failure becomes the error envelope.
62
+ private func answer(_ body: () throws -> Any) -> String {
63
+ do {
64
+ let v = try body()
65
+ if let s = v as? RawJSON { return s.text }
66
+ return Self.text(v)
67
+ } catch let e as SindoorError {
68
+ return Self.error(e.code, e.message, refs: e.refs)
69
+ } catch {
70
+ return Self.error("error", error.localizedDescription)
71
+ }
72
+ }
73
+
74
+ /// Text that is already JSON.
75
+ private struct RawJSON { let text: String }
76
+
77
+ private func keep(_ s: SindoorSite) -> [String: Any] {
78
+ lock.lock()
79
+ defer { lock.unlock() }
80
+ next += 1
81
+ sites[next] = s
82
+ return ["handle": next]
83
+ }
84
+
85
+ private func site(_ h: Double) throws -> SindoorSite {
86
+ lock.lock()
87
+ defer { lock.unlock() }
88
+ guard let s = sites[Int64(h)] else { throw SindoorError("disposed", "no site \(Int64(h)) (disposed?)") }
89
+ return s
90
+ }
91
+
92
+ private func locator(_ h: Double) throws -> SindoorLocator {
93
+ lock.lock()
94
+ defer { lock.unlock() }
95
+ guard let l = locators[Int64(h)] else { throw SindoorError("disposed", "no locator \(Int64(h)) (disposed?)") }
96
+ return l
97
+ }
98
+
99
+ /// A route end as the TypeScript side sends it: a ref, or `{level?, x, y}` in millimetres.
100
+ private static func place(_ v: Any?) throws -> SindoorPlace {
101
+ if let s = v as? String { return .ref(s) }
102
+ if let o = v as? [String: Any], let x = (o["x"] as? NSNumber)?.doubleValue, let y = (o["y"] as? NSNumber)?.doubleValue {
103
+ return .point(level: o["level"] as? String, x: x, y: y)
104
+ }
105
+ throw SindoorError("bad_request", "a route end is a ref or {level, x, y}")
106
+ }
107
+
108
+ // MARK: - Sites
109
+
110
+ @objc public func version() -> String {
111
+ answer { ["engine": SindoorSite.engineVersion, "sdk": "0.1.0"] }
112
+ }
113
+
114
+ @objc public func loadSite(_ options: String, done: @escaping (String) -> Void) {
115
+ Task.detached(priority: .userInitiated) { [weak self] in
116
+ guard let self else { return }
117
+ do {
118
+ let o = try Self.object(options)
119
+ guard let id = o["site"] as? String, !id.isEmpty else { throw SindoorError("no_site", "pass the site id") }
120
+ var base = SindoorClient.defaultBaseURL
121
+ if let b = o["baseUrl"] as? String, !b.isEmpty, let u = URL(string: b) { base = u }
122
+ let client = SindoorClient(key: o["key"] as? String, token: o["token"] as? String, baseURL: base)
123
+ let form = SindoorClient.Form(rawValue: (o["form"] as? String) ?? "customer") ?? .customer
124
+ let s = try await SindoorSite.load(site: id, client: client, form: form)
125
+ done(Self.text(self.keep(s)))
126
+ } catch let e as SindoorError {
127
+ done(Self.error(e.code, e.message, refs: e.refs))
128
+ } catch {
129
+ done(Self.error("error", error.localizedDescription))
130
+ }
131
+ }
132
+ }
133
+
134
+ @objc public func siteFromDownload(_ download: String, done: @escaping (String) -> Void) {
135
+ DispatchQueue.global(qos: .userInitiated).async { [weak self] in
136
+ guard let self else { return }
137
+ done(self.answer { self.keep(try SindoorSite.fromDownload(Data(download.utf8))) })
138
+ }
139
+ }
140
+
141
+ @objc public func siteDownload(_ h: Double) -> String {
142
+ answer { RawJSON(text: String(data: try site(h).download.data, encoding: .utf8) ?? "null") }
143
+ }
144
+
145
+ @objc public func siteFree(_ h: Double) {
146
+ lock.lock()
147
+ let s = sites.removeValue(forKey: Int64(h))
148
+ lock.unlock()
149
+ s?.dispose()
150
+ }
151
+
152
+ @objc public func siteRoute(_ h: Double, request: String) -> String {
153
+ answer {
154
+ var r = try Self.object(request)
155
+ let from = try Self.place(r.removeValue(forKey: "from"))
156
+ let to = try Self.place(r.removeValue(forKey: "to"))
157
+ let role = r.removeValue(forKey: "role") as? String
158
+ let profile = r.removeValue(forKey: "profile") as? String
159
+ // `at` in Unix seconds, as the engine and the JS SDK take it.
160
+ let at = (r.removeValue(forKey: "at") as? NSNumber).map { Date(timeIntervalSince1970: $0.doubleValue) }
161
+ return try site(h).route(from: from, to: to, role: role, profile: profile, at: at, options: r).json
162
+ }
163
+ }
164
+
165
+ @objc public func siteTour(_ h: Double, request: String) -> String {
166
+ answer { try site(h).tour(try Self.object(request)) }
167
+ }
168
+
169
+ @objc public func siteApproach(_ h: Double, request: String) -> String {
170
+ answer { try site(h).approach(try Self.object(request)) }
171
+ }
172
+
173
+ @objc public func siteLevels(_ h: Double) -> String {
174
+ answer { try site(h).levels() }
175
+ }
176
+
177
+ @objc public func siteLayer(_ h: Double) -> String {
178
+ answer { try site(h).layer() }
179
+ }
180
+
181
+ @objc public func toLngLat(_ h: Double, level: String, x: Double, y: Double) -> String {
182
+ answer {
183
+ let c = try site(h).toCoordinate(level: level, x: x, y: y)
184
+ return [c.longitude, c.latitude]
185
+ }
186
+ }
187
+
188
+ @objc public func fromLngLat(_ h: Double, level: String, lng: Double, lat: Double) -> String {
189
+ answer {
190
+ let p = try site(h).fromCoordinate(level: level, CLLocationCoordinate2D(latitude: lat, longitude: lng))
191
+ return ["level": p.level, "x": p.x, "y": p.y] as [String: Any]
192
+ }
193
+ }
194
+
195
+ // MARK: - Locators
196
+
197
+ @objc public func locatorNew(_ h: Double, config: String) -> String {
198
+ answer {
199
+ let l = try site(h).locator(config: try Self.object(config))
200
+ lock.lock()
201
+ defer { lock.unlock() }
202
+ next += 1
203
+ locators[next] = l
204
+ return ["handle": next]
205
+ }
206
+ }
207
+
208
+ @objc public func locatorObserve(_ h: Double, observations: String) -> String {
209
+ answer {
210
+ let l = try locator(h)
211
+ let v = try Self.value(observations)
212
+ let e: SindoorEstimate?
213
+ if let list = v as? [[String: Any]] {
214
+ e = try l.observe(list)
215
+ } else if let one = v as? [String: Any] {
216
+ e = try l.observe(one)
217
+ } else {
218
+ throw SindoorError("bad_request", "an observation is an object or a list of them")
219
+ }
220
+ return e?.json ?? NSNull()
221
+ }
222
+ }
223
+
224
+ @objc public func locatorState(_ h: Double) -> String {
225
+ answer { try locator(h).state() }
226
+ }
227
+
228
+ @objc public func locatorSetCalibration(_ h: Double, calibration: String) -> String {
229
+ answer {
230
+ // null drops the calibration: the engine takes an empty one the same way.
231
+ let c = (try? Self.value(calibration)) as? [String: Any] ?? [:]
232
+ return try locator(h).setCalibration(c)
233
+ }
234
+ }
235
+
236
+ @objc public func locatorFree(_ h: Double) {
237
+ stopFeeds(Int64(h))
238
+ lock.lock()
239
+ let l = locators.removeValue(forKey: Int64(h))
240
+ lock.unlock()
241
+ l?.dispose()
242
+ }
243
+
244
+ // MARK: - Sensors and beacons (iOS)
245
+
246
+ private func told(_ h: Int64, _ source: String) -> (SindoorError) -> Void {
247
+ { [weak self] e in self?.emitError(Double(h), source, e.code, e.message) }
248
+ }
249
+
250
+ private func estimates(_ h: Int64) -> (SindoorEstimate) -> Void {
251
+ { [weak self] e in self?.emitEstimate(Double(h), Self.text(e.json)) }
252
+ }
253
+
254
+ @objc public func startSensors(_ h: Double) -> String {
255
+ answer {
256
+ let l = try locator(h)
257
+ #if os(iOS)
258
+ let key = Int64(h)
259
+ DispatchQueue.main.async { [weak self] in
260
+ guard let self else { return }
261
+ self.lock.lock()
262
+ let s = self.sensors[key] ?? SindoorSensors()
263
+ self.sensors[key] = s
264
+ self.lock.unlock()
265
+ s.onError = self.told(key, "sensors")
266
+ s.start(feeding: l, onEstimate: self.estimates(key))
267
+ }
268
+ return ["status": "started"]
269
+ #else
270
+ _ = l
271
+ return ["status": "unavailable"]
272
+ #endif
273
+ }
274
+ }
275
+
276
+ @objc public func stopSensors(_ h: Double) {
277
+ #if os(iOS)
278
+ lock.lock()
279
+ let s = sensors.removeValue(forKey: Int64(h))
280
+ lock.unlock()
281
+ if let s { DispatchQueue.main.async { s.stop() } }
282
+ #endif
283
+ }
284
+
285
+ @objc public func startBeacons(_ h: Double, uuids: String) -> String {
286
+ answer {
287
+ let l = try locator(h)
288
+ #if os(iOS)
289
+ let key = Int64(h)
290
+ let wanted = ((try? Self.value(uuids)) as? [Any] ?? []).map { "\($0)".lowercased() }
291
+ // Empty: the site's own beacons (its iBeacon UUIDs, Eddystone when it has any).
292
+ let b = wanted.isEmpty ? try SindoorBeacons(site: l.site) : SindoorBeacons(uuids: wanted)
293
+ stopBeacons(h)
294
+ lock.lock()
295
+ beacons[key] = b
296
+ lock.unlock()
297
+ b.onError = told(key, "beacons")
298
+ DispatchQueue.main.async { [weak self] in
299
+ guard let self else { return }
300
+ b.start(feeding: l, onEstimate: self.estimates(key))
301
+ }
302
+ // Ranging waits for location When In Use; the SDK starts by itself once the app has it.
303
+ return ["status": SindoorBeacons.locationAuthorized ? "started" : "permission_missing"]
304
+ #else
305
+ _ = l
306
+ return ["status": "not_supported"]
307
+ #endif
308
+ }
309
+ }
310
+
311
+ @objc public func stopBeacons(_ h: Double) {
312
+ #if os(iOS)
313
+ lock.lock()
314
+ let b = beacons.removeValue(forKey: Int64(h))
315
+ lock.unlock()
316
+ if let b { DispatchQueue.main.async { b.stop() } }
317
+ #endif
318
+ }
319
+
320
+ private func stopFeeds(_ h: Int64) {
321
+ stopSensors(Double(h))
322
+ stopBeacons(Double(h))
323
+ }
324
+
325
+ /// The module goes away (a reload): everything stops and is freed.
326
+ @objc public func invalidate() {
327
+ lock.lock()
328
+ let ls = locators
329
+ let ss = sites
330
+ locators = [:]
331
+ sites = [:]
332
+ lock.unlock()
333
+ for (h, l) in ls {
334
+ stopFeeds(h)
335
+ l.dispose()
336
+ }
337
+ for s in ss.values { s.dispose() }
338
+ }
339
+ }
@@ -0,0 +1,48 @@
1
+ # CocoaPods helpers of @superrouteca/sindoor-react-native.
2
+ #
3
+ # The sIndoor iOS SDK is a Swift package (product `SIndoor`: the engine as a static xcframework, the Open Platform
4
+ # client, the phone's sensors and BLE beacons). The pod gets it through React Native's spm_dependency.
5
+ #
6
+ # Which package is used:
7
+ # * DEVELOPMENT: SINDOOR_IOS_PACKAGE_PATH (a checkout's sdk/apple) when set; else, inside the sIndoor repository, the
8
+ # package next to this one (sdk/apple). Build its engine first: sdk/apple/scripts/build-sdk-apple.sh (the
9
+ # xcframework is not committed). That package also names a local smap-sdk checkout for its SIndoorMap product
10
+ # (SMAP_SDK_PATH, see sdk/apple/Package.swift); this pod takes only SIndoor.
11
+ # * RELEASE: this release of the binary package Goodneo-Solutions/sindoor-releases.
12
+ # TODO(release): confirm the repository URL and that its tag equals this package's version.
13
+ require "json"
14
+
15
+ module SindoorReactNative
16
+ REMOTE = "https://github.com/Goodneo-Solutions/sindoor-releases.git".freeze
17
+ PRODUCT = "SIndoor".freeze
18
+
19
+ def self.package_root
20
+ File.realpath(File.join(__dir__, ".."))
21
+ end
22
+
23
+ def self.version
24
+ JSON.parse(File.read(File.join(package_root, "package.json")))["version"]
25
+ end
26
+
27
+ # The local Swift package directory, or nil for the published one.
28
+ def self.local_sdk
29
+ env = ENV["SINDOOR_IOS_PACKAGE_PATH"]
30
+ return File.expand_path(env) if env && !env.empty?
31
+ dir = File.expand_path(File.join(package_root, "..", "apple"))
32
+ manifest = File.join(dir, "Package.swift")
33
+ File.exist?(manifest) && File.read(manifest).include?(".library(name: \"#{PRODUCT}\"") ? dir : nil
34
+ end
35
+
36
+ # Called by the podspec.
37
+ def self.add_to_pod(spec)
38
+ local = local_sdk
39
+ if local
40
+ unless File.directory?(File.join(local, "Frameworks", "SindoorFFI.xcframework"))
41
+ Pod::UI.warn "[sIndoor] #{local}/Frameworks/SindoorFFI.xcframework is missing: run scripts/build-sdk-apple.sh there first"
42
+ end
43
+ spm_dependency(spec, url: local, requirement: {}, products: [PRODUCT])
44
+ else
45
+ spm_dependency(spec, url: REMOTE, requirement: { kind: "exactVersion", version: version }, products: [PRODUCT])
46
+ end
47
+ end
48
+ end
package/package.json CHANGED
@@ -1,6 +1,87 @@
1
1
  {
2
2
  "name": "@superrouteca/sindoor-react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "sIndoor for React Native: indoor routes, tours and positioning on the device over the sIndoor Android and iOS SDKs, phone sensors and BLE beacons, and a navigation screen on sMap maps.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "author": "Superroute Inc.",
7
+ "homepage": "https://open.superroute.ca/developer",
8
+ "keywords": [
9
+ "react-native",
10
+ "indoor",
11
+ "navigation",
12
+ "positioning",
13
+ "wayfinding",
14
+ "superroute",
15
+ "smap",
16
+ "ios",
17
+ "android"
18
+ ],
19
+ "main": "src/index.ts",
20
+ "types": "src/index.ts",
21
+ "react-native": "src/index.ts",
22
+ "source": "src/index.ts",
23
+ "files": [
24
+ "src",
25
+ "!src/__tests__",
26
+ "android/build.gradle",
27
+ "android/src",
28
+ "ios",
29
+ "SindoorReactNative.podspec",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "scripts": {
34
+ "test": "jest",
35
+ "typecheck": "tsc --noEmit",
36
+ "check:android": "scripts/check-android.sh",
37
+ "check:ios": "scripts/check-ios.sh"
38
+ },
39
+ "peerDependencies": {
40
+ "@superrouteca/smap-react-native": ">=1.6.2",
41
+ "react": ">=18",
42
+ "react-native": ">=0.81"
43
+ },
44
+ "peerDependenciesMeta": {
45
+ "@superrouteca/smap-react-native": {
46
+ "optional": true
47
+ }
48
+ },
49
+ "devDependencies": {
50
+ "@babel/core": "7.29.7",
51
+ "@react-native/babel-preset": "0.88.0",
52
+ "@react-native/jest-preset": "0.88.0",
53
+ "@types/jest": "29.5.14",
54
+ "@types/react": "19.3.0",
55
+ "@types/react-test-renderer": "19.3.0",
56
+ "jest": "29.7.0",
57
+ "react": "19.3.0",
58
+ "react-native": "0.88.0",
59
+ "react-test-renderer": "19.3.0",
60
+ "typescript": "6.0.3"
61
+ },
62
+ "jest": {
63
+ "preset": "@react-native/jest-preset",
64
+ "roots": [
65
+ "<rootDir>/src"
66
+ ],
67
+ "modulePathIgnorePatterns": [
68
+ "<rootDir>/example/"
69
+ ],
70
+ "testMatch": [
71
+ "**/__tests__/**/*.test.ts?(x)"
72
+ ]
73
+ },
74
+ "codegenConfig": {
75
+ "name": "SindoorReactNativeSpec",
76
+ "type": "modules",
77
+ "jsSrcsDir": "src",
78
+ "android": {
79
+ "javaPackageName": "ca.superroute.sindoor.reactnative"
80
+ },
81
+ "ios": {
82
+ "modulesProvider": {
83
+ "Sindoor": "RNSindoor"
84
+ }
85
+ }
86
+ }
87
+ }
@@ -0,0 +1,65 @@
1
+ // The sIndoor engine on the phone (a TurboModule, generated by the codegen from this file): the sIndoor Android SDK
2
+ // (`ca.superroute:sindoor`, the Rust core over JNI) and the iOS SDK (Swift package product `SIndoor`, the C library).
3
+ //
4
+ // Sites and locators are handles (numbers). Every answer is JSON text; an engine or platform error is answered as
5
+ // `{"error": {code, message, refs}}` (never thrown), which the TypeScript wrapper turns into a SindoorError. Engine
6
+ // calls are synchronous (they run in a few milliseconds on the device); downloading and compiling a site is not.
7
+ //
8
+ // The phone's sensors and BLE beacons feed a locator natively; each estimate is told as `sindoorEstimate` and each
9
+ // problem (a permission not granted, Bluetooth off, …) as `sindoorError`. The SDK never asks for a permission.
10
+ import { TurboModuleRegistry } from 'react-native';
11
+ import type { CodegenTypes, TurboModule } from 'react-native';
12
+
13
+ /** An estimate of a locator fed by the phone's sensors or beacons: `estimate` is its JSON (`{x, y, level, acc_mm, at, lng, lat}`). */
14
+ export type SindoorEstimateEvent = Readonly<{ locator: CodegenTypes.Double; estimate: string }>;
15
+
16
+ /** A problem of a locator's sensors or beacons (`source` `sensors` | `beacons`), as the native SDKs name it. */
17
+ export type SindoorErrorEvent = Readonly<{ locator: CodegenTypes.Double; source: string; code: string; message: string }>;
18
+
19
+ export interface Spec extends TurboModule {
20
+ readonly sindoorEstimate: CodegenTypes.EventEmitter<SindoorEstimateEvent>;
21
+ readonly sindoorError: CodegenTypes.EventEmitter<SindoorErrorEvent>;
22
+
23
+ /** `{engine, sdk}`: the engine library's version and the native SDK's. */
24
+ version(): string;
25
+
26
+ /** `{site, key?, token?, form?, baseUrl?}` → `{handle}`: downloads the site's package and compiles it on the device. */
27
+ loadSite(options: string): Promise<string>;
28
+ /** A download kept earlier (`{site?, package, overlay, live}`) → `{handle}`. */
29
+ siteFromDownload(download: string): Promise<string>;
30
+ /** The site's download as JSON text (for a cache). */
31
+ siteDownload(site: CodegenTypes.Double): string;
32
+ siteFree(site: CodegenTypes.Double): void;
33
+
34
+ /** `{from, to, role?, profile?, at?}` (each end a ref or `{level?, x, y}` in millimetres) → the route. */
35
+ siteRoute(site: CodegenTypes.Double, request: string): string;
36
+ siteTour(site: CodegenTypes.Double, request: string): string;
37
+ siteApproach(site: CodegenTypes.Double, request: string): string;
38
+ /** The levels `[{id, ordinal, …}]`. */
39
+ siteLevels(site: CodegenTypes.Double): string;
40
+ /** The indoor layer's GeoJSON — what sMap's `addIndoor` draws. */
41
+ siteLayer(site: CodegenTypes.Double): string;
42
+ /** Level millimetres → `[lng, lat]`. */
43
+ toLngLat(site: CodegenTypes.Double, level: string, x: CodegenTypes.Double, y: CodegenTypes.Double): string;
44
+ /** `[lng, lat]` on a level → `{level, x, y}` (millimetres, rounded). */
45
+ fromLngLat(site: CodegenTypes.Double, level: string, lng: CodegenTypes.Double, lat: CodegenTypes.Double): string;
46
+
47
+ /** A locator on a site → `{handle}`. */
48
+ locatorNew(site: CodegenTypes.Double, config: string): string;
49
+ /** One observation or a list → the estimate (with lng / lat), or `null` before the first fix. */
50
+ locatorObserve(locator: CodegenTypes.Double, observations: string): string;
51
+ locatorState(locator: CodegenTypes.Double): string;
52
+ locatorSetCalibration(locator: CodegenTypes.Double, calibration: string): string;
53
+ /** Frees the locator (its sensors and beacons stop). */
54
+ locatorFree(locator: CodegenTypes.Double): void;
55
+
56
+ /** Starts the phone's motion sensors feeding the locator → `{status: started | unavailable}`. */
57
+ startSensors(locator: CodegenTypes.Double): string;
58
+ stopSensors(locator: CodegenTypes.Double): void;
59
+ /** Starts BLE beacons feeding the locator; `uuids` a JSON array of iBeacon UUIDs (empty: the site's beacons on
60
+ * iOS, every beacon on Android) → `{status: started | permission_missing | bluetooth_off | not_supported, permissions?}`. */
61
+ startBeacons(locator: CodegenTypes.Double, uuids: string): string;
62
+ stopBeacons(locator: CodegenTypes.Double): void;
63
+ }
64
+
65
+ export default TurboModuleRegistry.get<Spec>('Sindoor');
package/src/client.ts ADDED
@@ -0,0 +1,91 @@
1
+ // The Open Platform's indoor routes (sIndoor DESIGN.md Part 2h, "P6 interfaces"): a site's package for the device, its
2
+ // layer, public sites, and a token for the full form (server side). Pure TypeScript over fetch — the same as
3
+ // @superrouteca/sindoor's SindoorClient; no native code.
4
+ import { SindoorError } from './errors';
5
+ import type { Download, IndoorLayer, PublicSite } from './types';
6
+
7
+ export const DEFAULT_BASE_URL = 'https://open.superroute.ca/v1/indoor';
8
+
9
+ type Fetch = (url: string, init: { method: string; headers: Record<string, string>; body?: string }) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>;
10
+
11
+ export interface ClientOptions {
12
+ /** An sMap map key (smk_…): the customer form of the account's own and public sites. */
13
+ key?: string;
14
+ /** An sIndoor token (si1.…) from your server's POST /v1/indoor/token: the full form. */
15
+ token?: string;
16
+ /** An Open Platform server key — only on a server, never in an app. */
17
+ apiKey?: string;
18
+ baseUrl?: string;
19
+ fetch?: Fetch;
20
+ }
21
+
22
+ export class SindoorClient {
23
+ readonly key?: string;
24
+ readonly token?: string;
25
+ readonly apiKey?: string;
26
+ readonly baseUrl: string;
27
+ private readonly fetch: Fetch;
28
+
29
+ constructor(o: ClientOptions = {}) {
30
+ this.key = o.key;
31
+ this.token = o.token;
32
+ this.apiKey = o.apiKey;
33
+ this.baseUrl = (o.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '');
34
+ const f = o.fetch || (typeof globalThis.fetch === 'function' ? (globalThis.fetch.bind(globalThis) as unknown as Fetch) : undefined);
35
+ if (!f) throw new SindoorError('no_fetch', 'no fetch available: pass options.fetch');
36
+ this.fetch = f;
37
+ }
38
+
39
+ headers(): Record<string, string> {
40
+ const h: Record<string, string> = { Accept: 'application/json' };
41
+ const bearer = this.token || this.apiKey;
42
+ if (bearer) h.Authorization = `Bearer ${bearer}`;
43
+ if (this.key) h['X-SMap-Key'] = this.key;
44
+ return h;
45
+ }
46
+
47
+ url(path: string, query?: Record<string, unknown>): string {
48
+ // React Native's URL has no writable searchParams on every engine: the query is built by hand.
49
+ const q: string[] = [];
50
+ if (this.key && !this.token) q.push(`key=${encodeURIComponent(this.key)}`);
51
+ for (const [k, v] of Object.entries(query || {})) {
52
+ if (v !== undefined && v !== null) q.push(`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
53
+ }
54
+ return this.baseUrl + path + (q.length ? `?${q.join('&')}` : '');
55
+ }
56
+
57
+ async request<T = any>(method: string, path: string, { query, body }: { query?: Record<string, unknown>; body?: unknown } = {}): Promise<T> {
58
+ const headers = this.headers();
59
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
60
+ const r = await this.fetch(this.url(path, query), { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
61
+ let v: any = null;
62
+ try {
63
+ v = await r.json();
64
+ } catch {
65
+ v = null;
66
+ }
67
+ if (!r.ok) {
68
+ const e = v?.error || {};
69
+ throw new SindoorError(e.code || `http_${r.status}`, e.message || `HTTP ${r.status}`, e.refs || []);
70
+ }
71
+ return v as T;
72
+ }
73
+
74
+ /** `{site, package, overlay: {revision, overlay}, live}` — the form the credentials allow (customer by default). */
75
+ package(site: string, form: 'customer' | 'full' = 'customer'): Promise<Download> {
76
+ return this.request('GET', `/sites/${encodeURIComponent(site)}/package`, { query: { form } });
77
+ }
78
+
79
+ layer(site: string): Promise<IndoorLayer> {
80
+ return this.request('GET', `/sites/${encodeURIComponent(site)}/layer`);
81
+ }
82
+
83
+ publicSites(bbox: [number, number, number, number]): Promise<PublicSite[]> {
84
+ return this.request('GET', '/public-sites', { query: { bbox: bbox.join(',') } });
85
+ }
86
+
87
+ /** Server side only (an Open Platform key): a short-lived token for the full form of a site. */
88
+ issueToken(site: string, { form = 'full', subject, ttlS }: { form?: 'customer' | 'full'; subject?: string; ttlS?: number } = {}): Promise<{ token: string; expires_at: number }> {
89
+ return this.request('POST', '/token', { body: { site, form, subject, ttl_s: ttlS } });
90
+ }
91
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,29 @@
1
+ // Errors of the engine, the native SDKs and the Open Platform: a stable `code` (`invalid_site`, `unknown_point`,
2
+ // `site_not_found`, `http_<status>`, `permission_missing`, …) and the refs concerned — as @superrouteca/sindoor.
3
+
4
+ export class SindoorError extends Error {
5
+ code: string;
6
+ refs: string[];
7
+
8
+ constructor(code: string, message?: string, refs: string[] = []) {
9
+ super(message || code);
10
+ this.name = 'SindoorError';
11
+ this.code = code;
12
+ this.refs = refs;
13
+ }
14
+ }
15
+
16
+ /** Parse an answer of the native module; `{error}` becomes a SindoorError. */
17
+ export function parse<T = any>(json: string | null | undefined): T {
18
+ if (json === null || json === undefined || json === '') return null as T;
19
+ let v: any;
20
+ try {
21
+ v = JSON.parse(json);
22
+ } catch {
23
+ throw new SindoorError('bad_answer', 'the native module answered something that is not JSON');
24
+ }
25
+ if (v && typeof v === 'object' && !Array.isArray(v) && v.error && typeof v.error === 'object') {
26
+ throw new SindoorError(v.error.code || 'error', v.error.message || '', Array.isArray(v.error.refs) ? v.error.refs.map(String) : []);
27
+ }
28
+ return v as T;
29
+ }