@sagepilot-ai/react-native-events-addon 0.0.0-stage → 0.5.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,250 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <React/RCTInvalidating.h>
3
+ #import <UIKit/UIKit.h>
4
+ #import <objc/runtime.h>
5
+ #import <stdatomic.h>
6
+ #import "SagepilotEventsCore.h"
7
+ #import "SagepilotEventsHTTP.h"
8
+
9
+ @interface SagepilotEventsModule : NSObject <RCTBridgeModule, RCTInvalidating> {
10
+ atomic_ulong _pending;
11
+ atomic_ulong _dropped;
12
+ atomic_ulong _sequence;
13
+ atomic_ulong _generation;
14
+ }
15
+ @property(nonatomic, strong) dispatch_queue_t worker;
16
+ @property(atomic, copy) NSDictionary *owner;
17
+ @property(atomic) BOOL enabled;
18
+ @property(atomic) BOOL active;
19
+ @property(nonatomic, copy) NSDictionary *identity;
20
+ @property(nonatomic, copy) NSDictionary *config;
21
+ @property(nonatomic, strong) SagepilotEventsStore *store;
22
+ @property(nonatomic, copy) NSString *processId;
23
+ @property(nonatomic, strong) NSDateFormatter *clock;
24
+ @property(nonatomic) BOOL started;
25
+ @property(atomic, strong) SagepilotEventsHTTP *http;
26
+ @property(atomic, strong) NSDictionary *prepared;
27
+ @property(atomic, copy) NSString *preparedEpoch;
28
+ - (void)observeEvent:(UIEvent *)event;
29
+ - (void)observeScreen:(UIViewController *)controller;
30
+ @end
31
+
32
+ static __weak SagepilotEventsModule *SPActiveEvents;
33
+
34
+ @interface UIApplication (SagepilotEvents)
35
+ - (void)sagepilot_events_sendEvent:(UIEvent *)event;
36
+ @end
37
+ @implementation UIApplication (SagepilotEvents)
38
+ /** Snapshots raw input/ownership before host handlers can navigate or change identity, then preserves dispatch. */
39
+ - (void)sagepilot_events_sendEvent:(UIEvent *)event {
40
+ @try { [SPActiveEvents observeEvent:event]; } @catch (NSException *error) { /* Observation must not break UIKit dispatch. */ }
41
+ [self sagepilot_events_sendEvent:event];
42
+ }
43
+ @end
44
+
45
+ @interface UIViewController (SagepilotEvents)
46
+ - (void)sagepilot_events_viewDidAppear:(BOOL)animated;
47
+ @end
48
+ @implementation UIViewController (SagepilotEvents)
49
+ /** Chains native visibility callbacks without replacing the application's navigation container. */
50
+ - (void)sagepilot_events_viewDidAppear:(BOOL)animated {
51
+ [self sagepilot_events_viewDidAppear:animated];
52
+ @try { [SPActiveEvents observeScreen:self]; } @catch (NSException *error) { /* Visibility observation is optional. */ }
53
+ }
54
+ @end
55
+
56
+ @implementation SagepilotEventsModule
57
+ RCT_EXPORT_MODULE(SagepilotEventsAddon)
58
+
59
+ /** Creates a background worker without touching UIKit or starting collection. */
60
+ - (instancetype)init {
61
+ if (!(self = [super init])) return nil;
62
+ _worker = dispatch_queue_create("ai.sagepilot.app-events", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0));
63
+ _processId = NSUUID.UUID.UUIDString.lowercaseString;
64
+ _clock = [NSDateFormatter new]; _clock.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
65
+ _clock.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; _clock.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
66
+ atomic_init(&_pending, 0); atomic_init(&_dropped, 0); atomic_init(&_sequence, 0); atomic_init(&_generation, 0);
67
+ return self;
68
+ }
69
+ /** All exported file/projection/compression methods run off the JS and main threads. */
70
+ - (dispatch_queue_t)methodQueue { return self.worker; }
71
+ /** Initialization does not require UIKit access. */
72
+ + (BOOL)requiresMainQueueSetup { return NO; }
73
+
74
+ /** Starts only explicitly permitted collection, using app-private, backup-excluded storage. */
75
+ RCT_REMAP_METHOD(configure, configure:(NSDictionary *)config resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
76
+ @try {
77
+ if (self.active) [NSException raise:@"SagepilotEvents" format:@"Only one app-event collector may run"];
78
+ self.identity = nil; self.owner = nil;
79
+ self.prepared = nil; self.preparedEpoch = nil; if (!self.http) self.http = [SagepilotEventsHTTP new];
80
+ NSURL *root = [NSFileManager.defaultManager URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
81
+ NSURL *directory = [root URLByAppendingPathComponent:@"SagepilotAppEvents" isDirectory:YES];
82
+ NSString *scope = config[@"sdk_installation_id"] ? [@"sdk:" stringByAppendingString:config[@"sdk_installation_id"]] : config[@"channel_id"];
83
+ self.store = [[SagepilotEventsStore alloc] initWithDirectory:directory.path scope:[SagepilotEventsStore scopeForWorkspace:config[@"workspace_id"] channel:scope]];
84
+ [directory setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
85
+ self.config = config; self.enabled = [config[@"enabled"] boolValue]; self.active = YES; self.started = NO;
86
+ atomic_fetch_add(&_generation, 1);
87
+ if (!self.enabled) [self.store clear];
88
+ dispatch_async(dispatch_get_main_queue(), ^{ [self attach]; });
89
+ resolve(nil);
90
+ } @catch(NSException *error) { reject(@"app_events", @"Could not initialize app observations", nil); }
91
+ }
92
+
93
+ /** Applies verified ownership and preserves its epoch across same-owner restarts. */
94
+ RCT_REMAP_METHOD(setIdentity, setIdentity:(NSDictionary *)identity resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
95
+ @try {
96
+ self.owner = nil;
97
+ self.prepared = nil; self.preparedEpoch = nil; [self.http cancel];
98
+ self.identity = [identity isKindOfClass:NSDictionary.class] ? identity : nil;
99
+ self.owner = [self.store owner:self.identity];
100
+ if (self.owner && self.enabled && !self.started) {
101
+ self.started = YES; [self enqueue:@"lifecycle" data:@{@"state":@"collector_started"} time:NSDate.date.timeIntervalSince1970 * 1000];
102
+ dispatch_async(dispatch_get_main_queue(), ^{
103
+ for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) if ([scene isKindOfClass:UIWindowScene.class]) {
104
+ for (UIWindow *window in ((UIWindowScene *)scene).windows) if (window.isKeyWindow && window.rootViewController) {
105
+ [self enqueue:@"screen" data:@{@"screen_class":NSStringFromClass(window.rootViewController.class),@"state":@"observed_at_start"} time:NSDate.date.timeIntervalSince1970 * 1000];
106
+ }
107
+ }
108
+ });
109
+ }
110
+ resolve(self.enabled ? self.owner[@"identity_epoch"] : nil);
111
+ } @catch(NSException *error) { self.owner = nil; reject(@"app_events", @"Could not establish capture ownership", nil); }
112
+ }
113
+
114
+ /** Clears unuploaded records on consent revocation and fences every queued old-generation descriptor. */
115
+ RCT_REMAP_METHOD(setEnabled, setEnabled:(BOOL)enabled resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
116
+ self.owner = nil; self.enabled = enabled; atomic_fetch_add(&_generation, 1);
117
+ self.prepared = nil; self.preparedEpoch = nil; [self.http cancel];
118
+ @try { if (!enabled) [self.store clear]; self.owner = [self.store owner:self.identity]; resolve(enabled ? self.owner[@"identity_epoch"] : nil); }
119
+ @catch(NSException *error) { self.enabled = NO; reject(@"app_events", @"Could not change collection permission", nil); }
120
+ }
121
+
122
+ /** Projects a bounded automatic network descriptor on this worker; no raw body is ever persisted. */
123
+ - (void)observeNetworkInput:(NSDictionary *)input {
124
+ @try {
125
+ NSDictionary *owner = self.owner;
126
+ if (!self.enabled || !self.active || !owner || ![owner[@"identity_epoch"] isEqual:input[@"identity_epoch"]]) { atomic_fetch_add(&_dropped, 1); return; }
127
+ NSMutableDictionary *data = [NSMutableDictionary dictionary];
128
+ for (NSString *key in @[@"method",@"status",@"duration_ms",@"outcome",@"body_omitted",@"request_body_omitted",@"request_id",@"phase"]) if (input[key]) data[key] = input[key];
129
+ NSString *route = [SagepilotEventsProjection route:input[@"route"]];
130
+ if (!route) { atomic_fetch_add(&_dropped, 1); return; }
131
+ data[@"route"] = route; data[@"route_version"] = @2;
132
+ for (NSString *key in @[@"request_body",@"response_body"]) if ([input[key] isKindOfClass:NSString.class]) {
133
+ NSDictionary *projection = [SagepilotEventsProjection project:input[key]];
134
+ if (projection[@"omitted"]) [self.store reject];
135
+ data[[key isEqual:@"request_body"] ? @"request" : @"response"] = projection;
136
+ }
137
+ [self record:@"network" data:data time:[input[@"occurred_at_ms"] doubleValue] owner:owner sequence:atomic_fetch_add(&_sequence, 1) + 1 monotonic:NSProcessInfo.processInfo.systemUptime * 1000];
138
+ } @catch(NSException *error) { atomic_fetch_add(&_dropped, 1); }
139
+ }
140
+
141
+ /** Processes a bounded bridge batch before acknowledging the in-memory handoff. */
142
+ RCT_REMAP_METHOD(observeNetworkBatch, observeNetworkBatch:(NSArray *)inputs resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
143
+ if (inputs.count > 32) { reject(@"app_events", @"Network observation batch exceeds limit", nil); return; }
144
+ for (NSDictionary *input in inputs) [self observeNetworkInput:input];
145
+ resolve(nil);
146
+ }
147
+
148
+ /** Compresses a bounded same-owner batch without parsing the journal on JavaScript. */
149
+ RCT_REMAP_METHOD(nextBatch, nextBatch:(double)bridgeDrops resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
150
+ @try {
151
+ self.prepared = self.active && self.enabled && self.owner ? [self.store nextBatchForOwner:self.owner nativeDropped:atomic_load(&_dropped) + (isfinite(bridgeDrops) && bridgeDrops > 0 ? (NSUInteger)bridgeDrops : 0)] : nil;
152
+ self.preparedEpoch = self.owner[@"identity_epoch"];
153
+ resolve(self.prepared ? @{@"lease":self.prepared[@"lease"],@"event_ids":self.prepared[@"event_ids"]} : nil);
154
+ }
155
+ @catch(NSException *error) { reject(@"app_events", @"Could not read native batch", nil); }
156
+ }
157
+ /** Authorizes an exact current-owner lease, keeping gzip bytes and HTTP entirely native. */
158
+ RCT_REMAP_METHOD(uploadBatch, uploadBatch:(NSString *)lease endpoint:(NSString *)endpoint headers:(NSDictionary *)headers resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
159
+ if (!self.active || !self.enabled || ![lease isEqual:self.prepared[@"lease"]] || ![self.owner[@"identity_epoch"] isEqual:self.preparedEpoch]) { reject(@"app_events", @"App-event upload lease expired", nil); return; }
160
+ [self.http post:endpoint headers:headers body:self.prepared[@"gzip"] completion:^(NSDictionary *receipt, NSError *error) { if (error) reject(@"app_events_upload", @"App-event batch admission failed", error); else resolve(receipt); }];
161
+ }
162
+ /** Removes only records with explicit terminal receipts for the exact native batch lease. */
163
+ RCT_REMAP_METHOD(acknowledge, acknowledge:(NSString *)lease ids:(NSArray *)ids resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
164
+ @try { [self.store acknowledge:lease ids:ids]; resolve(nil); } @catch(NSException *error) { reject(@"app_events", @"Could not acknowledge native batch", nil); }
165
+ }
166
+ /** Returns bounded counters, including overload, without exposing queued product data to app UI. */
167
+ RCT_REMAP_METHOD(diagnostics, diagnosticsWithResolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
168
+ NSMutableDictionary *result = [self.store.diagnostics mutableCopy] ?: [@{@"pending_records":@0,@"pending_bytes":@0,@"dropped_records":@0,@"rejected_payloads":@0} mutableCopy];
169
+ result[@"dropped_records"] = @([result[@"dropped_records"] unsignedIntegerValue] + atomic_load(&_dropped));
170
+ result[@"enabled"] = @(self.enabled && self.owner != nil && self.active); result[@"worker_backlog"] = @(atomic_load(&_pending)); result[@"network_observation_supported"] = @YES; resolve(result);
171
+ }
172
+ /** Stops capture; prior persisted records remain bound to their original owner. */
173
+ RCT_REMAP_METHOD(stop, stopWithResolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { [self invalidate]; resolve(nil); }
174
+
175
+ /** Attaches passive shared observers only after initialization, without an app-delegate change. */
176
+ - (void)attach {
177
+ if (!self.active) return;
178
+ static dispatch_once_t once;
179
+ dispatch_once(&once, ^{
180
+ method_exchangeImplementations(class_getInstanceMethod(UIApplication.class, @selector(sendEvent:)), class_getInstanceMethod(UIApplication.class, @selector(sagepilot_events_sendEvent:)));
181
+ method_exchangeImplementations(class_getInstanceMethod(UIViewController.class, @selector(viewDidAppear:)), class_getInstanceMethod(UIViewController.class, @selector(sagepilot_events_viewDidAppear:)));
182
+ });
183
+ SPActiveEvents = self;
184
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(activeNotification:) name:UIApplicationDidBecomeActiveNotification object:nil];
185
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(backgroundNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil];
186
+ }
187
+ /** Captures a real foreground transition, without inferring app installation. */
188
+ - (void)activeNotification:(NSNotification *)notification { [self enqueue:@"lifecycle" data:@{@"state":@"foreground"} time:NSDate.date.timeIntervalSince1970 * 1000]; }
189
+ /** Captures a real background transition; the SDK does not request unlimited background execution. */
190
+ - (void)backgroundNotification:(NSNotification *)notification { [self enqueue:@"lifecycle" data:@{@"state":@"background"} time:NSDate.date.timeIntervalSince1970 * 1000]; }
191
+
192
+ /** Observes completed/cancelled native touches only; text, screenshots and pointer moves are excluded. */
193
+ - (void)observeEvent:(UIEvent *)event {
194
+ if (!self.active || !self.enabled || !self.owner || event.type != UIEventTypeTouches) return;
195
+ NSUInteger count = 0;
196
+ for (UITouch *touch in event.allTouches) {
197
+ if (count++ >= 8) { atomic_fetch_add(&_dropped, 1); break; }
198
+ if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled) continue;
199
+ UIView *view = touch.view;
200
+ NSMutableArray *path = [NSMutableArray array]; UIView *current = view;
201
+ for (NSUInteger depth = 0; current && depth < 8; depth++) {
202
+ CGRect frame = current.frame;
203
+ [path addObject:@{@"class":NSStringFromClass(current.class),@"native_tag":@(current.tag),@"frame":@{@"x":@(frame.origin.x),@"y":@(frame.origin.y),@"width":@(frame.size.width),@"height":@(frame.size.height)}}]; current = current.superview;
204
+ }
205
+ [self enqueue:@"interaction" data:@{@"action":touch.phase == UITouchPhaseCancelled ? @"touch_cancelled" : @"touch_ended",
206
+ @"target_class":NSStringFromClass(view.class) ?: @"unknown", @"target_path":path, @"native_tag":@(view.tag), @"tap_count":@(touch.tapCount)} time:NSDate.date.timeIntervalSince1970 * 1000];
207
+ }
208
+ }
209
+ /** Records native visibility only; nested RN routes are not fabricated from a controller class. */
210
+ - (void)observeScreen:(UIViewController *)controller {
211
+ if (controller.isViewLoaded && controller.view.window) [self enqueue:@"screen" data:@{@"screen_class":NSStringFromClass(controller.class),@"state":@"appeared"} time:NSDate.date.timeIntervalSince1970 * 1000];
212
+ }
213
+ /** Hands bounded immutable descriptors to a serial worker without synchronous disk or network work. */
214
+ - (void)enqueue:(NSString *)kind data:(NSDictionary *)data time:(NSTimeInterval)time {
215
+ NSDictionary *owner = self.owner;
216
+ if (!self.active || !self.enabled || !owner) return;
217
+ if (atomic_fetch_add(&_pending, 1) >= 128) { atomic_fetch_sub(&_pending, 1); atomic_fetch_add(&_dropped, 1); return; }
218
+ unsigned long generation = atomic_load(&_generation), sequence = atomic_fetch_add(&_sequence, 1) + 1;
219
+ NSTimeInterval monotonic = NSProcessInfo.processInfo.systemUptime * 1000;
220
+ dispatch_async(self.worker, ^{
221
+ @autoreleasepool {
222
+ @try {
223
+ if (generation != atomic_load(&self->_generation) || !self.active || !self.enabled) { atomic_fetch_add(&self->_dropped, 1); return; }
224
+ [self record:kind data:data time:time owner:owner sequence:sequence monotonic:monotonic];
225
+ } @catch(NSException *error) { atomic_fetch_add(&self->_dropped, 1); }
226
+ @finally { atomic_fetch_sub(&self->_pending, 1); }
227
+ }
228
+ });
229
+ }
230
+ /** Persists capture-time identity/time and provenance rather than rewriting them at upload. */
231
+ - (void)record:(NSString *)kind data:(NSDictionary *)data time:(NSTimeInterval)time owner:(NSDictionary *)owner sequence:(unsigned long)sequence monotonic:(NSTimeInterval)monotonic {
232
+ if (!isfinite(time)) { [self.store reject]; return; }
233
+ NSMutableDictionary *event = [@{@"event_id":[NSString stringWithFormat:@"%@-%lu", self.processId, sequence],@"kind":kind,
234
+ @"clock_source":@"device_wall",@"clock_quality":@"unverified",@"capture_generation":[NSString stringWithFormat:@"%@-%lu",self.processId,atomic_load(&_generation)],
235
+ @"occurred_at":[self.clock stringFromDate:[NSDate dateWithTimeIntervalSince1970:time / 1000]],@"monotonic_ms":@(monotonic),@"sequence":@(sequence),
236
+ @"capture_process_id":self.processId,@"installation_id":self.store.installationId,@"workspace_id":self.config[@"workspace_id"],
237
+ @"sdk_version":self.config[@"sdk_version"],@"addon_version":self.config[@"addon_version"],@"platform":@"ios",@"owner":owner,@"data":data,@"capture_gap_count":@(atomic_load(&_dropped))} mutableCopy];
238
+ if (self.config[@"sdk_installation_id"]) {
239
+ event[@"device_installation_id"] = self.store.installationId;
240
+ event[@"installation_id"] = self.config[@"sdk_installation_id"];
241
+ } else { event[@"channel_id"] = self.config[@"channel_id"]; }
242
+ [self.store append:event];
243
+ }
244
+ /** Makes global hooks inert immediately and unregisters only this collector's notifications. */
245
+ - (void)invalidate {
246
+ self.active = NO; self.enabled = NO; self.owner = nil; atomic_fetch_add(&_generation, 1);
247
+ self.prepared = nil; self.preparedEpoch = nil; [self.http invalidate]; self.http = nil;
248
+ dispatch_async(dispatch_get_main_queue(), ^{ if (SPActiveEvents == self) SPActiveEvents = nil; [NSNotificationCenter.defaultCenter removeObserver:self]; });
249
+ }
250
+ @end
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@sagepilot-ai/react-native-events-addon",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "Optional native Android/iOS automatic app observations for Sagepilot",
5
+ "license": "MIT",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.mjs",
8
+ "react-native": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/index.js"
15
+ },
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "android/build.gradle",
20
+ "android/src",
21
+ "ios",
22
+ "SagepilotEventsAddon.podspec",
23
+ "react-native.config.js",
24
+ "dist",
25
+ "README.md",
26
+ "LICENSE.md"
27
+ ],
28
+ "sideEffects": false,
29
+ "scripts": {
30
+ "build": "tsup",
31
+ "typecheck": "tsc --noEmit",
32
+ "prepublishOnly": "npm run typecheck && npm run build"
33
+ },
34
+ "peerDependencies": {
35
+ "react": ">=18",
36
+ "react-native": ">=0.81.5"
37
+ },
38
+ "devDependencies": {
39
+ "@sagepilot-ai/sdk-installation-client": "0.0.0",
40
+ "tsup": "^8.3.5",
41
+ "typescript": "^5.7.2"
42
+ }
43
+ }
@@ -0,0 +1,4 @@
1
+ module.exports = { dependency: { platforms: {
2
+ android: { sourceDir: './android', packageImportPath: 'import ai.sagepilot.events.SagepilotEventsPackage;', packageInstance: 'new SagepilotEventsPackage()' },
3
+ ios: { podspecPath: './SagepilotEventsAddon.podspec' }
4
+ } } };