@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.
- package/LICENSE.md +21 -0
- package/README.md +138 -2
- package/SagepilotEventsAddon.podspec +16 -0
- package/android/build.gradle +8 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsHTTP.java +67 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsModule.java +96 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsPackage.java +16 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsProjection.java +190 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsRuntime.java +249 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsStore.java +173 -0
- package/dist/index.d.mts +49 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +990 -0
- package/dist/index.mjs +963 -0
- package/ios/SagepilotEventsCore.h +21 -0
- package/ios/SagepilotEventsCore.m +290 -0
- package/ios/SagepilotEventsHTTP.h +8 -0
- package/ios/SagepilotEventsHTTP.m +74 -0
- package/ios/SagepilotEventsModule.m +250 -0
- package/package.json +41 -4
- package/react-native.config.js +4 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sagepilot AI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,139 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Sagepilot React Native events add-on
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
One installation automatically collects supported app observations on Android and iOS.
|
|
4
|
+
|
|
5
|
+
The add-on bundles the shared installation client. Install it alongside your existing React Native app dependencies.
|
|
6
|
+
|
|
7
|
+
## Install and initialize
|
|
8
|
+
|
|
9
|
+
Requires RN 0.81.5+, Android API 24+, iOS 15.1+, native autolinking and a native rebuild. Install iOS pods as usual. Expo Go is unsupported; use a native development build.
|
|
10
|
+
|
|
11
|
+
Register the app in **Settings → SDK** and use its installation key and registered app ID. Supply a stable anonymous ID for the visitor.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createSagepilotInstallationEvents } from '@sagepilot-ai/react-native-events-addon';
|
|
15
|
+
|
|
16
|
+
const events = createSagepilotInstallationEvents({
|
|
17
|
+
key: 'workspace_uuid:installation_uuid',
|
|
18
|
+
anonymousId: stableAppVisitorId,
|
|
19
|
+
appId: 'com.example.app',
|
|
20
|
+
collectionEnabled: false
|
|
21
|
+
});
|
|
22
|
+
await events.start();
|
|
23
|
+
// Enable only after the app's collection permission allows it.
|
|
24
|
+
await events.setCollectionEnabled(true);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Collection defaults to off and requires permission from both the app and the installation settings. `await events.setCollectionEnabled(false)` stops capture, cancels in-flight upload and purges unuploaded records. `events.destroy()` detaches the observers and stops the installation client. Records that remain in the journal retain their original capture owner.
|
|
28
|
+
|
|
29
|
+
## Coverage
|
|
30
|
+
|
|
31
|
+
| Source | Current coverage |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| Android | Native Activity visibility/lifecycle and completed/cancelled touches in observed Activity windows. Passive callback chaining preserves host results/exceptions. |
|
|
34
|
+
| iOS | Native foreground/background, controller visibility and completed/cancelled UIKit touches. Shared method hooks chain original implementations; they do not add a gesture responder. |
|
|
35
|
+
| RN networking | Standard text XHR and the installed RN global fetch polyfill. Fetch header/body observations share a request ID. Its blob-backed JSON is observed when the app reads `Response.text/json`; the SDK never initiates a body read or clone. |
|
|
36
|
+
| Business context | Native-worker inspection of eligible JSON across industries. Versioned typed scalar fields retain original paths, array indices, numbers, booleans, nulls and bounded compact codes/enums/timestamps. No product marker or predefined event name is required. |
|
|
37
|
+
| Product hints | Additional candidates for explicit product/SKU/merchandise references or GraphQL Product/ProductVariant types; public product/money attributes remain available alongside generic context. |
|
|
38
|
+
|
|
39
|
+
A touch is not a successful cart addition or paid purchase. Native tags/classes are target hints, not verified product identifiers. Product fetches do not prove viewing. Product/variant/SKU/line references retain original field names; classification belongs to the server.
|
|
40
|
+
|
|
41
|
+
Input text, accessibility labels, screenshots, headers and cookies are excluded. Sensitive JSON subtrees are excluded before traversal. Generic string values are limited to compact ASCII codes/enums/references/timestamps up to 256 characters; free text, names, descriptions, common contact/credential formats and unsafe numbers are value-omitted. Omitted scalars retain an explicit reason, not a fabricated null. Generic URL values are omitted, with only a route fingerprint retained; explicit public product URL hints still omit queries/fragments/credentials. No arbitrary React state/store is inspected.
|
|
42
|
+
|
|
43
|
+
Filtering is conservative and heuristic, not a guarantee that every short code or number is non-sensitive. Approved app collection permission is still required. Some business fields remain unavailable by policy; enabling this SDK does not authorize exporting arbitrary personal or confidential data.
|
|
44
|
+
|
|
45
|
+
## Generic context and server grouping
|
|
46
|
+
|
|
47
|
+
Projection version 2 adds `fields` independent of the existing optional `product_candidates` hints. For example, an ordinary booking response can yield:
|
|
48
|
+
|
|
49
|
+
```json
|
|
50
|
+
{
|
|
51
|
+
"projection_version": 2,
|
|
52
|
+
"fields": [
|
|
53
|
+
{ "path": "$.booking.bookingRef", "type": "string", "value": "B-12" },
|
|
54
|
+
{ "path": "$.booking.state", "type": "string", "value": "confirmed" },
|
|
55
|
+
{ "path": "$.booking.partySize", "type": "number", "value": 2 }
|
|
56
|
+
]
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The same projection handles lesson completion, telecom plans, subscriptions or commerce; the SDK never labels these as business events. `structure` retains wildcard array paths/types, while `fields` retains actual indices so the server can keep fields from the same item together. GraphQL `operationName` and eligible `variables` fields are retained; query text is omitted. An HTTP status or boolean alone is not evidence of a completed business outcome.
|
|
61
|
+
|
|
62
|
+
Existing journal records retain their original projection and occurrence identity across retries.
|
|
63
|
+
|
|
64
|
+
Routes have no industry word allowlist. On the native worker, alphabetic operation segments become deterministic SHA-256 fingerprints, probable numeric/mixed IDs become placeholders, and API version segments remain distinct. `route_version: 2` distinguishes this representation. Raw paths exist only in bounded in-memory handoff; they never enter the file journal or upload. These are grouping hints, not exact route templates or anonymization: alphabetic IDs can still split families, mixed/numeric operation names can be ambiguous, and fingerprints can be dictionary-guessed. Server grouping must combine trusted workspace/app scope, method, operation/context and structural evidence, not the route alone. No SDK-side semantic grouping or AI is added.
|
|
65
|
+
|
|
66
|
+
Current boundaries: custom/pre-bound fetch transports, native networking, WebViews, arbitrary binary/streaming bodies, direct XHR `responseType=json` bodies and data fetched before initialization are unsupported. Fetch bodies the app never reads, or custom Response.json implementations that bypass the observed text path, remain unavailable. Callback overrides that bypass observed native/super implementations reduce coverage. Activity/controller names do not expose every RN logical route. Coexistence with other instrumentation needs device validation. Missing identifiers/outcomes stay unavailable; no brand adapter hides those gaps.
|
|
67
|
+
|
|
68
|
+
## Threads and bounds
|
|
69
|
+
|
|
70
|
+
Touch callbacks snapshot small descriptors. Projection, file writes, encoding and gzip run on a serial native worker. A separate network worker uploads prepared bytes. The installation client authorizes each lease in JavaScript and the native worker sends the compressed body directly.
|
|
71
|
+
|
|
72
|
+
Initial hard caps, subject to pilot validation:
|
|
73
|
+
|
|
74
|
+
- 128 queued native descriptors; Android also caps estimated raw bytes at 512 KiB. JS queues at most 128 network observations/512 KiB estimated bytes, then hands off one native batch of at most 32 observations/approximately 256 KiB at a time. In-flight XHR and fetch metadata each cap at 128; retained request bodies share a 128-Ki-code-unit budget. Completed fetch correlation metadata caps at 128 without retaining responses/bodies.
|
|
75
|
+
- 64 Ki UTF-16 code units per text body, depth 12 before parsing; 512 traversed nodes, 64 fields/object, 20 array entries, 128 structural descriptors, 64 scalar context entries and 20 product candidates. All projection arrays share an 11 KiB entry budget per body; keys are traversed deterministically and `limited` exposes truncation. These describe a sample, not a complete arbitrary payload.
|
|
76
|
+
- 32 KiB per sanitized occurrence, 2,048 persisted records and 10 MiB logical record bytes, excluding filesystem overhead. Oldest records are evicted at capacity; diagnostics/uploaded `capture_gaps` expose losses.
|
|
77
|
+
- 100 records/approximately 128 KiB uncompressed per native gzip batch; four batches/drain, one active upload, two-second drain timer, capped exponential retry/backoff with jitter.
|
|
78
|
+
- Bounded upload timeouts and 64 KiB receipt bytes; redirects rejected. HTTPS in production; loopback development supported.
|
|
79
|
+
|
|
80
|
+
The journal uses atomic app-private files excluded from backups, with iOS data protection. Session credentials stay in memory or in the installation client's configured storage. Collection starts after the installation session succeeds. Persisted records can be uploaded after a matching session is restored.
|
|
81
|
+
|
|
82
|
+
Hard process kills can lose descriptors before persistence. Overload, quotas, omitted inputs and identity transitions can leave gaps. Counters are process-local, not complete loss accounting across hard kills. Infinite offline time and unlimited rates are unsupported. Device throughput, battery, memory and UI overhead remain unbenchmarked.
|
|
83
|
+
|
|
84
|
+
## Time and ownership
|
|
85
|
+
|
|
86
|
+
Records preserve `event_id`, immutable `occurred_at` (UTC milliseconds), monotonic time, per-process sequence, device installation, capture owner and epoch, workspace and SDK installation scope, platform and package versions. Retries retain the original identity and time. The native installation collector uses anonymous sessions.
|
|
87
|
+
|
|
88
|
+
The journal leases records for the original session owner. A different SDK installation uses its own journal scope.
|
|
89
|
+
|
|
90
|
+
## Ingestion
|
|
91
|
+
|
|
92
|
+
The installation client calls `/platform-api/v1/sdk/sessions` for a signed installation token and the Event Handler upload URL. The native worker sends gzip batches to `/events/v1/sdk/observations` with that token. A custom JS `fetch` can serve session requests. The uploader uses native HTTP.
|
|
93
|
+
|
|
94
|
+
```json
|
|
95
|
+
{
|
|
96
|
+
"schema_version": 1,
|
|
97
|
+
"capture_gaps": { "quota_evicted": 0, "rejected_payloads": 0, "collector_dropped": 0 },
|
|
98
|
+
"observations": [{
|
|
99
|
+
"event_id": "capture-process-123-1",
|
|
100
|
+
"kind": "network",
|
|
101
|
+
"occurred_at": "2026-10-20T09:10:11.123Z",
|
|
102
|
+
"owner": { "session_id": "session-id", "customer_id": null, "identity_epoch": "capture-epoch" },
|
|
103
|
+
"data": { "method": "POST", "route_version": 2, "route": "https://app.example/:op_0123456789abcdef/:segment", "status": 200, "outcome": "completed" }
|
|
104
|
+
}]
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
The example omits other provenance. Ingestion must durably admit before returning per-record receipts:
|
|
109
|
+
|
|
110
|
+
```json
|
|
111
|
+
{ "results": [{ "event_id": "capture-process-123-1", "status": "admitted" }] }
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Only `admitted`, `duplicate`, `disabled` and `invalid` remove leased records. Retryable or missing receipts and HTTP or network failures retain them. Foreign or duplicate IDs and unknown statuses reject the receipt.
|
|
115
|
+
|
|
116
|
+
## Validation
|
|
117
|
+
|
|
118
|
+
```sh
|
|
119
|
+
npm run typecheck
|
|
120
|
+
npm run build
|
|
121
|
+
npm run test:events-addon
|
|
122
|
+
npm run test:events-native
|
|
123
|
+
npm run test:installation-events
|
|
124
|
+
npm run test:sdk-push
|
|
125
|
+
npm run test:sdk-compat
|
|
126
|
+
npm run test:release
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Native tests require JDK 17+ (`JAVA_HOME`), macOS/Clang/Foundation, full Xcode/iOS simulator SDK and installed RN headers. Use `SAGE_EVENTS_JSON_JAR`, `SAGE_EVENTS_ANDROID_JAR` and `SAGE_EVENTS_REACT_AAR`, or cached Gradle/Android artifacts. They run actual Java/Foundation cores against shared commerce, education, booking, telecom, generic context and GraphQL fixtures, plus deterministic truncation, route fingerprints, real Java HTTP failures/redirects/oversize/hangs, Android collector compilation and iOS UIKit/RN syntax checks. These are not an end-to-end RN application build or device performance evidence.
|
|
130
|
+
|
|
131
|
+
`test:events-addon` runs the installation entry point with a modeled native bridge and loopback HTTP. The stateful fixture in `postman/mocks/sdk-events` exercises session bootstrap, gzip admission and upload retries. Native core tests exercise the journal and uploader separately.
|
|
132
|
+
|
|
133
|
+
```sh
|
|
134
|
+
postman simulation run postman/simulations/sdk-events.sim.yaml --port 4917 --output ndjson --no-history
|
|
135
|
+
SAGE_EVENTS_SIM_URL=http://127.0.0.1:4917/sdk npm run test:events-addon
|
|
136
|
+
SAGE_EVENTS_SIM_URL=http://127.0.0.1:4917/sdk npm run test:events-native
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
With `SAGE_EVENTS_SIM_URL`, the native suite also runs the iOS NSURLSession uploader against the fixture and checks success, errors, redirect rejection and the response cap. All fixture credentials are synthetic.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
require 'json'
|
|
2
|
+
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
|
|
3
|
+
Pod::Spec.new do |s|
|
|
4
|
+
s.name = 'SagepilotEventsAddon'
|
|
5
|
+
s.version = package['version']
|
|
6
|
+
s.summary = package['description']
|
|
7
|
+
s.homepage = 'https://github.com/sage-pilot/sage-sdk'
|
|
8
|
+
s.license = 'MIT'
|
|
9
|
+
s.author = 'Sagepilot'
|
|
10
|
+
s.source = { :git => 'https://github.com/sage-pilot/sage-sdk.git', :tag => s.version.to_s }
|
|
11
|
+
s.platform = :ios, '15.1'
|
|
12
|
+
s.source_files = 'ios/*.{h,m}'
|
|
13
|
+
s.frameworks = 'Foundation', 'UIKit'
|
|
14
|
+
s.libraries = 'z'
|
|
15
|
+
s.dependency 'React-Core'
|
|
16
|
+
end
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
apply plugin: 'com.android.library'
|
|
2
|
+
android {
|
|
3
|
+
namespace 'ai.sagepilot.events'
|
|
4
|
+
compileSdkVersion rootProject.ext.has('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 35
|
|
5
|
+
defaultConfig { minSdkVersion 24 }
|
|
6
|
+
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
|
7
|
+
}
|
|
8
|
+
dependencies { implementation 'com.facebook.react:react-android' }
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
package ai.sagepilot.events;
|
|
2
|
+
|
|
3
|
+
import org.json.JSONObject;
|
|
4
|
+
import java.io.*;
|
|
5
|
+
import java.net.*;
|
|
6
|
+
import java.nio.charset.StandardCharsets;
|
|
7
|
+
import java.util.Map;
|
|
8
|
+
import java.util.concurrent.*;
|
|
9
|
+
import java.util.concurrent.atomic.AtomicLong;
|
|
10
|
+
|
|
11
|
+
/** Bounded native HTTP upload; credentials are per-request memory and never journaled or logged. */
|
|
12
|
+
public final class SagepilotEventsHTTP {
|
|
13
|
+
private volatile HttpURLConnection connection;
|
|
14
|
+
private final AtomicLong cancellationRevision = new AtomicLong();
|
|
15
|
+
private static final ScheduledThreadPoolExecutor deadlines = new ScheduledThreadPoolExecutor(1, runnable -> {
|
|
16
|
+
Thread thread = new Thread(runnable, "SagepilotUploadDeadline"); thread.setDaemon(true); return thread;
|
|
17
|
+
});
|
|
18
|
+
static { deadlines.setRemoveOnCancelPolicy(true); }
|
|
19
|
+
|
|
20
|
+
/** Posts a prepared gzip body without redirects, unlimited response buffering or an unbounded network wait. */
|
|
21
|
+
public JSONObject post(String endpoint, Map<String, String> headers, Callable<byte[]> loadBody) throws Exception {
|
|
22
|
+
long revision = cancellationRevision.get();
|
|
23
|
+
URL url = new URL(endpoint);
|
|
24
|
+
if (!url.getProtocol().equals("https") && !(url.getProtocol().equals("http") && (url.getHost().equals("127.0.0.1") || url.getHost().equals("localhost") || url.getHost().equals("10.0.2.2") || url.getHost().equals("[::1]")))) throw new IOException("HTTPS is required for app-event upload");
|
|
25
|
+
if (url.getUserInfo() != null) throw new IOException("Credentials are not allowed in upload URLs");
|
|
26
|
+
HttpURLConnection request = (HttpURLConnection)url.openConnection(); connection = request;
|
|
27
|
+
ScheduledFuture<?> alarm = deadlines.schedule(request::disconnect, 15, TimeUnit.SECONDS);
|
|
28
|
+
long deadline = System.nanoTime() + 15_000_000_000L;
|
|
29
|
+
try {
|
|
30
|
+
// Publish the connection before reading the owner-bound lease, so a fence can cancel the handoff.
|
|
31
|
+
byte[] body = loadBody.call();
|
|
32
|
+
checkCurrent(revision);
|
|
33
|
+
request.setConnectTimeout(5000); request.setReadTimeout(10000); request.setInstanceFollowRedirects(false); request.setRequestMethod("POST"); request.setDoOutput(true);
|
|
34
|
+
for (Map.Entry<String,String> header : headers.entrySet()) request.setRequestProperty(header.getKey(), header.getValue());
|
|
35
|
+
request.setFixedLengthStreamingMode(body.length);
|
|
36
|
+
try (OutputStream output = request.getOutputStream()) { checkCurrent(revision); output.write(body); }
|
|
37
|
+
checkCurrent(revision);
|
|
38
|
+
request.setReadTimeout(remaining(deadline));
|
|
39
|
+
int status = request.getResponseCode();
|
|
40
|
+
if (status < 200 || status >= 300) throw new IOException("App-event admission failed with HTTP " + status);
|
|
41
|
+
if (request.getContentLengthLong() > 65536) throw new IOException("App-event receipt exceeds limit");
|
|
42
|
+
try (InputStream input = request.getInputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
|
|
43
|
+
byte[] buffer = new byte[4096]; int length;
|
|
44
|
+
while (true) {
|
|
45
|
+
request.setReadTimeout(remaining(deadline)); length = input.read(buffer); if (length == -1) break;
|
|
46
|
+
if (output.size() + length > 65536) throw new IOException("App-event receipt exceeds limit"); output.write(buffer, 0, length);
|
|
47
|
+
}
|
|
48
|
+
return new JSONObject(new String(output.toByteArray(), StandardCharsets.UTF_8));
|
|
49
|
+
}
|
|
50
|
+
} finally { alarm.cancel(false); request.disconnect(); if (connection == request) connection = null; }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Rejects a cancellation even if disconnect ran before the connection opened its socket. */
|
|
54
|
+
private void checkCurrent(long revision) throws IOException {
|
|
55
|
+
if (revision != cancellationRevision.get()) throw new IOException("App-event admission was cancelled");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Recalculates a total read deadline so trickle responses cannot keep a lease alive indefinitely. */
|
|
59
|
+
private static int remaining(long deadline) throws IOException {
|
|
60
|
+
long milliseconds = (deadline - System.nanoTime()) / 1_000_000;
|
|
61
|
+
if (milliseconds <= 0) throw new IOException("App-event admission timed out");
|
|
62
|
+
return (int)Math.min(10000, milliseconds);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Cancels in-flight upload before changing identity or revoking collection. */
|
|
66
|
+
public void cancel() { cancellationRevision.incrementAndGet(); HttpURLConnection current = connection; if (current != null) current.disconnect(); }
|
|
67
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
package ai.sagepilot.events;
|
|
2
|
+
|
|
3
|
+
import com.facebook.react.bridge.*;
|
|
4
|
+
import java.util.concurrent.*;
|
|
5
|
+
import org.json.JSONArray;
|
|
6
|
+
import org.json.JSONObject;
|
|
7
|
+
|
|
8
|
+
/** Thin RN boundary; all file access, projection and compression run on a bounded native worker. */
|
|
9
|
+
public final class SagepilotEventsModule extends ReactContextBaseJavaModule {
|
|
10
|
+
private final ThreadPoolExecutor worker = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(160), runnable -> {
|
|
11
|
+
Thread thread = new Thread(runnable, "SagepilotAppEvents"); thread.setDaemon(true); return thread;
|
|
12
|
+
}, new ThreadPoolExecutor.AbortPolicy());
|
|
13
|
+
private final SagepilotEventsRuntime runtime;
|
|
14
|
+
private final SagepilotEventsHTTP http = new SagepilotEventsHTTP();
|
|
15
|
+
private final ThreadPoolExecutor network = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), runnable -> {
|
|
16
|
+
Thread thread = new Thread(runnable, "SagepilotEventsUpload"); thread.setDaemon(true); return thread;
|
|
17
|
+
}, new ThreadPoolExecutor.AbortPolicy());
|
|
18
|
+
private JSONObject owner;
|
|
19
|
+
|
|
20
|
+
/** Constructs passive observers without starting collection. */
|
|
21
|
+
public SagepilotEventsModule(ReactApplicationContext context) { super(context); runtime = new SagepilotEventsRuntime(context, worker); }
|
|
22
|
+
/** Exposes the package's autolinked bridge name. */
|
|
23
|
+
@Override public String getName() { return "SagepilotEventsAddon"; }
|
|
24
|
+
|
|
25
|
+
/** Converts only small control results; compressed payload bytes remain a bounded string. */
|
|
26
|
+
private void run(Promise promise, Operation operation) {
|
|
27
|
+
try { worker.execute(() -> { try { promise.resolve(operation.call()); } catch (Exception error) { promise.reject("app_events", "Sagepilot app-event operation failed", error); } }); }
|
|
28
|
+
catch (RejectedExecutionException error) { promise.reject("app_events_busy", "Sagepilot app-event worker is busy", error); }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Opens the per-app journal without any channel, notification or chat UI dependency. */
|
|
32
|
+
@ReactMethod public void configure(ReadableMap config, Promise promise) {
|
|
33
|
+
JSONObject value = new JSONObject(config.toHashMap()); run(promise, () -> { owner = null; runtime.configure(value); return null; });
|
|
34
|
+
}
|
|
35
|
+
/** Pauses capture before replacing ownership, fencing requests that span login/logout. */
|
|
36
|
+
@ReactMethod public void setIdentity(ReadableMap next, Promise promise) {
|
|
37
|
+
runtime.fence(); http.cancel(); JSONObject value = next == null ? null : new JSONObject(next.toHashMap());
|
|
38
|
+
run(promise, () -> { owner = value; return runtime.identity(value); });
|
|
39
|
+
}
|
|
40
|
+
/** Clears unuploaded observations only on explicit collection revocation. */
|
|
41
|
+
@ReactMethod public void setEnabled(boolean enabled, Promise promise) {
|
|
42
|
+
runtime.fence(); http.cancel(); run(promise, () -> runtime.enabled(enabled, owner));
|
|
43
|
+
}
|
|
44
|
+
/** Accepts only the internal automatic XHR descriptor; the app API exposes no tracking method. */
|
|
45
|
+
@ReactMethod public void observeNetworkBatch(ReadableArray observations, Promise promise) {
|
|
46
|
+
try {
|
|
47
|
+
if (observations.size() > 32) throw new IllegalArgumentException("Network observation batch exceeds limit");
|
|
48
|
+
java.util.List<JSONObject> values = new java.util.ArrayList<>();
|
|
49
|
+
for (int i = 0; i < observations.size(); i++) values.add(new JSONObject(observations.getMap(i).toHashMap()));
|
|
50
|
+
if (values.isEmpty()) { promise.resolve(null); return; }
|
|
51
|
+
java.util.concurrent.atomic.AtomicInteger remaining = new java.util.concurrent.atomic.AtomicInteger(values.size());
|
|
52
|
+
for (JSONObject input : values) runtime.network(input, () -> { if (remaining.decrementAndGet() == 0) promise.resolve(null); });
|
|
53
|
+
}
|
|
54
|
+
catch (Exception error) { promise.reject("app_events", "Could not observe network result", error); }
|
|
55
|
+
}
|
|
56
|
+
/** Reads and compresses at most one current-owner batch. */
|
|
57
|
+
@ReactMethod public void nextBatch(double bridgeDrops, Promise promise) {
|
|
58
|
+
run(promise, () -> {
|
|
59
|
+
JSONObject batch = runtime.batch(Double.isFinite(bridgeDrops) && bridgeDrops > 0 ? (long)bridgeDrops : 0); if (batch == null) return null;
|
|
60
|
+
java.util.Map<String,Object> result = new java.util.HashMap<>(); result.put("lease", batch.getString("lease"));
|
|
61
|
+
java.util.List<String> ids = new java.util.ArrayList<>(); JSONArray array = batch.getJSONArray("event_ids");
|
|
62
|
+
for (int i = 0; i < array.length(); i++) ids.add(array.getString(i)); result.put("event_ids", ids);
|
|
63
|
+
return Arguments.makeNativeMap(result);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** Runs authenticated native networking separately so slow uploads never block journal writes. */
|
|
67
|
+
@ReactMethod public void uploadBatch(String lease, String endpoint, ReadableMap headers, Promise promise) {
|
|
68
|
+
java.util.Map<String,String> values = new java.util.HashMap<>(); ReadableMapKeySetIterator keys = headers.keySetIterator();
|
|
69
|
+
while (keys.hasNextKey()) { String key = keys.nextKey(); values.put(key, headers.getString(key)); }
|
|
70
|
+
try {
|
|
71
|
+
network.execute(() -> {
|
|
72
|
+
try {
|
|
73
|
+
JSONObject receipt = http.post(endpoint, values, () -> runtime.uploadBody(lease));
|
|
74
|
+
JSONArray results = receipt.getJSONArray("results"); if (results.length() > 100) throw new IllegalStateException("Too many admission receipts");
|
|
75
|
+
java.util.List<java.util.Map<String,Object>> records = new java.util.ArrayList<>();
|
|
76
|
+
for (int i = 0; i < results.length(); i++) { JSONObject item = results.getJSONObject(i); java.util.Map<String,Object> record = new java.util.HashMap<>(); record.put("event_id", item.getString("event_id")); record.put("status", item.getString("status")); records.add(record); }
|
|
77
|
+
java.util.Map<String,Object> result = new java.util.HashMap<>(); result.put("results", records); promise.resolve(Arguments.makeNativeMap(result));
|
|
78
|
+
} catch (Exception error) { promise.reject("app_events_upload", "App-event batch admission failed", error); }
|
|
79
|
+
});
|
|
80
|
+
} catch (RejectedExecutionException error) { promise.reject("app_events_busy", "An app-event upload is already pending", error); }
|
|
81
|
+
}
|
|
82
|
+
/** Applies only terminal receipts belonging to this exact native batch lease. */
|
|
83
|
+
@ReactMethod public void acknowledge(String lease, ReadableArray ids, Promise promise) { JSONArray value = new JSONArray(ids.toArrayList()); run(promise, () -> { runtime.acknowledge(lease, value); return null; }); }
|
|
84
|
+
/** Reports counters rather than all payloads. */
|
|
85
|
+
@ReactMethod public void diagnostics(Promise promise) { run(promise, () -> { JSONObject values = runtime.diagnostics(); java.util.Map<String,Object> result = new java.util.HashMap<>(); java.util.Iterator<String> keys = values.keys(); while (keys.hasNext()) { String key = keys.next(); result.put(key, values.get(key)); } return Arguments.makeNativeMap(result); }); }
|
|
86
|
+
/** Disables hooks immediately, then confirms worker teardown without deleting acknowledged history. */
|
|
87
|
+
@ReactMethod public void stop(Promise promise) { runtime.stop(); http.cancel(); run(promise, () -> null); }
|
|
88
|
+
/** Stops collection when React destroys the bridge, allowing already queued worker jobs to finish safely. */
|
|
89
|
+
@Override public void invalidate() { runtime.stop(); http.cancel(); worker.shutdown(); network.shutdown(); super.invalidate(); }
|
|
90
|
+
|
|
91
|
+
/** Allows worker operations to propagate useful native errors through one reusable bridge path. */
|
|
92
|
+
private interface Operation {
|
|
93
|
+
/** Runs one bounded native control operation on the background worker. */
|
|
94
|
+
Object call() throws Exception;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
package ai.sagepilot.events;
|
|
2
|
+
|
|
3
|
+
import com.facebook.react.ReactPackage;
|
|
4
|
+
import com.facebook.react.bridge.NativeModule;
|
|
5
|
+
import com.facebook.react.bridge.ReactApplicationContext;
|
|
6
|
+
import com.facebook.react.uimanager.ViewManager;
|
|
7
|
+
import java.util.Collections;
|
|
8
|
+
import java.util.List;
|
|
9
|
+
|
|
10
|
+
/** Autolinks automatic collectors without adding a view or changing the app's component tree. */
|
|
11
|
+
public final class SagepilotEventsPackage implements ReactPackage {
|
|
12
|
+
/** Creates the optional native collector module. */
|
|
13
|
+
@Override public List<NativeModule> createNativeModules(ReactApplicationContext context) { return Collections.singletonList(new SagepilotEventsModule(context)); }
|
|
14
|
+
/** This add-on does not install a React UI component or responder. */
|
|
15
|
+
@Override public List<ViewManager> createViewManagers(ReactApplicationContext context) { return Collections.emptyList(); }
|
|
16
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
package ai.sagepilot.events;
|
|
2
|
+
|
|
3
|
+
import org.json.JSONArray;
|
|
4
|
+
import org.json.JSONObject;
|
|
5
|
+
import java.util.Iterator;
|
|
6
|
+
import java.util.Locale;
|
|
7
|
+
import java.util.HashSet;
|
|
8
|
+
import java.util.Set;
|
|
9
|
+
|
|
10
|
+
/** Bounded domain-neutral context projection; business meanings belong to the server. */
|
|
11
|
+
public final class SagepilotEventsProjection {
|
|
12
|
+
public static final int BODY_LIMIT = 65536;
|
|
13
|
+
private static final java.util.regex.Pattern SENSITIVE = java.util.regex.Pattern.compile("password|secret|token|auth|email|phone|address|card|payment|customer|user|session|cookie|medical|health|credential|private|passport|license|socialsecurity|apikey|accesskey|jwt|birth|iban|cvv|passcode|(^pin$)|(^otp$)|(^ssn$)");
|
|
14
|
+
private static final java.util.regex.Pattern TEXT_FIELD = java.util.regex.Pattern.compile("name$|title$|description$|message$|comments?$|notes?$|^content$|html$|^text$|freetext$|^search$|^query$");
|
|
15
|
+
private static final java.util.regex.Pattern COMPACT = java.util.regex.Pattern.compile("[A-Za-z0-9_./:@+-]{0,256}");
|
|
16
|
+
private static final java.util.regex.Pattern PRIVATE_VALUE = java.util.regex.Pattern.compile("(?i)@|^bearer|^eyJ[A-Za-z0-9_-]*\\.|^(sk|pk)_(live|test)_|^(?:\\+?[0-9]{7,19}|\\+?[0-9]{1,4}[-.() ]?[0-9]{3}[-.() ]?[0-9]{3,4})$");
|
|
17
|
+
private static final java.util.regex.Pattern NUMERIC_REFERENCE = java.util.regex.Pattern.compile("[0-9]{7,15}");
|
|
18
|
+
private static final java.util.regex.Pattern FIELD = java.util.regex.Pattern.compile("[A-Za-z_][A-Za-z0-9_]{0,63}");
|
|
19
|
+
private static final java.util.regex.Pattern CONTROL = java.util.regex.Pattern.compile("[\\x00-\\x1f]");
|
|
20
|
+
private static final java.util.regex.Pattern VERSION = java.util.regex.Pattern.compile("[vV][0-9]{1,3}");
|
|
21
|
+
private static final java.util.regex.Pattern OPERATION = java.util.regex.Pattern.compile("[A-Za-z][A-Za-z_-]{0,47}");
|
|
22
|
+
private static final Set<String> FIELDS = new HashSet<>(java.util.Arrays.asList(
|
|
23
|
+
"id", "productid", "productcode", "variantid", "variantcode", "merchandiseid", "sku", "title", "name", "brand", "category",
|
|
24
|
+
"price", "unitprice", "sellingprice", "saleprice", "amount", "currency", "currencycode", "quantity", "quantityadded", "delta",
|
|
25
|
+
"discount", "discountamount", "image", "imageurl", "url", "producturl", "available", "availability", "typename"));
|
|
26
|
+
|
|
27
|
+
/** Projects bounded field paths, typed scalar context and optional product hints from any JSON shape. */
|
|
28
|
+
public static JSONObject project(String body) throws Exception {
|
|
29
|
+
JSONObject result = new JSONObject();
|
|
30
|
+
if (!safeJson(body)) return result.put("omitted", "size_depth_or_format_limit");
|
|
31
|
+
Object value;
|
|
32
|
+
try { value = body.trim().startsWith("[") ? new JSONArray(body) : new JSONObject(body); }
|
|
33
|
+
catch (Exception error) { return result.put("omitted", "invalid_json"); }
|
|
34
|
+
State state = new State();
|
|
35
|
+
walk(value, "$", "$", 0, state);
|
|
36
|
+
return result.put("projection_version", 2).put("structure", state.structure).put("fields", state.fields).put("product_candidates", state.candidates).put("signals", state.signals)
|
|
37
|
+
.put("limited", state.limited);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Fingerprints alphabetic operation segments and masks probable IDs without retaining raw route text. */
|
|
41
|
+
public static String route(String input) throws Exception {
|
|
42
|
+
if (input == null || input.length() > 2048) return null;
|
|
43
|
+
java.net.URI uri = new java.net.URI(input);
|
|
44
|
+
if (!("https".equals(uri.getScheme()) || "http".equals(uri.getScheme())) || uri.getHost() == null || uri.getRawUserInfo() != null) return null;
|
|
45
|
+
String[] parts = (uri.getRawPath() == null ? "" : uri.getRawPath()).split("/", -1);
|
|
46
|
+
StringBuilder path = new StringBuilder();
|
|
47
|
+
for (int i = 1; i < Math.min(parts.length, 12); i++) {
|
|
48
|
+
String part;
|
|
49
|
+
try { part = java.net.URLDecoder.decode(parts[i].replace("+", "%2B"), "UTF-8"); }
|
|
50
|
+
catch (IllegalArgumentException error) { part = ""; }
|
|
51
|
+
path.append('/');
|
|
52
|
+
if (VERSION.matcher(part).matches()) path.append(part);
|
|
53
|
+
else if (OPERATION.matcher(part).matches()) {
|
|
54
|
+
byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(part.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
|
55
|
+
path.append(":op_"); for (int n = 0; n < 8; n++) path.append("0123456789abcdef".charAt((digest[n] & 255) >>> 4)).append("0123456789abcdef".charAt(digest[n] & 15));
|
|
56
|
+
} else if (!part.isEmpty()) path.append(":segment");
|
|
57
|
+
}
|
|
58
|
+
return new java.net.URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), path.toString(), null, null).toString();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Bounds every retained projection entry by its encoded size, shared across all output arrays. */
|
|
62
|
+
private static void retain(JSONArray target, JSONObject entry, int cap, State state) {
|
|
63
|
+
int bytes = entry.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8).length + 1;
|
|
64
|
+
if (target.length() >= cap || state.bytes + bytes > 11264) { state.limited = true; return; }
|
|
65
|
+
target.put(entry); state.bytes += bytes;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Retains safe scalar context without requiring industry-specific field names or inferring semantics. */
|
|
69
|
+
private static JSONObject field(Object value, String path, String type) throws Exception {
|
|
70
|
+
JSONObject field = new JSONObject().put("path", path).put("type", type);
|
|
71
|
+
String name = key(path.substring(path.lastIndexOf('.') + 1));
|
|
72
|
+
if (value instanceof String) {
|
|
73
|
+
String text = (String)value;
|
|
74
|
+
if (TEXT_FIELD.matcher(name).find() && !name.equals("operationname") && !name.equals("typename")) return field.put("omitted", "text_or_sensitive_value");
|
|
75
|
+
if (text.toLowerCase(Locale.ROOT).startsWith("http://") || text.toLowerCase(Locale.ROOT).startsWith("https://")) {
|
|
76
|
+
Object url; try { url = route(text); } catch (Exception error) { url = null; }
|
|
77
|
+
if (url != null) field.put("route_fingerprint", url);
|
|
78
|
+
return field.put("omitted", url == null ? "invalid_url" : "url_value");
|
|
79
|
+
}
|
|
80
|
+
if (!COMPACT.matcher(text).matches() || PRIVATE_VALUE.matcher(text).find()) return field.put("omitted", "text_or_sensitive_value");
|
|
81
|
+
} else if (value instanceof Number && (!Double.isFinite(((Number)value).doubleValue()) || Math.abs(((Number)value).doubleValue()) > 9007199254740991d)) return field.put("omitted", "unsafe_number");
|
|
82
|
+
return field.put("value", value);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Rejects nesting bombs before invoking the platform JSON parser. */
|
|
86
|
+
static boolean safeJson(String text) {
|
|
87
|
+
if (text == null || text.length() > BODY_LIMIT) return false;
|
|
88
|
+
String trimmed = text.trim(); if (!(trimmed.startsWith("[") || trimmed.startsWith("{"))) return false;
|
|
89
|
+
int depth = 0; boolean quoted = false, escaped = false;
|
|
90
|
+
for (int i = 0; i < text.length(); i++) {
|
|
91
|
+
char c = text.charAt(i);
|
|
92
|
+
if (quoted) { if (escaped) escaped = false; else if (c == '\\') escaped = true; else if (c == '"') quoted = false; }
|
|
93
|
+
else if (c == '"') quoted = true;
|
|
94
|
+
else if (c == '{' || c == '[') { if (++depth > 12) return false; }
|
|
95
|
+
else if (c == '}' || c == ']') { if (--depth < 0) return false; }
|
|
96
|
+
}
|
|
97
|
+
return depth == 0 && !quoted;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Normalizes policy matching without rewriting original field paths. */
|
|
101
|
+
private static String key(String key) { return key.replace("_", "").toLowerCase(Locale.ROOT); }
|
|
102
|
+
|
|
103
|
+
/** Makes budget truncation deterministic across Android and iOS dictionary enumeration orders. */
|
|
104
|
+
private static Iterator<String> keys(JSONObject object) {
|
|
105
|
+
java.util.ArrayList<String> names = new java.util.ArrayList<>();
|
|
106
|
+
Iterator<String> input = object.keys(); while (input.hasNext()) names.add(input.next());
|
|
107
|
+
java.util.Collections.sort(names); return names.iterator();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Recognizes explicit product references without asserting the meaning of a bare id. */
|
|
111
|
+
private static boolean candidate(JSONObject object) {
|
|
112
|
+
for (String name : new String[]{"sku", "product_id", "productId", "productCode", "product_code", "merchandiseId", "merchandise_id"}) {
|
|
113
|
+
if (object.has(name) && object.opt(name) != JSONObject.NULL) return true;
|
|
114
|
+
}
|
|
115
|
+
String type = object.optString("__typename"); return type.equalsIgnoreCase("Product") || type.equalsIgnoreCase("ProductVariant");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Keeps short public product attributes and bounded money objects, never arbitrary nested values. */
|
|
119
|
+
private static Object attribute(Object value, String name, int depth) throws Exception {
|
|
120
|
+
if (value == JSONObject.NULL || value instanceof Boolean) return value;
|
|
121
|
+
if (value instanceof Number) return Double.isFinite(((Number)value).doubleValue()) && Math.abs(((Number)value).doubleValue()) <= 9007199254740991d ? value : null;
|
|
122
|
+
if (value instanceof String) {
|
|
123
|
+
String string = (String)value;
|
|
124
|
+
if (string.length() > 256 || CONTROL.matcher(string).find()) return null;
|
|
125
|
+
if (name.contains("url") || name.equals("image")) {
|
|
126
|
+
try {
|
|
127
|
+
java.net.URI uri = new java.net.URI(string);
|
|
128
|
+
if (!("https".equals(uri.getScheme()) || "http".equals(uri.getScheme())) || uri.getRawUserInfo() != null || uri.getHost() == null) return null;
|
|
129
|
+
return new java.net.URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), null, null).toString();
|
|
130
|
+
} catch (Exception error) { return null; }
|
|
131
|
+
}
|
|
132
|
+
boolean reference = name.equals("id") || name.endsWith("id") || name.equals("sku") || name.endsWith("code");
|
|
133
|
+
return PRIVATE_VALUE.matcher(string).find() && !(reference && NUMERIC_REFERENCE.matcher(string).matches()) ? null : string;
|
|
134
|
+
}
|
|
135
|
+
if (value instanceof JSONObject && depth < 2) {
|
|
136
|
+
JSONObject result = new JSONObject(), object = (JSONObject)value;
|
|
137
|
+
Iterator<String> keys = keys(object); int count = 0;
|
|
138
|
+
while (keys.hasNext() && count++ < 32) {
|
|
139
|
+
String original = keys.next(), normalized = key(original);
|
|
140
|
+
if (!FIELDS.contains(normalized) || SENSITIVE.matcher(normalized).find()) continue;
|
|
141
|
+
Object item = attribute(object.opt(original), normalized, depth + 1);
|
|
142
|
+
if (item != null) result.put(original, item);
|
|
143
|
+
}
|
|
144
|
+
return result.length() == 0 ? null : result;
|
|
145
|
+
}
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Traverses a bounded structural sample, excluding sensitive subtrees before recursion. */
|
|
150
|
+
private static void walk(Object value, String path, String shape, int depth, State state) throws Exception {
|
|
151
|
+
if (++state.nodes > 512 || depth > 10) { state.limited = true; return; }
|
|
152
|
+
String type = value instanceof JSONObject ? "object" : value instanceof JSONArray ? "array" : value == JSONObject.NULL ? "null"
|
|
153
|
+
: value instanceof Boolean ? "boolean" : value instanceof Number ? "number" : "string";
|
|
154
|
+
if (state.structure.length() < 128 && state.paths.add(shape + "|" + type)) {
|
|
155
|
+
retain(state.structure, new JSONObject().put("path", shape).put("type", type), 128, state);
|
|
156
|
+
}
|
|
157
|
+
else if (state.structure.length() >= 128 && !state.paths.contains(shape + "|" + type)) state.limited = true;
|
|
158
|
+
if (value instanceof JSONObject) {
|
|
159
|
+
JSONObject object = (JSONObject)value;
|
|
160
|
+
if (candidate(object) && object.length() > 32) state.limited = true;
|
|
161
|
+
if (candidate(object) && state.candidates.length() < 20) {
|
|
162
|
+
Object projected = attribute(object, "", 0);
|
|
163
|
+
if (projected != null) retain(state.candidates, new JSONObject().put("path", path).put("fields", projected), 20, state);
|
|
164
|
+
}
|
|
165
|
+
else if (candidate(object)) state.limited = true;
|
|
166
|
+
Iterator<String> keys = keys(object); int count = 0;
|
|
167
|
+
while (keys.hasNext() && count++ < 64 && state.nodes < 512) {
|
|
168
|
+
String original = keys.next(), normalized = key(original);
|
|
169
|
+
if (!FIELD.matcher(original).matches() || SENSITIVE.matcher(normalized).find()) continue;
|
|
170
|
+
Object child = object.opt(original);
|
|
171
|
+
if (TEXT_FIELD.matcher(normalized).find() && !normalized.equals("operationname") && !normalized.equals("typename") && (child instanceof JSONObject || child instanceof JSONArray)) continue;
|
|
172
|
+
if (state.signals.length() < 32 && (normalized.equals("success") || normalized.equals("accepted")) && child instanceof Boolean) {
|
|
173
|
+
retain(state.signals, new JSONObject().put("path", path + "." + original).put("value", child), 32, state);
|
|
174
|
+
}
|
|
175
|
+
walk(child, path + "." + original, shape + "." + original, depth + 1, state);
|
|
176
|
+
}
|
|
177
|
+
if (keys.hasNext()) state.limited = true;
|
|
178
|
+
} else if (value instanceof JSONArray) {
|
|
179
|
+
JSONArray array = (JSONArray)value;
|
|
180
|
+
for (int i = 0; i < Math.min(20, array.length()) && state.nodes < 512; i++) walk(array.opt(i), path + "[" + i + "]", shape + "[]", depth + 1, state);
|
|
181
|
+
if (array.length() > 20) state.limited = true;
|
|
182
|
+
} else retain(state.fields, field(value, path, type), 64, state);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Holds per-body traversal budgets; no application object is retained after projection. */
|
|
186
|
+
private static final class State {
|
|
187
|
+
final JSONArray structure = new JSONArray(), fields = new JSONArray(), candidates = new JSONArray(), signals = new JSONArray();
|
|
188
|
+
final Set<String> paths = new HashSet<>(); int nodes, bytes; boolean limited;
|
|
189
|
+
}
|
|
190
|
+
}
|