create-signet-app 0.8.2 → 0.9.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.
Files changed (58) hide show
  1. package/base/api/api/app.ts +15 -1
  2. package/base/api/api/env.ts +4 -0
  3. package/base/api/api/services.ts +55 -1
  4. package/base/web/src/routes/_app.tsx +6 -3
  5. package/package.json +3 -2
  6. package/parts/auth/api/api/routes/auth.ts +31 -8
  7. package/parts/mobile/api/api/routes/mobile.ts +71 -0
  8. package/parts/mobile/api/test/mobile.test.ts +104 -0
  9. package/parts/mobile/part.ts +11 -0
  10. package/parts/pwa/web/public/icon-192.png +0 -0
  11. package/parts/pwa/web/public/icon-512.png +0 -0
  12. package/parts/pwa/web/public/icon-maskable-512.png +0 -0
  13. package/parts/pwa/web/public/manifest.webmanifest +11 -1
  14. package/parts/pwa/web/public/sw.js +8 -1
  15. package/src/compose.ts +15 -4
  16. package/src/index.ts +53 -13
  17. package/src/mobile.ts +58 -0
  18. package/src/picker.ts +21 -8
  19. package/template-mobile/README.md +139 -0
  20. package/template-mobile/_github/workflows/ci.yml +38 -0
  21. package/template-mobile/_gitignore +1 -0
  22. package/template-mobile/mobile/_gitignore +16 -0
  23. package/template-mobile/mobile/app.config.ts +77 -0
  24. package/template-mobile/mobile/assets/adaptive-icon.png +0 -0
  25. package/template-mobile/mobile/assets/icon.png +0 -0
  26. package/template-mobile/mobile/assets/notification-icon.png +0 -0
  27. package/template-mobile/mobile/assets/splash-icon.png +0 -0
  28. package/template-mobile/mobile/babel.config.js +4 -0
  29. package/template-mobile/mobile/biome.json +8 -0
  30. package/template-mobile/mobile/eas.json +27 -0
  31. package/template-mobile/mobile/expo-env.d.ts +1 -0
  32. package/template-mobile/mobile/jest.config.js +9 -0
  33. package/template-mobile/mobile/jest.setup.js +32 -0
  34. package/template-mobile/mobile/src/__tests__/auth-gate.test.tsx +40 -0
  35. package/template-mobile/mobile/src/__tests__/sign-in.test.tsx +41 -0
  36. package/template-mobile/mobile/src/app/(app)/_layout.tsx +48 -0
  37. package/template-mobile/mobile/src/app/(app)/devices/[id].tsx +62 -0
  38. package/template-mobile/mobile/src/app/(app)/devices/_layout.tsx +19 -0
  39. package/template-mobile/mobile/src/app/(app)/devices/index.tsx +40 -0
  40. package/template-mobile/mobile/src/app/(app)/index.tsx +69 -0
  41. package/template-mobile/mobile/src/app/(app)/settings.tsx +116 -0
  42. package/template-mobile/mobile/src/app/(auth)/_layout.tsx +19 -0
  43. package/template-mobile/mobile/src/app/(auth)/sign-in.tsx +49 -0
  44. package/template-mobile/mobile/src/app/(auth)/verify.tsx +62 -0
  45. package/template-mobile/mobile/src/app/_layout.tsx +95 -0
  46. package/template-mobile/mobile/src/components/ui.tsx +230 -0
  47. package/template-mobile/mobile/src/lib/analytics.ts +20 -0
  48. package/template-mobile/mobile/src/lib/api.ts +49 -0
  49. package/template-mobile/mobile/src/lib/auth.ts +43 -0
  50. package/template-mobile/mobile/src/lib/config.ts +14 -0
  51. package/template-mobile/mobile/src/lib/devices.ts +18 -0
  52. package/template-mobile/mobile/src/lib/outbox.ts +84 -0
  53. package/template-mobile/mobile/src/lib/polyfills.ts +6 -0
  54. package/template-mobile/mobile/src/lib/push.ts +97 -0
  55. package/template-mobile/mobile/src/lib/session.ts +39 -0
  56. package/template-mobile/mobile/src/lib/storage.ts +17 -0
  57. package/template-mobile/mobile/src/lib/theme.tsx +64 -0
  58. package/template-mobile/mobile/tsconfig.json +11 -0
@@ -0,0 +1,95 @@
1
+ import "@/lib/polyfills"
2
+ import { nativeTheme } from "@dapplelight/signet-tokens/native"
3
+ import { QueryClientProvider } from "@tanstack/react-query"
4
+ import { type ErrorBoundaryProps, Stack } from "expo-router"
5
+ import * as SplashScreen from "expo-splash-screen"
6
+ import { StatusBar } from "expo-status-bar"
7
+ import { useEffect } from "react"
8
+ import { Pressable, Text, useColorScheme, View } from "react-native"
9
+ import { SafeAreaView } from "react-native-safe-area-context"
10
+ import { useScreenViews } from "@/lib/analytics"
11
+ import { queryClient } from "@/lib/api"
12
+ import "@/lib/auth"
13
+ import { useSession } from "@/lib/session"
14
+ import { DEFAULT_THEME, ThemeProvider, useTheme } from "@/lib/theme"
15
+
16
+ void SplashScreen.preventAutoHideAsync().catch(() => {})
17
+
18
+ /**
19
+ * The auth gate: signed in, the (app) tabs; signed out, (auth). A session
20
+ * that ends anywhere (sign-out, a 401 the refresh could not fix) lands on
21
+ * sign-in, because the guard flips.
22
+ */
23
+ function Gate() {
24
+ const tokens = useSession()
25
+ const t = useTheme()
26
+ useScreenViews()
27
+ const ready = tokens !== undefined
28
+ useEffect(() => {
29
+ if (ready) void SplashScreen.hideAsync().catch(() => {})
30
+ }, [ready])
31
+ if (!ready) return null
32
+ return (
33
+ <>
34
+ <StatusBar style={t.dark ? "light" : "dark"} />
35
+ <Stack
36
+ screenOptions={{
37
+ headerShown: false,
38
+ contentStyle: { backgroundColor: t.colors.background },
39
+ }}
40
+ >
41
+ {/* Name where each side lands: (auth) has no index of its own. */}
42
+ <Stack.Protected guard={!!tokens} redirectTo="/sign-in">
43
+ <Stack.Screen name="(app)" />
44
+ </Stack.Protected>
45
+ <Stack.Protected guard={!tokens} redirectTo="/">
46
+ <Stack.Screen name="(auth)" />
47
+ </Stack.Protected>
48
+ </Stack>
49
+ </>
50
+ )
51
+ }
52
+
53
+ export default function RootLayout() {
54
+ return (
55
+ <QueryClientProvider client={queryClient}>
56
+ <ThemeProvider>
57
+ <Gate />
58
+ </ThemeProvider>
59
+ </QueryClientProvider>
60
+ )
61
+ }
62
+
63
+ /** Shown in place of any screen that throws while rendering. */
64
+ export function ErrorBoundary({ error, retry }: ErrorBoundaryProps) {
65
+ const t = nativeTheme(DEFAULT_THEME, useColorScheme())
66
+ return (
67
+ <SafeAreaView style={{ flex: 1, backgroundColor: t.colors.background }}>
68
+ <View style={{ flex: 1, justifyContent: "center", padding: 24, gap: 16 }}>
69
+ <Text
70
+ accessibilityRole="header"
71
+ style={{ color: t.colors.foreground, fontSize: t.fontSize.xl, fontWeight: "600" }}
72
+ >
73
+ Something went wrong
74
+ </Text>
75
+ <Text style={{ color: t.colors.mutedForeground, fontSize: t.fontSize.base }}>
76
+ {__DEV__ ? error.message : "This screen hit a problem. Try again."}
77
+ </Text>
78
+ <Pressable
79
+ accessibilityRole="button"
80
+ accessibilityLabel="Try again"
81
+ onPress={retry}
82
+ style={{
83
+ minHeight: 44,
84
+ borderRadius: t.radius.md,
85
+ backgroundColor: t.colors.primary,
86
+ alignItems: "center",
87
+ justifyContent: "center",
88
+ }}
89
+ >
90
+ <Text style={{ color: t.colors.primaryForeground, fontWeight: "600" }}>Try again</Text>
91
+ </Pressable>
92
+ </View>
93
+ </SafeAreaView>
94
+ )
95
+ }
@@ -0,0 +1,230 @@
1
+ import { errorCopy } from "@dapplelight/signet-lib/api"
2
+ import type { ReactNode } from "react"
3
+ import {
4
+ ActivityIndicator,
5
+ KeyboardAvoidingView,
6
+ Platform,
7
+ Pressable,
8
+ ScrollView,
9
+ Text,
10
+ TextInput,
11
+ type TextInputProps,
12
+ View,
13
+ } from "react-native"
14
+ import { type Edge, SafeAreaView } from "react-native-safe-area-context"
15
+ import { useTheme } from "@/lib/theme"
16
+
17
+ /** The smallest comfortable touch target, in points (Apple's 44, Android's 48dp). */
18
+ export const TOUCH = 44
19
+
20
+ /**
21
+ * A screen's background and padding inside the safe area. `form` scrolls and
22
+ * moves up with the keyboard, so the focused field and its button stay visible.
23
+ */
24
+ export function Screen({
25
+ children,
26
+ form,
27
+ edges = ["bottom"],
28
+ }: {
29
+ children: ReactNode
30
+ form?: boolean
31
+ edges?: Edge[]
32
+ }) {
33
+ const t = useTheme()
34
+ const body = { padding: t.spacing * 5, gap: t.spacing * 4 }
35
+ return (
36
+ <SafeAreaView edges={edges} style={{ flex: 1, backgroundColor: t.colors.background }}>
37
+ {form ? (
38
+ <KeyboardAvoidingView
39
+ style={{ flex: 1 }}
40
+ behavior={Platform.OS === "ios" ? "padding" : undefined}
41
+ >
42
+ <ScrollView contentContainerStyle={body} keyboardShouldPersistTaps="handled">
43
+ {children}
44
+ </ScrollView>
45
+ </KeyboardAvoidingView>
46
+ ) : (
47
+ <View style={[{ flex: 1 }, body]}>{children}</View>
48
+ )}
49
+ </SafeAreaView>
50
+ )
51
+ }
52
+
53
+ export function Title({ children }: { children: ReactNode }) {
54
+ const t = useTheme()
55
+ return (
56
+ <Text
57
+ accessibilityRole="header"
58
+ style={{ color: t.colors.foreground, fontSize: t.fontSize.xl, fontWeight: "600" }}
59
+ >
60
+ {children}
61
+ </Text>
62
+ )
63
+ }
64
+
65
+ export function Body({ children, muted }: { children: ReactNode; muted?: boolean }) {
66
+ const t = useTheme()
67
+ return (
68
+ <Text
69
+ style={{
70
+ color: muted ? t.colors.mutedForeground : t.colors.foreground,
71
+ fontSize: t.fontSize.base,
72
+ }}
73
+ >
74
+ {children}
75
+ </Text>
76
+ )
77
+ }
78
+
79
+ export function Button({
80
+ label,
81
+ onPress,
82
+ variant = "primary",
83
+ loading,
84
+ disabled,
85
+ hint,
86
+ }: {
87
+ label: string
88
+ onPress: () => void
89
+ variant?: "primary" | "secondary" | "destructive"
90
+ loading?: boolean
91
+ disabled?: boolean
92
+ /** What happens on press, for screen readers, when the label alone does not say. */
93
+ hint?: string
94
+ }) {
95
+ const t = useTheme()
96
+ const bg = {
97
+ primary: t.colors.primary,
98
+ secondary: t.colors.secondary,
99
+ destructive: t.colors.destructive,
100
+ }[variant]
101
+ const fg = variant === "secondary" ? t.colors.secondaryForeground : t.colors.primaryForeground
102
+ const off = disabled || loading
103
+ return (
104
+ <Pressable
105
+ accessibilityRole="button"
106
+ accessibilityLabel={label}
107
+ accessibilityHint={hint}
108
+ accessibilityState={{ disabled: !!off, busy: !!loading }}
109
+ disabled={off}
110
+ onPress={onPress}
111
+ style={({ pressed }) => ({
112
+ minHeight: TOUCH,
113
+ borderRadius: t.radius.md,
114
+ backgroundColor: bg,
115
+ alignItems: "center",
116
+ justifyContent: "center",
117
+ paddingHorizontal: t.spacing * 4,
118
+ opacity: off ? 0.5 : pressed ? 0.8 : 1,
119
+ })}
120
+ >
121
+ {loading ? (
122
+ <ActivityIndicator color={fg} />
123
+ ) : (
124
+ <Text style={{ color: fg, fontSize: t.fontSize.base, fontWeight: "600" }}>{label}</Text>
125
+ )}
126
+ </Pressable>
127
+ )
128
+ }
129
+
130
+ export function TextField({
131
+ label,
132
+ error,
133
+ ...input
134
+ }: TextInputProps & { label: string; error?: string | undefined }) {
135
+ const t = useTheme()
136
+ return (
137
+ <View style={{ gap: t.spacing * 1.5 }}>
138
+ <Text style={{ color: t.colors.foreground, fontSize: t.fontSize.sm, fontWeight: "500" }}>
139
+ {label}
140
+ </Text>
141
+ <TextInput
142
+ accessibilityLabel={label}
143
+ accessibilityHint={error}
144
+ placeholderTextColor={t.colors.mutedForeground}
145
+ style={{
146
+ minHeight: TOUCH,
147
+ borderWidth: 1,
148
+ borderColor: error ? t.colors.destructive : t.colors.input,
149
+ borderRadius: t.radius.md,
150
+ paddingHorizontal: t.spacing * 3,
151
+ color: t.colors.foreground,
152
+ backgroundColor: t.colors.card,
153
+ fontSize: t.fontSize.base,
154
+ }}
155
+ {...input}
156
+ />
157
+ {error ? (
158
+ <Text accessibilityLiveRegion="polite" style={{ color: t.colors.destructive }}>
159
+ {error}
160
+ </Text>
161
+ ) : null}
162
+ </View>
163
+ )
164
+ }
165
+
166
+ /** A tappable row, at least one touch target tall. */
167
+ export function Row({
168
+ title,
169
+ detail,
170
+ onPress,
171
+ label,
172
+ }: {
173
+ title: string
174
+ detail?: string
175
+ onPress?: () => void
176
+ label?: string
177
+ }) {
178
+ const t = useTheme()
179
+ return (
180
+ <Pressable
181
+ accessibilityRole={onPress ? "button" : undefined}
182
+ accessibilityLabel={label ?? (detail ? `${title}, ${detail}` : title)}
183
+ disabled={!onPress}
184
+ onPress={onPress}
185
+ style={({ pressed }) => ({
186
+ minHeight: TOUCH + 12,
187
+ justifyContent: "center",
188
+ paddingHorizontal: t.spacing * 4,
189
+ paddingVertical: t.spacing * 2,
190
+ backgroundColor: pressed ? t.colors.muted : t.colors.card,
191
+ borderBottomWidth: 1,
192
+ borderBottomColor: t.colors.border,
193
+ })}
194
+ >
195
+ <Text style={{ color: t.colors.cardForeground, fontSize: t.fontSize.base }}>{title}</Text>
196
+ {detail ? (
197
+ <Text style={{ color: t.colors.mutedForeground, fontSize: t.fontSize.sm }}>{detail}</Text>
198
+ ) : null}
199
+ </Pressable>
200
+ )
201
+ }
202
+
203
+ /** Loading, empty and error in one place, so every list says them the same way. */
204
+ export function StateView({
205
+ loading,
206
+ error,
207
+ empty,
208
+ onRetry,
209
+ }: {
210
+ loading?: boolean
211
+ error?: unknown
212
+ empty?: string
213
+ onRetry?: () => void
214
+ }) {
215
+ const t = useTheme()
216
+ if (loading)
217
+ return (
218
+ <View style={{ padding: t.spacing * 8, alignItems: "center" }}>
219
+ <ActivityIndicator accessibilityLabel="Loading" color={t.colors.primary} />
220
+ </View>
221
+ )
222
+ const copy = error ? errorCopy((error as { code?: string }).code) : undefined
223
+ return (
224
+ <View style={{ padding: t.spacing * 8, gap: t.spacing * 3, alignItems: "center" }}>
225
+ <Body muted={!copy}>{copy ? copy.title : empty}</Body>
226
+ {copy ? <Body muted>{copy.detail}</Body> : null}
227
+ {copy && onRetry ? <Button label="Try again" variant="secondary" onPress={onRetry} /> : null}
228
+ </View>
229
+ )
230
+ }
@@ -0,0 +1,20 @@
1
+ import { beaconTransport, createAnalytics } from "@dapplelight/signet-lib/analytics"
2
+ import { usePathname } from "expo-router"
3
+ import { useEffect } from "react"
4
+ import { ANALYTICS_URL } from "./config"
5
+
6
+ /**
7
+ * Events in batches to EXPO_PUBLIC_ANALYTICS_URL; with it unset, a client that
8
+ * sends nothing. Ids live in memory, so each cold start is a new visit.
9
+ */
10
+ export const analytics = createAnalytics(
11
+ ANALYTICS_URL ? { transport: beaconTransport(ANALYTICS_URL) } : {},
12
+ )
13
+
14
+ /** One `screen_view` per route the app shows. Mounted once, in the root layout. */
15
+ export function useScreenViews() {
16
+ const path = usePathname()
17
+ useEffect(() => {
18
+ analytics.track("screen_view", { path })
19
+ }, [path])
20
+ }
@@ -0,0 +1,49 @@
1
+ import { ApiError, createApiClient, errorCopy } from "@dapplelight/signet-lib/api"
2
+ import { queryDefaults } from "@dapplelight/signet-lib/api/query-client"
3
+ import { QueryClient } from "@tanstack/react-query"
4
+ import { analytics } from "./analytics"
5
+ import { API_URL } from "./config"
6
+ import { session } from "./session"
7
+
8
+ export const queryClient = new QueryClient({ defaultOptions: queryDefaults() })
9
+
10
+ /**
11
+ * The API, with this phone's bearer token on every request. A 401 is retried
12
+ * once after a refresh; a 401 that stands means the session is gone (revoked,
13
+ * or the refresh token expired), so it is cleared and the gate shows sign-in
14
+ * (lib/auth.ts forgets the rest of the signed-in state).
15
+ */
16
+ export const api = createApiClient({
17
+ baseUrl: API_URL,
18
+ credentials: "omit",
19
+ token: session.token,
20
+ refresh: session.refresh,
21
+ headers: () => analytics.headers(),
22
+ onAuthError: () => void session.clear(),
23
+ })
24
+
25
+ /** What to tell the person: the server's own message for a refusal, else Signet's default copy. */
26
+ export function messageOf(e: unknown): string {
27
+ if (e instanceof ApiError && e.code && e.status < 500) return e.message
28
+ return errorCopy(e instanceof ApiError ? e.code : undefined).detail
29
+ }
30
+
31
+ /** The signed-in user, as /api/account/me returns them. */
32
+ export type User = {
33
+ id: string
34
+ phone: string
35
+ name: string | null
36
+ email: string | null
37
+ role: string
38
+ }
39
+
40
+ /** A signed-in device, as /api/sessions lists them. */
41
+ export type Device = {
42
+ id: string
43
+ device: string
44
+ ip: string | null
45
+ createdAt: number
46
+ lastSeenAt: number
47
+ expiresAt: number
48
+ current: boolean
49
+ }
@@ -0,0 +1,43 @@
1
+ import { fromTokenResponse } from "@dapplelight/signet-lib/session"
2
+ import { analytics } from "./analytics"
3
+ import { api, queryClient, type User } from "./api"
4
+ import { outbox } from "./outbox"
5
+ import { unregisterPush } from "./push"
6
+ import { CLIENT_ID, session } from "./session"
7
+
8
+ type TokenResponse = { access_token: string; refresh_token: string; expires_in: number }
9
+
10
+ /** Text a one-time code to `phone`. Resolves the masked number it went to. */
11
+ export async function requestCode(phone: string): Promise<string> {
12
+ const r = await api.post<{ to: string }>("/api/auth/otp", { phone })
13
+ return r.to
14
+ }
15
+
16
+ /** Trade the code for this phone's token pair; the gate then shows the app. */
17
+ export async function verifyCode(phone: string, code: string): Promise<User> {
18
+ const r = await api.post<{ user: User; tokens: TokenResponse }>(
19
+ `/api/auth/verify?client_id=${CLIENT_ID}`,
20
+ { phone, code },
21
+ )
22
+ analytics.identify(r.user.id)
23
+ await session.set(fromTokenResponse(r.tokens))
24
+ return r.user
25
+ }
26
+
27
+ /** Sign out here: the API revokes the session and drops the push token, best effort. */
28
+ export async function signOut(): Promise<void> {
29
+ const tokens = await session.get()
30
+ await unregisterPush()
31
+ if (tokens?.refreshToken)
32
+ await api.post("/api/mobile/revoke", { token: tokens.refreshToken }).catch(() => {})
33
+ await session.clear()
34
+ }
35
+
36
+ // However the session ends (sign-out, a revoked session, an expired refresh
37
+ // token), nothing of the last user stays: cached screens, queued writes, ids.
38
+ session.subscribe((tokens) => {
39
+ if (tokens) return
40
+ queryClient.clear()
41
+ void outbox.clear()
42
+ analytics.reset()
43
+ })
@@ -0,0 +1,14 @@
1
+ import Constants from "expo-constants"
2
+
3
+ /** What app.config.ts put in `extra`, read once. */
4
+ const extra = (Constants.expoConfig?.extra ?? {}) as {
5
+ apiUrl?: string
6
+ analyticsUrl?: string
7
+ eas?: { projectId?: string }
8
+ }
9
+
10
+ /** The API's origin, from EXPO_PUBLIC_API_URL at build time. */
11
+ export const API_URL = (extra.apiUrl ?? "http://localhost:3000").replace(/\/$/, "")
12
+ export const ANALYTICS_URL = extra.analyticsUrl
13
+ export const EAS_PROJECT_ID = extra.eas?.projectId
14
+ export const APP_VERSION = Constants.expoConfig?.version ?? "0.0.0"
@@ -0,0 +1,18 @@
1
+ import { createRelativeTimeFormatter } from "@dapplelight/signet-lib/format"
2
+ import { useQuery } from "@tanstack/react-query"
3
+ import { api, type Device } from "./api"
4
+
5
+ export const relative = createRelativeTimeFormatter()
6
+
7
+ /** Where this account is signed in: the sample list. Current device first. */
8
+ export function useDevices() {
9
+ return useQuery({
10
+ queryKey: ["devices"],
11
+ queryFn: async () => {
12
+ const { sessions } = await api.get<{ sessions: Device[] }>("/api/sessions")
13
+ return sessions.sort(
14
+ (a, b) => Number(b.current) - Number(a.current) || b.lastSeenAt - a.lastSeenAt,
15
+ )
16
+ },
17
+ })
18
+ }
@@ -0,0 +1,84 @@
1
+ import { isAuthError } from "@dapplelight/signet-lib/api"
2
+ import { isRetryable } from "@dapplelight/signet-lib/api/query-client"
3
+ import { createOutbox } from "@dapplelight/signet-lib/offline"
4
+ import * as Network from "expo-network"
5
+ import { useEffect, useState } from "react"
6
+ import { api } from "./api"
7
+ import { appStorage } from "./storage"
8
+
9
+ /** A write to send when the phone is back online. */
10
+ export type QueuedWrite = {
11
+ method: "POST" | "PUT" | "PATCH" | "DELETE"
12
+ path: string
13
+ body?: unknown
14
+ }
15
+
16
+ export const outbox = createOutbox<QueuedWrite>({ storage: appStorage, key: "outbox" })
17
+
18
+ const listeners = new Set<() => void>()
19
+ const changed = () => {
20
+ for (const l of listeners) l()
21
+ }
22
+
23
+ /** Send what is queued, oldest first. A write the server refuses for good (a 4xx) is dropped. */
24
+ export async function flushOutbox(): Promise<number> {
25
+ const sent = await outbox.flush(async (w, id) => {
26
+ try {
27
+ await api.request(w.path, {
28
+ method: w.method,
29
+ ...(w.body === undefined ? {} : { body: JSON.stringify(w.body) }),
30
+ headers: { "Idempotency-Key": id },
31
+ })
32
+ } catch (e) {
33
+ // Offline, a 5xx or a 401 stays for the next flush; a 400 or 404 never succeeds.
34
+ if (isRetryable(e) || isAuthError(e)) throw e
35
+ }
36
+ })
37
+ changed()
38
+ return sent
39
+ }
40
+
41
+ /**
42
+ * Send `write` now; when the request cannot reach the server, queue it.
43
+ * Resolves "sent" or "queued"; a refusal (a 4xx) still throws, for the form.
44
+ */
45
+ export async function sendOrQueue(write: QueuedWrite): Promise<"sent" | "queued"> {
46
+ try {
47
+ await api.request(write.path, {
48
+ method: write.method,
49
+ ...(write.body === undefined ? {} : { body: JSON.stringify(write.body) }),
50
+ })
51
+ return "sent"
52
+ } catch (e) {
53
+ // A fetch that never reached the server is a TypeError; anything else is the server's answer.
54
+ if (!(e instanceof TypeError)) throw e
55
+ await outbox.add(write)
56
+ changed()
57
+ return "queued"
58
+ }
59
+ }
60
+
61
+ /** Flush when the network comes back. Mounted once, in the signed-in layout. */
62
+ export function useOutboxFlush() {
63
+ useEffect(() => {
64
+ void flushOutbox().catch(() => {})
65
+ const sub = Network.addNetworkStateListener((s) => {
66
+ if (s.isConnected && s.isInternetReachable !== false) void flushOutbox().catch(() => {})
67
+ })
68
+ return () => sub.remove()
69
+ }, [])
70
+ }
71
+
72
+ /** How many writes wait to be sent. */
73
+ export function usePendingWrites(): number {
74
+ const [n, setN] = useState(0)
75
+ useEffect(() => {
76
+ const read = () => void outbox.count().then(setN, () => {})
77
+ read()
78
+ listeners.add(read)
79
+ return () => {
80
+ listeners.delete(read)
81
+ }
82
+ }, [])
83
+ return n
84
+ }
@@ -0,0 +1,6 @@
1
+ import { randomUUID } from "expo-crypto"
2
+
3
+ // Signet's outbox and analytics call crypto.randomUUID, which Hermes lacks.
4
+ const g = globalThis as { crypto?: { randomUUID?: () => string } }
5
+ g.crypto ??= {}
6
+ g.crypto.randomUUID ??= randomUUID
@@ -0,0 +1,97 @@
1
+ import * as Notifications from "expo-notifications"
2
+ import { type Href, router } from "expo-router"
3
+ import { useEffect, useState } from "react"
4
+ import { Linking, Platform } from "react-native"
5
+ import { api } from "./api"
6
+ import { EAS_PROJECT_ID } from "./config"
7
+ import { appStorage } from "./storage"
8
+
9
+ const TOKEN_KEY = "push-token"
10
+
11
+ // A notification that arrives while the app is open still shows.
12
+ Notifications.setNotificationHandler({
13
+ handleNotification: async () => ({
14
+ shouldShowBanner: true,
15
+ shouldShowList: true,
16
+ shouldPlaySound: false,
17
+ shouldSetBadge: false,
18
+ }),
19
+ })
20
+
21
+ /** Screens a notification may open; anything else in a payload is ignored. */
22
+ const ROUTES = ["/", "/devices", "/settings"]
23
+
24
+ /** The screen a tapped notification's `data.url` points to, if it is one of ours. */
25
+ export function notificationHref(data: unknown): Href | null {
26
+ const url = (data as { url?: unknown } | null | undefined)?.url
27
+ if (typeof url !== "string") return null
28
+ return ROUTES.some((r) => url === r || (r !== "/" && url.startsWith(`${r}/`)))
29
+ ? (url as Href)
30
+ : null
31
+ }
32
+
33
+ /**
34
+ * Send this phone's Expo push token to the API. Asks for permission only when
35
+ * `ask`; a phone that said no for good is sent to Settings instead.
36
+ * Resolves whether notifications are on.
37
+ */
38
+ export async function registerForPush(ask: boolean): Promise<boolean> {
39
+ const perm = ask
40
+ ? await Notifications.requestPermissionsAsync()
41
+ : await Notifications.getPermissionsAsync()
42
+ if (!perm.granted) {
43
+ if (ask && !perm.canAskAgain) await Linking.openSettings()
44
+ return false
45
+ }
46
+ if (Platform.OS === "android")
47
+ await Notifications.setNotificationChannelAsync("default", {
48
+ name: "Notifications",
49
+ importance: Notifications.AndroidImportance.DEFAULT,
50
+ })
51
+ const { data: token } = await Notifications.getExpoPushTokenAsync(
52
+ EAS_PROJECT_ID ? { projectId: EAS_PROJECT_ID } : {},
53
+ )
54
+ if ((await appStorage.get(TOKEN_KEY)) !== token) {
55
+ await api.post("/api/mobile/push/token", { token })
56
+ await appStorage.set(TOKEN_KEY, token)
57
+ }
58
+ return true
59
+ }
60
+
61
+ /** On sign-out: the API stops pushing to this phone. Best effort. */
62
+ export async function unregisterPush(): Promise<void> {
63
+ const token = await appStorage.get(TOKEN_KEY)
64
+ if (!token) return
65
+ await appStorage.remove(TOKEN_KEY)
66
+ await api.delete("/api/mobile/push/token", { token }).catch(() => {})
67
+ }
68
+
69
+ /**
70
+ * Signed-in only: re-send the token of a phone that already allowed
71
+ * notifications (tokens change), and open the screen a tapped notification names.
72
+ */
73
+ export function usePushRouting() {
74
+ const last = Notifications.useLastNotificationResponse()
75
+ useEffect(() => {
76
+ registerForPush(false).catch(() => {}) // offline or a simulator: tried again next launch
77
+ }, [])
78
+ useEffect(() => {
79
+ const href = notificationHref(last?.notification.request.content.data)
80
+ if (href) router.push(href)
81
+ }, [last])
82
+ }
83
+
84
+ /** For Settings: whether notifications are on (null while checking), and turning them on. */
85
+ export function usePushStatus() {
86
+ const [on, setOn] = useState<boolean | null>(null)
87
+ useEffect(() => {
88
+ Notifications.getPermissionsAsync().then(
89
+ (p) => setOn(p.granted),
90
+ () => setOn(false),
91
+ )
92
+ }, [])
93
+ return {
94
+ on,
95
+ enable: () => registerForPush(true).then(setOn, () => setOn(false)),
96
+ }
97
+ }