@astratra/native 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.
package/src/glass.js ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * How much glass this device can actually render.
3
+ *
4
+ * The first version of this said "iOS or an imitation", which was wrong and
5
+ * gave every Android app a flat plate where iOS got a translucent surface.
6
+ * Android renders a REAL backdrop blur — it simply needs to be asked for
7
+ * explicitly, and the ask is different from iOS's.
8
+ *
9
+ * So there are three answers, not two:
10
+ *
11
+ * 'native' — the platform's own glass material (iOS 26+ glass effect API);
12
+ * 'blur' — a real backdrop blur (expo-blur, iOS AND Android);
13
+ * 'fallback' — no blur available: a translucent layer, honestly flat.
14
+ *
15
+ * Deciding it once, from facts the caller reports, keeps every surface of the
16
+ * app in agreement — a header that blurs above a card that does not is worse
17
+ * than neither blurring.
18
+ *
19
+ * `apiAvailable` and `effectAvailable` stay separate: the module can be
20
+ * installed (API present) while the OS is too old for the effect itself.
21
+ */
22
+ function resolveGlassMode({ platform, apiAvailable, effectAvailable, blurAvailable } = {}) {
23
+ if (platform === 'ios' && Boolean(apiAvailable) && Boolean(effectAvailable)) return 'native';
24
+ if (blurAvailable) return 'blur';
25
+ return 'fallback';
26
+ }
27
+
28
+ /**
29
+ * What to pass expo-blur so the blur is real on this platform.
30
+ *
31
+ * Android needs `experimentalBlurMethod: 'dimezisBlurView'`. Without it the
32
+ * BlurView renders as a plain translucent overlay — it looks like the fallback
33
+ * while claiming to be a blur, which is the worst of the three states because
34
+ * nobody notices it is wrong.
35
+ */
36
+ function blurPropsFor(platform, intensity = 40) {
37
+ return {
38
+ intensity,
39
+ tint: 'light',
40
+ ...(platform === 'android' ? { experimentalBlurMethod: 'dimezisBlurView' } : {})
41
+ };
42
+ }
43
+
44
+ module.exports = { resolveGlassMode, blurPropsFor };
package/src/index.d.ts ADDED
@@ -0,0 +1,282 @@
1
+ /** The three async methods a keystore must have. expo-secure-store fits as-is. */
2
+ export interface Keystore {
3
+ getItemAsync(key: string): Promise<string | null>;
4
+ setItemAsync(key: string, value: string): Promise<void>;
5
+ deleteItemAsync(key: string): Promise<void>;
6
+ }
7
+
8
+ /** Anything with the browser Storage shape. */
9
+ export interface WebStorageLike {
10
+ getItem(key: string): string | null | undefined;
11
+ setItem(key: string, value: string): void;
12
+ removeItem(key: string): void;
13
+ }
14
+
15
+ export function createMemoryKeystore(): Keystore;
16
+ export function createWebKeystore(storage: WebStorageLike | null | undefined): Keystore;
17
+
18
+ export interface SessionTokens {
19
+ accessToken?: string | null;
20
+ refreshToken?: string | null;
21
+ }
22
+
23
+ export interface SecureSession {
24
+ readonly keys: Readonly<{ access: string; refresh: string; biometric: string }>;
25
+ getAccessToken(): Promise<string | null>;
26
+ getRefreshToken(): Promise<string | null>;
27
+ save(tokens?: SessionTokens): Promise<void>;
28
+ clear(): Promise<void>;
29
+ forget(): void;
30
+ }
31
+
32
+ export function createSecureSession(options: { keystore: Keystore; namespace?: string }): SecureSession;
33
+
34
+ /** expo-local-authentication's shape, narrowed to what the gate uses. */
35
+ export interface Authenticator {
36
+ hasHardwareAsync(): Promise<boolean>;
37
+ isEnrolledAsync(): Promise<boolean>;
38
+ authenticateAsync(options?: { promptMessage?: string }): Promise<{ success: boolean }>;
39
+ }
40
+
41
+ export interface BiometricState {
42
+ enabled: boolean;
43
+ hardware: boolean;
44
+ enrolled: boolean;
45
+ supported: boolean;
46
+ }
47
+
48
+ export interface BiometricEnableResult {
49
+ enabled: boolean;
50
+ supported: boolean;
51
+ failed: boolean;
52
+ }
53
+
54
+ export interface BiometricGate {
55
+ readonly key: string;
56
+ read(): Promise<BiometricState>;
57
+ enable(options?: { promptMessage?: string }): Promise<BiometricEnableResult>;
58
+ disable(): Promise<{ enabled: false }>;
59
+ confirm(options?: { promptMessage?: string }): Promise<boolean>;
60
+ }
61
+
62
+ export function createBiometricGate(options: {
63
+ keystore: Keystore;
64
+ authenticator: Authenticator;
65
+ namespace?: string;
66
+ promptMessage?: string;
67
+ }): BiometricGate;
68
+
69
+ /**
70
+ * 'native' — the platform's own glass material (iOS glass effect API);
71
+ * 'blur' — a real backdrop blur, iOS AND Android;
72
+ * 'fallback' — no blur available; an honest translucent layer.
73
+ */
74
+ export type GlassMode = 'native' | 'blur' | 'fallback';
75
+
76
+ export function resolveGlassMode(facts?: {
77
+ platform?: string;
78
+ apiAvailable?: boolean;
79
+ effectAvailable?: boolean;
80
+ blurAvailable?: boolean;
81
+ }): GlassMode;
82
+
83
+ export interface BlurProps {
84
+ intensity: number;
85
+ tint: string;
86
+ /** Android only, and required there: without it the blur is not a blur. */
87
+ experimentalBlurMethod?: string;
88
+ }
89
+
90
+ export function blurPropsFor(platform: string, intensity?: number): BlurProps;
91
+
92
+ /* ─────────────────────────── Foreground watch ────────────────────────── */
93
+
94
+ export interface WatchedItem {
95
+ createdAt?: string;
96
+ read?: boolean;
97
+ [key: string]: unknown;
98
+ }
99
+
100
+ export const FOREGROUND_POLL_MS: number;
101
+ export function freshItems<T extends WatchedItem>(items: T[] | null | undefined, lastSeenISO: string | null): T[];
102
+ export function nextStamp(items: WatchedItem[] | null | undefined, previous: string | null): string | null;
103
+ export function shouldPoll(appState: string, hasUser: boolean): boolean;
104
+
105
+ /* ───────────────────────────── Push policy ───────────────────────────── */
106
+
107
+ export type PushPermission = 'undetermined' | 'granted' | 'denied';
108
+ export type RegistrationAction = 'none' | 'register' | 'request' | 'open-settings';
109
+
110
+ export function decideRegistrationAction(input: {
111
+ explicit: boolean;
112
+ permission: PushPermission;
113
+ }): RegistrationAction;
114
+
115
+ export interface NotificationRoute {
116
+ pattern: RegExp;
117
+ allow?: (recipient: unknown, match: RegExpMatchArray) => boolean;
118
+ to?: string;
119
+ }
120
+
121
+ export interface NotificationPayload {
122
+ actionIdentifier?: string;
123
+ route?: unknown;
124
+ [key: string]: unknown;
125
+ }
126
+
127
+ export interface NotificationRouter {
128
+ readonly fallback: string;
129
+ resolve(route: unknown, recipient?: unknown): string;
130
+ resolveAction(payload: NotificationPayload | null | undefined, recipient?: unknown): string;
131
+ }
132
+
133
+ export function createNotificationRouter(options: {
134
+ fallback: string;
135
+ routes?: NotificationRoute[];
136
+ actions?: Record<string, (payload: NotificationPayload) => string | null | undefined>;
137
+ }): NotificationRouter;
138
+
139
+ /* ──────────────────────────── Push settings ──────────────────────────── */
140
+
141
+ export type PushState = 'enabled' | 'disabled' | 'undetermined' | 'denied' | 'error';
142
+ export type PushViewState = PushState | 'loading';
143
+ export type PushAction = 'enable' | 'disable' | 'open-settings' | 'retry';
144
+
145
+ export function resolvePushAction(state: PushViewState | string): PushAction | null;
146
+ export function isPushEnabled(state: PushViewState | string): boolean;
147
+
148
+ export interface PushSettingsSnapshot {
149
+ state: PushViewState;
150
+ busy: boolean;
151
+ }
152
+
153
+ export interface PushSettingsOperations {
154
+ getState(): Promise<PushState>;
155
+ enable?(): Promise<unknown>;
156
+ disable?(): Promise<unknown>;
157
+ openSettings?(): Promise<unknown>;
158
+ }
159
+
160
+ export interface PushSettingsController {
161
+ activate(): { ready: Promise<void>; dispose(): void };
162
+ refresh(): Promise<void>;
163
+ act(): Promise<void>;
164
+ }
165
+
166
+ export function createPushSettingsController(
167
+ operations: PushSettingsOperations,
168
+ onChange: (snapshot: PushSettingsSnapshot) => void
169
+ ): PushSettingsController;
170
+
171
+ /* ────────────────────────────── Checkout ─────────────────────────────── */
172
+
173
+ export interface LinkingLike {
174
+ openURL(url: string): Promise<unknown>;
175
+ }
176
+
177
+ export interface WebBrowserLike {
178
+ openAuthSessionAsync?(url: string, returnUrl: string): Promise<{ type: string }>;
179
+ openBrowserAsync(url: string, options?: Record<string, unknown>): Promise<unknown>;
180
+ }
181
+
182
+ /** Resolves true when the person came back through the return link — never "paid". */
183
+ export type CheckoutOpener = (url: string, returnUrl?: string) => Promise<boolean>;
184
+
185
+ export function createCheckoutOpener(options: {
186
+ linking: LinkingLike;
187
+ loadBrowser?: () => WebBrowserLike | null;
188
+ browserOptions?: Record<string, unknown>;
189
+ }): CheckoutOpener;
190
+
191
+ /* ─────────────────────────── Push registration ───────────────────────── */
192
+
193
+ export interface PushDeviceRecord {
194
+ registered: boolean;
195
+ enabled: boolean;
196
+ }
197
+
198
+ export interface PushRegistration {
199
+ installationId: string;
200
+ pushToken: string;
201
+ platform: string;
202
+ deviceName?: string;
203
+ }
204
+
205
+ export interface PushApi {
206
+ register(registration: PushRegistration): Promise<PushDeviceRecord>;
207
+ current(installationId: string): Promise<PushDeviceRecord>;
208
+ unregister(installationId: string): Promise<unknown>;
209
+ }
210
+
211
+ export interface PushDependencies {
212
+ platform: string;
213
+ isDevice: boolean;
214
+ deviceName?: string | null;
215
+ randomUUID(): string;
216
+ keystore: Keystore;
217
+ projectId: string | (() => Promise<string> | string);
218
+ notifications: Record<string, any>;
219
+ channels?: Array<{ id: string; name: string; config?: Record<string, unknown> }>;
220
+ categories?: Array<{ id: string; actions: unknown[] }>;
221
+ router: NotificationRouter;
222
+ navigate(route: string): void;
223
+ onAction?(payload: NotificationPayload): boolean | Promise<boolean>;
224
+ api: PushApi;
225
+ }
226
+
227
+ export interface PushService {
228
+ getInstallationId(): Promise<string>;
229
+ getState(): Promise<PushState | 'unsupported'>;
230
+ enable(): Promise<PushState | 'unsupported'>;
231
+ sync(): Promise<PushState | 'unsupported'>;
232
+ disable(): Promise<PushState | 'unsupported'>;
233
+ unregister(): Promise<void>;
234
+ allowRegistration(): void;
235
+ startListeners(recipient?: unknown): Promise<() => void>;
236
+ logout(signOut?: () => Promise<void>): Promise<void>;
237
+ }
238
+
239
+ export function createPushService(options: {
240
+ load: () => PushDependencies | Promise<PushDependencies>;
241
+ namespace?: string;
242
+ }): PushService;
243
+
244
+ export function readPermission(
245
+ status: { status?: string; granted?: boolean; ios?: { status: number } },
246
+ notifications: { IosAuthorizationStatus?: Record<string, number> }
247
+ ): PushPermission;
248
+
249
+ /* ───────────────────────────── API transport ─────────────────────────── */
250
+
251
+ export class ApiError extends Error {
252
+ name: 'ApiError';
253
+ status: number;
254
+ /** A failure can still be actionable — a 409 may carry where to go next. */
255
+ data?: unknown;
256
+ constructor(message: string, status: number, data?: unknown);
257
+ }
258
+
259
+ export interface ApiClient {
260
+ /** Unwraps the `data` envelope; throws ApiError on anything but 2xx. */
261
+ request<T = unknown>(path: string, init?: RequestInit): Promise<T>;
262
+ /** Server-sent events: the checked response, unread. */
263
+ stream(path: string, init?: RequestInit): Promise<Response>;
264
+ /** Bytes: the checked response, for the caller to write to disk. */
265
+ raw(path: string, init?: RequestInit): Promise<Response>;
266
+ /** Relative paths resolve against the origin, not against /api. */
267
+ resolveAssetUrl(path: string | null | undefined): string | undefined;
268
+ ApiError: typeof ApiError;
269
+ }
270
+
271
+ export function createApiClient(options: {
272
+ baseUrl: string;
273
+ session: SecureSession;
274
+ fetch?: typeof fetch;
275
+ language?: () => string | null | undefined;
276
+ platform?: string;
277
+ refresh?: () => Promise<void>;
278
+ excluded?: string[];
279
+ loginPath?: string;
280
+ refreshPath?: string;
281
+ onSessionExpired?: (cause: unknown) => void;
282
+ }): ApiClient;
package/src/index.js ADDED
@@ -0,0 +1,12 @@
1
+ module.exports = {
2
+ ...require('./keystore'),
3
+ ...require('./session'),
4
+ ...require('./biometric'),
5
+ ...require('./glass'),
6
+ ...require('./pushWatch'),
7
+ ...require('./pushPolicy'),
8
+ ...require('./pushSettings'),
9
+ ...require('./pushService'),
10
+ ...require('./checkout'),
11
+ ...require('./api')
12
+ };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Where the tokens live, and why the app must not care.
3
+ *
4
+ * On a phone a session belongs in the platform keystore — Keychain on iOS,
5
+ * Keystore on Android. That is a NATIVE module: importing it in this package
6
+ * would drag a native build into every test run, and would make the package
7
+ * useless anywhere the module is absent — a browser preview, a Node test, a
8
+ * development client compiled before the module was installed.
9
+ *
10
+ * So the keystore is INJECTED. Anything with the three async methods below
11
+ * qualifies: expo-secure-store passes as-is, and the two adapters here cover
12
+ * the cases where it cannot run.
13
+ *
14
+ * The contract is deliberately expo-secure-store's own, method names included.
15
+ * Renaming it would have forced every caller to write a wrapper for the one
16
+ * implementation everybody actually uses.
17
+ */
18
+
19
+ /**
20
+ * Tokens held for the lifetime of the process, nowhere else.
21
+ *
22
+ * For tests, and for the rare screen that must run before a keystore exists.
23
+ * NOT a fallback to reach for in a shipped app: a session that lives only in
24
+ * memory is gone at the next launch, and the person signs in again every time.
25
+ */
26
+ function createMemoryKeystore() {
27
+ const values = new Map();
28
+ return {
29
+ async getItemAsync(key) {
30
+ return values.has(key) ? values.get(key) : null;
31
+ },
32
+ async setItemAsync(key, value) {
33
+ values.set(key, String(value));
34
+ },
35
+ async deleteItemAsync(key) {
36
+ values.delete(key);
37
+ }
38
+ };
39
+ }
40
+
41
+ /**
42
+ * The browser stand-in, for development previews only.
43
+ *
44
+ * expo-secure-store has no real web implementation, and `localStorage` is not
45
+ * a keystore: any script on the page reads it. It is here so a preview can be
46
+ * clicked through, never so a shipped web build can hold a session.
47
+ *
48
+ * @param {object|null} storage localStorage, sessionStorage, or anything with
49
+ * getItem/setItem/removeItem. Null or absent is tolerated — a page with
50
+ * storage disabled must not crash on boot.
51
+ */
52
+ function createWebKeystore(storage) {
53
+ const backing = storage || null;
54
+ return {
55
+ async getItemAsync(key) {
56
+ if (!backing) return null;
57
+ try {
58
+ const value = backing.getItem(key);
59
+ return value === undefined ? null : value;
60
+ } catch {
61
+ return null;
62
+ }
63
+ },
64
+ async setItemAsync(key, value) {
65
+ if (!backing) return;
66
+ try {
67
+ backing.setItem(key, String(value));
68
+ } catch {
69
+ /* storage full or blocked: losing the session beats crashing */
70
+ }
71
+ },
72
+ async deleteItemAsync(key) {
73
+ if (!backing) return;
74
+ try {
75
+ backing.removeItem(key);
76
+ } catch {
77
+ /* same */
78
+ }
79
+ }
80
+ };
81
+ }
82
+
83
+ module.exports = { createMemoryKeystore, createWebKeystore };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Two decisions about a push that are easy to get wrong.
3
+ *
4
+ * WHEN TO ASK. The system prompt can be raised ONCE. Raise it on launch,
5
+ * before the person understands what the app sends, and a reflex "no" is
6
+ * permanent — the OS never asks again, and the only way back is a trip to the
7
+ * settings app that almost nobody makes. So the prompt waits for an explicit
8
+ * tap, and an already-granted permission registers silently.
9
+ *
10
+ * WHERE A TAP LEADS. A notification carries a route from the server. Following
11
+ * it blindly opens screens the recipient has no business seeing: the payload
12
+ * is data from the network, and roles change between the moment a notification
13
+ * is sent and the moment it is tapped. So a route is followed only if it
14
+ * matches a declared rule AND the rule admits this recipient. Everything else
15
+ * lands on the notification list, which is never wrong.
16
+ *
17
+ * The rules are declared BY ALLOWANCE, not by exclusion: a route nobody
18
+ * declared is refused. A blocklist silently admits every screen added later
19
+ * and forgotten.
20
+ */
21
+
22
+ /**
23
+ * @param {{explicit: boolean, permission: 'undetermined'|'granted'|'denied'}} input
24
+ * `explicit` is true when the person just tapped the switch themselves.
25
+ * @returns {'none'|'register'|'request'|'open-settings'}
26
+ */
27
+ function decideRegistrationAction({ explicit, permission } = {}) {
28
+ if (permission === 'granted') return 'register';
29
+ if (!explicit) return 'none';
30
+ return permission === 'undetermined' ? 'request' : 'open-settings';
31
+ }
32
+
33
+ /** Query strings and fragments are decoration; they must not defeat a match. */
34
+ function normalizeRoute(route) {
35
+ if (typeof route !== 'string') return '';
36
+ return route.split(/[?#]/, 1)[0];
37
+ }
38
+
39
+ /**
40
+ * @param {object} options
41
+ * @param {string} options.fallback Where a refused or unknown route lands.
42
+ * @param {Array<{pattern: RegExp, allow: Function, to?: string}>} [options.routes]
43
+ * `allow(recipient, match)` decides; `to` overrides the destination.
44
+ * @param {Object<string, Function>} [options.actions] Notification action
45
+ * buttons: id => (payload) => route|null. The result goes through the same
46
+ * permission check as any other route.
47
+ */
48
+ function createNotificationRouter(options = {}) {
49
+ const fallback = options.fallback || '/';
50
+ const routes = Array.isArray(options.routes) ? options.routes : [];
51
+ const actions = options.actions || {};
52
+
53
+ function resolve(route, recipient) {
54
+ const normalized = normalizeRoute(route);
55
+ if (!normalized) return fallback;
56
+ for (const rule of routes) {
57
+ if (!rule || !(rule.pattern instanceof RegExp)) continue;
58
+ const match = normalized.match(rule.pattern);
59
+ if (!match) continue;
60
+ const allowed = typeof rule.allow === 'function' ? rule.allow(recipient, match) : true;
61
+ return allowed ? (rule.to || normalized) : fallback;
62
+ }
63
+ return fallback;
64
+ }
65
+
66
+ /**
67
+ * A tap on an action button. The button names an intent ("justify", "refund");
68
+ * turning it into a route is the app's business, checking it is ours.
69
+ */
70
+ function resolveAction(payload, recipient) {
71
+ const data = payload || {};
72
+ const build = actions[data.actionIdentifier];
73
+ if (typeof build === 'function') {
74
+ const route = build(data);
75
+ if (route) return resolve(route, recipient);
76
+ }
77
+ return resolve(data.route, recipient);
78
+ }
79
+
80
+ return { resolve, resolveAction, fallback };
81
+ }
82
+
83
+ module.exports = { decideRegistrationAction, createNotificationRouter };