@startsimpli/integrations 0.2.86 → 0.2.87
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/package.json +4 -4
- package/src/native/recording/__tests__/authRefresh.test.ts +112 -0
- package/src/native/recording/__tests__/interruptionResume.test.ts +178 -0
- package/src/native/recording/__tests__/lifecycle.test.ts +157 -0
- package/src/native/recording/__tests__/recovery.test.ts +23 -0
- package/src/native/recording/index.ts +1 -0
- package/src/native/recording/lifecycle.ts +83 -0
- package/src/native/recording/recorder.ts +38 -6
- package/src/native/recording/recorderAudio.ts +20 -2
- package/src/native/recording/session.ts +13 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.87",
|
|
4
4
|
"description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://startsimpli.com",
|
|
@@ -99,10 +99,10 @@
|
|
|
99
99
|
"react-native": "0.85.3",
|
|
100
100
|
"react-native-safe-area-context": "~5.7.0",
|
|
101
101
|
"@startsimpli/llm": "0.4.28",
|
|
102
|
-
"@startsimpli/ui": "0.4.167",
|
|
103
102
|
"@startsimpli/ui-native": "0.1.3",
|
|
104
|
-
"@startsimpli/
|
|
105
|
-
"@startsimpli/
|
|
103
|
+
"@startsimpli/utils": "0.4.15",
|
|
104
|
+
"@startsimpli/ui": "0.4.167",
|
|
105
|
+
"@startsimpli/auth": "0.4.47"
|
|
106
106
|
},
|
|
107
107
|
"scripts": {
|
|
108
108
|
"type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createUploadQueue } from '@startsimpli/utils';
|
|
3
|
+
import { createSession, type SecretStore } from '../session';
|
|
4
|
+
import { createNotes } from '../notes';
|
|
5
|
+
import { FakeForm } from './fakeForm';
|
|
6
|
+
|
|
7
|
+
// bd startsim-150po.4: a token that expires mid-use must refresh, retry and
|
|
8
|
+
// leave 'auth.refresh' evidence in the diagnostics.
|
|
9
|
+
|
|
10
|
+
function jwt(secondsFromNow: number) {
|
|
11
|
+
const exp = Math.floor(Date.now() / 1000) + secondsFromNow;
|
|
12
|
+
const enc = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64');
|
|
13
|
+
return `${enc({ alg: 'HS256' })}.${enc({ exp, iat: exp - 3600, userId: '1' })}.sig`;
|
|
14
|
+
}
|
|
15
|
+
const res = (status: number, body: unknown = {}) => ({ ok: status < 400, status, json: async () => body }) as Response;
|
|
16
|
+
|
|
17
|
+
function setup(handler: (url: string, init: RequestInit, n: { refresh: number; api: number }) => Response | Promise<Response>) {
|
|
18
|
+
const data: Record<string, string> = { refresh: 'R0' };
|
|
19
|
+
const storage: SecretStore = {
|
|
20
|
+
getRefreshToken: async () => data.refresh ?? null,
|
|
21
|
+
setRefreshToken: async (t) => { data.refresh = t; },
|
|
22
|
+
clear: async () => { delete data.refresh; },
|
|
23
|
+
};
|
|
24
|
+
const n = { refresh: 0, api: 0 };
|
|
25
|
+
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
|
|
26
|
+
if (String(url).endsWith('/auth/token/refresh/')) n.refresh += 1; else n.api += 1;
|
|
27
|
+
return handler(String(url), init ?? {}, n);
|
|
28
|
+
});
|
|
29
|
+
const diag = { log: vi.fn() };
|
|
30
|
+
const session = createSession({ centralUrl: 'http://central', storage, fetch: fetchMock as never, diag });
|
|
31
|
+
return { session, fetchMock, diag, data, n };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
describe('token expiry', () => {
|
|
35
|
+
it('401 -> refresh -> retry succeeds, and the refresh is logged without any token value', async () => {
|
|
36
|
+
const s = setup((url, init, n) => {
|
|
37
|
+
if (url.endsWith('/auth/token/refresh/')) return res(200, { access: jwt(3600), refresh: 'R1' });
|
|
38
|
+
return (init.headers as Record<string, string>).Authorization?.includes('stale') ? res(401) : res(200, { ok: 1 });
|
|
39
|
+
});
|
|
40
|
+
// no access token yet: the client refreshes first (cold start after expiry)
|
|
41
|
+
const out = await s.session.authorizedFetch('http://tandem/x');
|
|
42
|
+
expect(out.status).toBe(200);
|
|
43
|
+
expect(s.data.refresh).toBe('R1');
|
|
44
|
+
expect(s.diag.log).toHaveBeenCalledWith('auth.refresh', { ok: true, status: 200 });
|
|
45
|
+
expect(JSON.stringify(s.diag.log.mock.calls)).not.toMatch(/R0|R1|Bearer/);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('an access token the API rejects (expired mid-session) refreshes again and retries exactly once', async () => {
|
|
49
|
+
let apiCalls = 0;
|
|
50
|
+
const s = setup((url) => {
|
|
51
|
+
if (url.endsWith('/auth/token/refresh/')) return res(200, { access: jwt(3600), refresh: 'Rn' });
|
|
52
|
+
apiCalls += 1;
|
|
53
|
+
return apiCalls === 1 ? res(401) : res(200, {});
|
|
54
|
+
});
|
|
55
|
+
const out = await s.session.authorizedFetch('http://tandem/x');
|
|
56
|
+
expect(out.status).toBe(200);
|
|
57
|
+
expect(s.n).toEqual({ refresh: 2, api: 2 });
|
|
58
|
+
expect(s.diag.log.mock.calls.filter((c) => c[0] === 'auth.refresh')).toHaveLength(2);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('refresh rejected by the server -> signedOut, logged ok:false with the status', async () => {
|
|
62
|
+
const s = setup((url) => (url.endsWith('/auth/token/refresh/') ? res(401, { detail: 'expired' }) : res(200)));
|
|
63
|
+
const states: string[] = [];
|
|
64
|
+
s.session.subscribe((x) => states.push(x));
|
|
65
|
+
await expect(s.session.authorizedFetch('http://tandem/x')).rejects.toThrow();
|
|
66
|
+
expect(s.session.getState()).toBe('signedOut');
|
|
67
|
+
expect(s.diag.log).toHaveBeenCalledWith('auth.refresh', expect.objectContaining({ ok: false, status: 401 }));
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('refresh fails on the network (airplane mode) -> logged, token kept, stays signed in', async () => {
|
|
71
|
+
const s = setup((url) => { if (url.endsWith('/auth/token/refresh/')) throw new TypeError('Network request failed'); return res(200); });
|
|
72
|
+
await s.session.restore();
|
|
73
|
+
expect(s.session.getState()).toBe('signedIn');
|
|
74
|
+
expect(s.data.refresh).toBe('R0');
|
|
75
|
+
expect(s.diag.log).toHaveBeenCalledWith('auth.refresh', expect.objectContaining({ ok: false, error: 'Network request failed' }));
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('an upload after expiry: refresh happens inside the queue attempt and the note is sent once', async () => {
|
|
79
|
+
const s = setup((url, init) => {
|
|
80
|
+
if (url.endsWith('/auth/token/refresh/')) return res(200, { access: jwt(3600), refresh: 'R1' });
|
|
81
|
+
return res(202);
|
|
82
|
+
});
|
|
83
|
+
const notes = createNotes({ tandemUrl: 'http://tandem', authorizedFetch: s.session.authorizedFetch, createForm: () => new FakeForm() as never });
|
|
84
|
+
let saved: string | null = null;
|
|
85
|
+
const removed: string[] = [];
|
|
86
|
+
const queue = createUploadQueue({
|
|
87
|
+
store: { read: async () => saved, write: async (v) => { saved = v; } },
|
|
88
|
+
upload: (job) => notes.upload({ id: job.id, uri: job.uri, durationMs: 1 }),
|
|
89
|
+
removeFile: async (job) => { removed.push(job.uri); },
|
|
90
|
+
});
|
|
91
|
+
expect(await queue.enqueue({ id: 'note-aaaa', uri: 'file:///d/a.m4a' })).toBe('sent');
|
|
92
|
+
expect(removed).toEqual(['file:///d/a.m4a']);
|
|
93
|
+
expect(s.n.refresh).toBe(1);
|
|
94
|
+
expect(s.diag.log).toHaveBeenCalledWith('auth.refresh', { ok: true, status: 200 });
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('refresh rejected during an upload: the note stays queued (never lost), session flips to signedOut', async () => {
|
|
98
|
+
const s = setup((url) => (url.endsWith('/auth/token/refresh/') ? res(401) : res(202)));
|
|
99
|
+
const notes = createNotes({ tandemUrl: 'http://tandem', authorizedFetch: s.session.authorizedFetch, createForm: () => new FakeForm() as never });
|
|
100
|
+
let saved: string | null = null;
|
|
101
|
+
const removed: string[] = [];
|
|
102
|
+
const queue = createUploadQueue({
|
|
103
|
+
store: { read: async () => saved, write: async (v) => { saved = v; } },
|
|
104
|
+
upload: (job) => notes.upload({ id: job.id, uri: job.uri, durationMs: 1 }),
|
|
105
|
+
removeFile: async (job) => { removed.push(job.uri); },
|
|
106
|
+
});
|
|
107
|
+
expect(await queue.enqueue({ id: 'note-bbbb', uri: 'file:///d/b.m4a' })).toBe('queued');
|
|
108
|
+
expect(removed).toEqual([]);
|
|
109
|
+
expect(await queue.pending()).toHaveLength(1);
|
|
110
|
+
expect(s.session.getState()).toBe('signedOut');
|
|
111
|
+
});
|
|
112
|
+
});
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createRecorder, type RecorderAudio } from '../recorder';
|
|
3
|
+
import { createRecorderAudio, type AudioDriver, type SessionInspector } from '../recorderAudio';
|
|
4
|
+
|
|
5
|
+
// bd startsim-150po.3: another app taking the mic ends the recording; when the
|
|
6
|
+
// system hands the session back the recorder starts a continuation note.
|
|
7
|
+
|
|
8
|
+
function audioSetup() {
|
|
9
|
+
const driver: AudioDriver = {
|
|
10
|
+
configureSession: vi.fn(async () => undefined),
|
|
11
|
+
create: vi.fn(),
|
|
12
|
+
prepare: vi.fn(async () => undefined),
|
|
13
|
+
record: vi.fn(),
|
|
14
|
+
stop: vi.fn(async () => undefined),
|
|
15
|
+
status: vi.fn(() => ({ url: 'file:///d/x.m4a', durationMillis: 9000, metering: -30, isRecording: true })),
|
|
16
|
+
};
|
|
17
|
+
const l: { interruption?: (e: { type: 'began' | 'ended'; shouldResume?: boolean }) => void } = {};
|
|
18
|
+
const session: SessionInspector = {
|
|
19
|
+
info: async () => ({ category: 'playAndRecord', mode: 'default', options: [], sampleRate: 48000, inputs: [] }),
|
|
20
|
+
onInterruption: (cb) => { l.interruption = cb as never; return () => { l.interruption = undefined; }; },
|
|
21
|
+
onRouteChange: () => () => undefined,
|
|
22
|
+
};
|
|
23
|
+
const onInterrupted = vi.fn();
|
|
24
|
+
const onInterruptionEnded = vi.fn();
|
|
25
|
+
const audio = createRecorderAudio({
|
|
26
|
+
driver, session, fs: { size: async () => 5000 }, poll: () => () => undefined, sleep: async () => undefined,
|
|
27
|
+
diag: { log: vi.fn() }, onInterrupted, onInterruptionEnded,
|
|
28
|
+
});
|
|
29
|
+
return { audio, l, onInterrupted, onInterruptionEnded };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe('audio adapter: interruption ended', () => {
|
|
33
|
+
it('reports ended (with shouldResume) AFTER the interrupted recording was finalized and stopped', async () => {
|
|
34
|
+
const s = audioSetup();
|
|
35
|
+
await s.audio.start({ onLevel: vi.fn() });
|
|
36
|
+
s.l.interruption!({ type: 'began' });
|
|
37
|
+
await s.audio.stop(); // what recorder.interrupt() does
|
|
38
|
+
s.l.interruption!({ type: 'ended', shouldResume: true });
|
|
39
|
+
expect(s.onInterruptionEnded).toHaveBeenCalledWith({ shouldResume: true });
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('ignores an ended that follows no interruption of ours', async () => {
|
|
43
|
+
const s = audioSetup();
|
|
44
|
+
await s.audio.start({ onLevel: vi.fn() });
|
|
45
|
+
await s.audio.stop();
|
|
46
|
+
s.l.interruption?.({ type: 'ended', shouldResume: true });
|
|
47
|
+
expect(s.onInterruptionEnded).not.toHaveBeenCalled();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('reports ended once', async () => {
|
|
51
|
+
const s = audioSetup();
|
|
52
|
+
await s.audio.start({ onLevel: vi.fn() });
|
|
53
|
+
s.l.interruption!({ type: 'began' });
|
|
54
|
+
await s.audio.stop();
|
|
55
|
+
s.l.interruption!({ type: 'ended', shouldResume: true });
|
|
56
|
+
s.l.interruption?.({ type: 'ended', shouldResume: true });
|
|
57
|
+
expect(s.onInterruptionEnded).toHaveBeenCalledTimes(1);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
function recorderSetup() {
|
|
62
|
+
let n = 0;
|
|
63
|
+
const audio: RecorderAudio = {
|
|
64
|
+
start: vi.fn(async () => undefined),
|
|
65
|
+
stop: vi.fn(async () => ({ uri: `file:///d/seg${++n}.m4a`, durationMs: 9000 })),
|
|
66
|
+
};
|
|
67
|
+
const sent: Array<{ id: string }> = [];
|
|
68
|
+
let releaseSend: (() => void) | null = null;
|
|
69
|
+
const send = vi.fn(async (f: { id: string }) => {
|
|
70
|
+
sent.push(f);
|
|
71
|
+
if (releaseSend === null && holdSend) await new Promise<void>((r) => { releaseSend = r; });
|
|
72
|
+
return 'sent' as const;
|
|
73
|
+
});
|
|
74
|
+
let holdSend = false;
|
|
75
|
+
const scheduled: Array<{ ms: number; fn: () => void }> = [];
|
|
76
|
+
let ids = 0;
|
|
77
|
+
const log = vi.fn();
|
|
78
|
+
const recorder = createRecorder({
|
|
79
|
+
audio, send, newId: () => `note-${++ids}`, diag: { log },
|
|
80
|
+
now: () => 0,
|
|
81
|
+
schedule: (fn, ms) => { scheduled.push({ fn, ms }); return () => undefined; },
|
|
82
|
+
});
|
|
83
|
+
return { recorder, audio, sent, scheduled, log, hold: () => { holdSend = true; }, release: () => releaseSend?.() };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
describe('recorder: resume after interruption', () => {
|
|
87
|
+
it('interrupted, then the system returns the session -> a NEW note starts recording', async () => {
|
|
88
|
+
const s = recorderSetup();
|
|
89
|
+
await s.recorder.go();
|
|
90
|
+
await s.recorder.interrupt('interruption');
|
|
91
|
+
expect(s.recorder.getState().phase).toBe('sent');
|
|
92
|
+
await s.recorder.resumeAfterInterruption({ shouldResume: true });
|
|
93
|
+
expect(s.audio.start).toHaveBeenCalledTimes(2);
|
|
94
|
+
expect(s.recorder.getState()).toMatchObject({ phase: 'recording', noteId: 'note-2' });
|
|
95
|
+
expect(s.log).toHaveBeenCalledWith('record.resumed', expect.objectContaining({ id: 'note-2', after: 'note-1' }));
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('shouldResume false -> stays stopped, logged', async () => {
|
|
99
|
+
const s = recorderSetup();
|
|
100
|
+
await s.recorder.go();
|
|
101
|
+
await s.recorder.interrupt('interruption');
|
|
102
|
+
await s.recorder.resumeAfterInterruption({ shouldResume: false });
|
|
103
|
+
expect(s.audio.start).toHaveBeenCalledTimes(1);
|
|
104
|
+
expect(s.log).toHaveBeenCalledWith('record.resume-skipped', expect.objectContaining({ shouldResume: false }));
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it('a missing shouldResume (Safari-style takeover) counts as resumable', async () => {
|
|
108
|
+
const s = recorderSetup();
|
|
109
|
+
await s.recorder.go();
|
|
110
|
+
await s.recorder.interrupt('interruption');
|
|
111
|
+
await s.recorder.resumeAfterInterruption({});
|
|
112
|
+
expect(s.recorder.getState().phase).toBe('recording');
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('no resume when the user stopped on their own', async () => {
|
|
116
|
+
const s = recorderSetup();
|
|
117
|
+
await s.recorder.go();
|
|
118
|
+
await s.recorder.stop();
|
|
119
|
+
await s.recorder.resumeAfterInterruption({ shouldResume: true });
|
|
120
|
+
expect(s.audio.start).toHaveBeenCalledTimes(1);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('a manual go() after the interruption clears the pending resume', async () => {
|
|
124
|
+
const s = recorderSetup();
|
|
125
|
+
await s.recorder.go();
|
|
126
|
+
await s.recorder.interrupt('interruption');
|
|
127
|
+
await s.recorder.go();
|
|
128
|
+
await s.recorder.stop();
|
|
129
|
+
await s.recorder.resumeAfterInterruption({ shouldResume: true });
|
|
130
|
+
expect(s.audio.start).toHaveBeenCalledTimes(2);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('the continuation keeps the autostop budget that was left', async () => {
|
|
134
|
+
let t = 0;
|
|
135
|
+
const s = recorderSetup();
|
|
136
|
+
const audio = s.audio;
|
|
137
|
+
const scheduled: Array<{ ms: number }> = [];
|
|
138
|
+
const recorder = createRecorder({
|
|
139
|
+
audio, send: async () => 'sent', newId: () => `n${t++}`, now: () => clock.v,
|
|
140
|
+
schedule: (_fn, ms) => { scheduled.push({ ms }); return () => undefined; },
|
|
141
|
+
});
|
|
142
|
+
const clock = { v: 0 };
|
|
143
|
+
await recorder.go({ autostopSeconds: 30 });
|
|
144
|
+
clock.v = 9000;
|
|
145
|
+
await recorder.interrupt('interruption');
|
|
146
|
+
await recorder.resumeAfterInterruption({ shouldResume: true });
|
|
147
|
+
expect(scheduled.map((x) => x.ms)).toEqual([30000, 21000]);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('a slow upload of the first segment does not clobber the continuation phase', async () => {
|
|
151
|
+
const s = recorderSetup();
|
|
152
|
+
s.hold();
|
|
153
|
+
await s.recorder.go();
|
|
154
|
+
const interrupting = s.recorder.interrupt('interruption'); // blocked in send
|
|
155
|
+
await vi.waitFor(() => expect(s.recorder.getState().phase).toBe('uploading'));
|
|
156
|
+
await s.recorder.resumeAfterInterruption({ shouldResume: true });
|
|
157
|
+
expect(s.recorder.getState().phase).toBe('recording');
|
|
158
|
+
s.release();
|
|
159
|
+
await interrupting;
|
|
160
|
+
expect(s.recorder.getState()).toMatchObject({ phase: 'recording', noteId: 'note-2' });
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('a route-change takeover resumes immediately on whatever input is left', async () => {
|
|
164
|
+
const s = recorderSetup();
|
|
165
|
+
await s.recorder.go();
|
|
166
|
+
await s.recorder.interrupt('route-change');
|
|
167
|
+
expect(s.recorder.getState()).toMatchObject({ phase: 'recording', noteId: 'note-2' });
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it('a resume whose start fails ends idle with the error and never throws', async () => {
|
|
171
|
+
const s = recorderSetup();
|
|
172
|
+
await s.recorder.go();
|
|
173
|
+
await s.recorder.interrupt('interruption');
|
|
174
|
+
(s.audio.start as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('mic busy'));
|
|
175
|
+
await s.recorder.resumeAfterInterruption({ shouldResume: true });
|
|
176
|
+
expect(s.recorder.getState()).toMatchObject({ phase: 'idle', error: 'mic busy' });
|
|
177
|
+
});
|
|
178
|
+
});
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createUploadQueue } from '@startsimpli/utils';
|
|
3
|
+
import { createUploadLifecycle, type AppStateName } from '../lifecycle';
|
|
4
|
+
|
|
5
|
+
// bd startsim-150po.2 / .4: delivery while backgrounded, offline, and across restarts.
|
|
6
|
+
|
|
7
|
+
function setup(opts: { startState?: AppStateName } = {}) {
|
|
8
|
+
let appState: AppStateName = opts.startState ?? 'active';
|
|
9
|
+
const appListeners = new Set<(s: AppStateName) => void>();
|
|
10
|
+
let now = 0;
|
|
11
|
+
let saved: string | null = null;
|
|
12
|
+
const net = { online: true, killOnBackground: false };
|
|
13
|
+
const uploaded: string[] = [];
|
|
14
|
+
const removed: string[] = [];
|
|
15
|
+
const bg = { begun: [] as string[], ended: [] as number[], expire: undefined as undefined | (() => void) };
|
|
16
|
+
const timers: Array<{ at: number; fn: () => void; cancelled: boolean }> = [];
|
|
17
|
+
const diag = { log: vi.fn() };
|
|
18
|
+
// eslint-disable-next-line prefer-const
|
|
19
|
+
let lifecycle: ReturnType<typeof createUploadLifecycle>;
|
|
20
|
+
const queue = createUploadQueue({
|
|
21
|
+
store: { read: async () => saved, write: async (v) => { saved = v; } },
|
|
22
|
+
upload: async (job) => {
|
|
23
|
+
// The wrapper owns the OS grace period around each upload.
|
|
24
|
+
await lifecycle.withBackgroundTime(`upload:${job.id}`, async () => {
|
|
25
|
+
if (!net.online) throw new TypeError('Network request failed');
|
|
26
|
+
if (net.killOnBackground && appState !== 'active') throw new TypeError('The network connection was lost.');
|
|
27
|
+
uploaded.push(job.id);
|
|
28
|
+
});
|
|
29
|
+
},
|
|
30
|
+
removeFile: async (job) => { removed.push(job.uri); },
|
|
31
|
+
now: () => now,
|
|
32
|
+
});
|
|
33
|
+
lifecycle = createUploadLifecycle({
|
|
34
|
+
queue,
|
|
35
|
+
appState: {
|
|
36
|
+
current: () => appState,
|
|
37
|
+
subscribe: (cb) => { appListeners.add(cb); return () => appListeners.delete(cb); },
|
|
38
|
+
},
|
|
39
|
+
background: {
|
|
40
|
+
begin: async (name, onExpire) => { bg.begun.push(name); bg.expire = onExpire; return bg.begun.length; },
|
|
41
|
+
end: async (id) => { bg.ended.push(id); },
|
|
42
|
+
},
|
|
43
|
+
now: () => now,
|
|
44
|
+
schedule: (fn, ms) => {
|
|
45
|
+
const t = { at: now + ms, fn, cancelled: false };
|
|
46
|
+
timers.push(t);
|
|
47
|
+
return () => { t.cancelled = true; };
|
|
48
|
+
},
|
|
49
|
+
diag,
|
|
50
|
+
});
|
|
51
|
+
lifecycle.start();
|
|
52
|
+
return {
|
|
53
|
+
queue, lifecycle, uploaded, removed, bg, net, diag,
|
|
54
|
+
setApp: (s: AppStateName) => { appState = s; appListeners.forEach((l) => l(s)); },
|
|
55
|
+
advance: async (ms: number) => {
|
|
56
|
+
// 1 s steps: a timer armed by an earlier tick fires in the same call
|
|
57
|
+
const step = ms > 120_000 ? ms : 1000;
|
|
58
|
+
for (let left = ms; left > 0; left -= step) {
|
|
59
|
+
now += Math.min(step, left);
|
|
60
|
+
for (const t of timers.filter((x) => !x.cancelled && x.at <= now)) { t.cancelled = true; t.fn(); }
|
|
61
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
timers,
|
|
65
|
+
/** JS is frozen while locked: the clock moves, no timer fires. */
|
|
66
|
+
suspend: (ms: number) => { now += ms; },
|
|
67
|
+
settle: () => new Promise((r) => setTimeout(r, 5)),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const job = { id: 'note-0001', uri: 'file:///d/a.m4a', durationMs: 383000 };
|
|
72
|
+
|
|
73
|
+
describe('upload lifecycle', () => {
|
|
74
|
+
it('a recording that ends while locked: the upload dies in the background and completes on the next foreground', async () => {
|
|
75
|
+
const s = setup({ startState: 'background' });
|
|
76
|
+
s.net.killOnBackground = true;
|
|
77
|
+
expect(await s.lifecycle.enqueue(job)).toBe('queued');
|
|
78
|
+
expect(s.uploaded).toEqual([]);
|
|
79
|
+
s.setApp('active');
|
|
80
|
+
await s.settle();
|
|
81
|
+
await s.advance(0);
|
|
82
|
+
// the 2 s backoff has not elapsed: nothing yet, but a retry is armed
|
|
83
|
+
expect(s.uploaded).toEqual([]);
|
|
84
|
+
await s.advance(2_100);
|
|
85
|
+
expect(s.uploaded).toEqual(['note-0001']);
|
|
86
|
+
expect(s.removed).toEqual(['file:///d/a.m4a']);
|
|
87
|
+
expect(await s.queue.pending()).toEqual([]);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('foreground after a long lock drains immediately (backoff already elapsed)', async () => {
|
|
91
|
+
const s = setup({ startState: 'background' });
|
|
92
|
+
s.net.killOnBackground = true;
|
|
93
|
+
await s.lifecycle.enqueue(job);
|
|
94
|
+
s.suspend(40 * 60_000);
|
|
95
|
+
s.setApp('active');
|
|
96
|
+
await s.settle();
|
|
97
|
+
expect(s.uploaded).toEqual(['note-0001']);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('asks the OS for background time around every upload and always gives it back', async () => {
|
|
101
|
+
const s = setup();
|
|
102
|
+
await s.lifecycle.enqueue(job);
|
|
103
|
+
expect(s.bg.begun).toEqual(['upload:note-0001']);
|
|
104
|
+
expect(s.bg.ended).toEqual([1]);
|
|
105
|
+
s.net.online = false;
|
|
106
|
+
await s.lifecycle.enqueue({ ...job, id: 'note-0002', uri: 'file:///d/b.m4a' });
|
|
107
|
+
expect(s.bg.ended).toEqual([1, 2]); // released even though the upload threw
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('when the OS expires the grace period the event is logged', async () => {
|
|
111
|
+
const s = setup();
|
|
112
|
+
let finish!: () => void;
|
|
113
|
+
const p = s.lifecycle.withBackgroundTime('x', () => new Promise<void>((r) => { finish = r; }));
|
|
114
|
+
await s.settle();
|
|
115
|
+
s.bg.expire!();
|
|
116
|
+
expect(s.diag.log).toHaveBeenCalledWith('upload.background-expired', expect.objectContaining({ name: 'x' }));
|
|
117
|
+
finish();
|
|
118
|
+
await p;
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('offline -> online with no foreground event: a retry timer drains the queue', async () => {
|
|
122
|
+
const s = setup();
|
|
123
|
+
s.net.online = false;
|
|
124
|
+
expect(await s.lifecycle.enqueue(job)).toBe('queued');
|
|
125
|
+
await s.advance(10_000);
|
|
126
|
+
expect(s.uploaded).toEqual([]); // still offline, still queued
|
|
127
|
+
expect((await s.queue.pending())).toHaveLength(1);
|
|
128
|
+
s.net.online = true;
|
|
129
|
+
await s.advance(30_000);
|
|
130
|
+
expect(s.uploaded).toEqual(['note-0001']);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('keeps retrying while anything is pending and stops arming when the queue is empty', async () => {
|
|
134
|
+
const s = setup();
|
|
135
|
+
s.net.online = false;
|
|
136
|
+
await s.lifecycle.enqueue(job);
|
|
137
|
+
await s.advance(5_000);
|
|
138
|
+
await s.advance(5_000);
|
|
139
|
+
expect(s.timers.filter((t) => !t.cancelled)).toHaveLength(1);
|
|
140
|
+
s.net.online = true;
|
|
141
|
+
await s.advance(60_000);
|
|
142
|
+
await s.settle();
|
|
143
|
+
expect(await s.queue.pending()).toEqual([]);
|
|
144
|
+
expect(s.timers.filter((t) => !t.cancelled)).toHaveLength(0);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('stop() unsubscribes from app state', async () => {
|
|
148
|
+
const s = setup({ startState: 'background' });
|
|
149
|
+
s.lifecycle.start();
|
|
150
|
+
s.lifecycle.stop();
|
|
151
|
+
s.net.killOnBackground = false;
|
|
152
|
+
await s.lifecycle.enqueue(job).catch(() => undefined);
|
|
153
|
+
s.setApp('active');
|
|
154
|
+
await s.settle();
|
|
155
|
+
expect(s.diag.log).not.toHaveBeenCalledWith('queue.drain', expect.objectContaining({ trigger: 'foreground' }));
|
|
156
|
+
});
|
|
157
|
+
});
|
|
@@ -43,3 +43,26 @@ describe('orphan recovery (app killed mid-recording)', () => {
|
|
|
43
43
|
expect(enqueue).toHaveBeenCalledTimes(1);
|
|
44
44
|
});
|
|
45
45
|
});
|
|
46
|
+
|
|
47
|
+
describe('kill mid-recording, relaunch (bd startsim-150po.4)', () => {
|
|
48
|
+
it('a recording the dead process never stopped is queued, uploaded once, and its file removed', async () => {
|
|
49
|
+
const { createUploadQueue } = await import('@startsimpli/utils');
|
|
50
|
+
let saved: string | null = null;
|
|
51
|
+
const uploaded: string[] = [];
|
|
52
|
+
const removed: string[] = [];
|
|
53
|
+
const queue = createUploadQueue({
|
|
54
|
+
store: { read: async () => saved, write: async (v) => { saved = v; } },
|
|
55
|
+
upload: async (job) => { uploaded.push(job.id); },
|
|
56
|
+
removeFile: async (job) => { removed.push(job.uri); },
|
|
57
|
+
});
|
|
58
|
+
const onDisk = [{ uri: 'file:///docs/ExpoAudio/A1B2C3D4-0000.m4a', bytes: 120000 }];
|
|
59
|
+
// launch 1 (after the kill) and launch 2 (user kills the app again before the upload): same result
|
|
60
|
+
for (let launch = 0; launch < 2; launch++) {
|
|
61
|
+
const queued = new Set((await queue.pending()).map((j) => j.uri));
|
|
62
|
+
await recoverOrphans({ list: async () => onDisk.filter((f) => !queued.has(f.uri)), enqueue: (j) => queue.enqueue(j), log: vi.fn() });
|
|
63
|
+
onDisk.splice(0, onDisk.length, ...onDisk.filter((f) => !removed.includes(f.uri)));
|
|
64
|
+
}
|
|
65
|
+
expect(uploaded).toEqual(['A1B2C3D4-0000']);
|
|
66
|
+
expect(removed).toEqual(['file:///docs/ExpoAudio/A1B2C3D4-0000.m4a']);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { UploadQueue } from '@startsimpli/utils';
|
|
2
|
+
|
|
3
|
+
export type AppStateName = 'active' | 'inactive' | 'background' | (string & {});
|
|
4
|
+
|
|
5
|
+
export interface BackgroundTasks {
|
|
6
|
+
/** UIApplication.beginBackgroundTask: a grace period for work already in flight. Resolves an opaque id. */
|
|
7
|
+
begin(name: string, onExpire: () => void): Promise<number>;
|
|
8
|
+
end(id: number): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* When queued voice notes get delivered. Three triggers, none of which needs the
|
|
13
|
+
* user: the app returning to the foreground, a retry timer armed at the next
|
|
14
|
+
* due job (offline -> online has no event in RN), and an OS grace period held
|
|
15
|
+
* around each upload so a recording that ends while locked can still finish.
|
|
16
|
+
*/
|
|
17
|
+
export function createUploadLifecycle(deps: {
|
|
18
|
+
queue: UploadQueue;
|
|
19
|
+
appState: { current(): AppStateName; subscribe(cb: (s: AppStateName) => void): () => void };
|
|
20
|
+
background: BackgroundTasks;
|
|
21
|
+
schedule?: (fn: () => void, ms: number) => () => void;
|
|
22
|
+
now?: () => number;
|
|
23
|
+
diag?: { log(event: string, fields?: Record<string, unknown>): void };
|
|
24
|
+
/** Never re-arm sooner than this (default 1 s). */
|
|
25
|
+
minRetryMs?: number;
|
|
26
|
+
}) {
|
|
27
|
+
const log = (e: string, f?: Record<string, unknown>) => deps.diag?.log(e, f);
|
|
28
|
+
const now = deps.now ?? Date.now;
|
|
29
|
+
const schedule = deps.schedule ?? ((fn, ms) => { const h = setTimeout(fn, ms); return () => clearTimeout(h); });
|
|
30
|
+
const minMs = deps.minRetryMs ?? 1000;
|
|
31
|
+
let unsubscribe: (() => void) | null = null;
|
|
32
|
+
let cancelTimer: (() => void) | null = null;
|
|
33
|
+
|
|
34
|
+
async function arm(): Promise<void> {
|
|
35
|
+
cancelTimer?.();
|
|
36
|
+
cancelTimer = null;
|
|
37
|
+
const pending = await deps.queue.pending();
|
|
38
|
+
if (pending.length === 0) return;
|
|
39
|
+
const next = Math.min(...pending.map((j) => j.nextAttemptAt));
|
|
40
|
+
cancelTimer = schedule(() => { void drain('retry'); }, Math.max(minMs, next - now()));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function drain(trigger: 'foreground' | 'retry' | 'launch'): Promise<void> {
|
|
44
|
+
log('queue.drain', { trigger });
|
|
45
|
+
try {
|
|
46
|
+
await deps.queue.drain();
|
|
47
|
+
} finally {
|
|
48
|
+
await arm();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
/** Wrap each upload: the OS keeps the process alive a while longer once the app is backgrounded. */
|
|
54
|
+
async withBackgroundTime<T>(name: string, work: () => Promise<T>): Promise<T> {
|
|
55
|
+
const id = await deps.background.begin(name, () => log('upload.background-expired', { name })).catch(() => null);
|
|
56
|
+
try {
|
|
57
|
+
return await work();
|
|
58
|
+
} finally {
|
|
59
|
+
if (id !== null) await deps.background.end(id).catch(() => undefined);
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
/** Same as queue.enqueue, but a note that could not be sent also arms the retry timer. */
|
|
63
|
+
async enqueue(job: Parameters<UploadQueue['enqueue']>[0]) {
|
|
64
|
+
try {
|
|
65
|
+
return await deps.queue.enqueue(job);
|
|
66
|
+
} finally {
|
|
67
|
+
await arm();
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
start() {
|
|
71
|
+
if (unsubscribe) return;
|
|
72
|
+
unsubscribe = deps.appState.subscribe((s) => { if (s === 'active') void drain('foreground'); });
|
|
73
|
+
void arm();
|
|
74
|
+
},
|
|
75
|
+
stop() {
|
|
76
|
+
unsubscribe?.();
|
|
77
|
+
unsubscribe = null;
|
|
78
|
+
cancelTimer?.();
|
|
79
|
+
cancelTimer = null;
|
|
80
|
+
},
|
|
81
|
+
drain,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
@@ -63,15 +63,20 @@ export function createRecorder(deps: Deps) {
|
|
|
63
63
|
let startedAt = 0;
|
|
64
64
|
let cancelAutostop: (() => void) | null = null;
|
|
65
65
|
let permission: Permission | 'unknown' = 'unknown';
|
|
66
|
+
/** Set when the system (not the user) ended a recording: what is needed to continue it. */
|
|
67
|
+
let pendingResume: { after: string; autostopLeftMs?: number } | null = null;
|
|
68
|
+
let autostopMs: number | undefined;
|
|
66
69
|
|
|
67
70
|
const set = (next: RecorderState) => {
|
|
68
71
|
state = next;
|
|
69
72
|
listeners.forEach((l) => l(state));
|
|
70
73
|
};
|
|
71
74
|
|
|
72
|
-
async function go(options: GoOptions = {}): Promise<void> {
|
|
73
|
-
|
|
75
|
+
async function go(options: GoOptions = {}, resumed?: { after: string }): Promise<void> {
|
|
76
|
+
// A continuation may start while the previous segment's upload is still in flight.
|
|
77
|
+
if (starting || state.phase === 'recording' || (state.phase === 'uploading' && !resumed)) return;
|
|
74
78
|
starting = true;
|
|
79
|
+
if (!resumed) pendingResume = null;
|
|
75
80
|
try {
|
|
76
81
|
if (deps.ensurePermission) {
|
|
77
82
|
try {
|
|
@@ -103,8 +108,9 @@ export function createRecorder(deps: Deps) {
|
|
|
103
108
|
return;
|
|
104
109
|
}
|
|
105
110
|
startedAt = now();
|
|
106
|
-
log('record.start', { id, permission });
|
|
111
|
+
log(resumed ? 'record.resumed' : 'record.start', { id, permission, ...(resumed ?? {}) });
|
|
107
112
|
set({ phase: 'recording', noteId: id, permission: permission === 'unknown' ? undefined : permission });
|
|
113
|
+
autostopMs = options.autostopSeconds ? options.autostopSeconds * 1000 : undefined;
|
|
108
114
|
if (options.autostopSeconds) {
|
|
109
115
|
log('record.autostop.scheduled', { id, seconds: options.autostopSeconds });
|
|
110
116
|
cancelAutostop = schedule(() => { void stop(); }, options.autostopSeconds * 1000);
|
|
@@ -142,10 +148,27 @@ export function createRecorder(deps: Deps) {
|
|
|
142
148
|
log('record.send-error', { id, error: e instanceof Error ? e.message : String(e) });
|
|
143
149
|
outcome = 'queued';
|
|
144
150
|
}
|
|
145
|
-
|
|
151
|
+
// A continuation may already be recording: the earlier upload must not overwrite that.
|
|
152
|
+
const current = state as RecorderState;
|
|
153
|
+
if (current.phase === 'uploading' && current.noteId === id) {
|
|
154
|
+
set({ phase: outcome, noteId: id, permission: current.permission, ...(silent ? { warning: 'no-audio' as const } : {}) });
|
|
155
|
+
}
|
|
146
156
|
return file;
|
|
147
157
|
}
|
|
148
158
|
|
|
159
|
+
/** The system gave the session back: continue as a new note, unless told not to. */
|
|
160
|
+
async function resumeAfterInterruption(e: { shouldResume?: boolean }): Promise<void> {
|
|
161
|
+
const pending = pendingResume;
|
|
162
|
+
if (!pending) return;
|
|
163
|
+
if (e.shouldResume === false) {
|
|
164
|
+
log('record.resume-skipped', { after: pending.after, shouldResume: false });
|
|
165
|
+
pendingResume = null;
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
pendingResume = null;
|
|
169
|
+
await go({ autostopSeconds: pending.autostopLeftMs !== undefined ? pending.autostopLeftMs / 1000 : undefined }, { after: pending.after });
|
|
170
|
+
}
|
|
171
|
+
|
|
149
172
|
return {
|
|
150
173
|
getState: () => state,
|
|
151
174
|
subscribe(listener: (s: RecorderState) => void) {
|
|
@@ -157,8 +180,17 @@ export function createRecorder(deps: Deps) {
|
|
|
157
180
|
/** The system took the mic (call, Siri, route loss): finalize and queue what we have. */
|
|
158
181
|
async interrupt(reason: string) {
|
|
159
182
|
if (state.phase !== 'recording') return;
|
|
160
|
-
|
|
161
|
-
|
|
183
|
+
const id = state.noteId!;
|
|
184
|
+
log('record.interrupted', { id, reason });
|
|
185
|
+
const elapsed = now() - startedAt;
|
|
186
|
+
const left = autostopMs !== undefined ? Math.max(1000, autostopMs - elapsed) : undefined;
|
|
187
|
+
// Armed before stop() so an 'ended' that arrives during the upload is not lost.
|
|
188
|
+
pendingResume = { after: id, autostopLeftMs: left };
|
|
189
|
+
const file = await stop();
|
|
190
|
+
if (!file) { pendingResume = null; return; }
|
|
191
|
+
// A lost route has no 'ended' event: carry on with whatever input is left.
|
|
192
|
+
if (reason === 'route-change') await resumeAfterInterruption({ shouldResume: true });
|
|
162
193
|
},
|
|
194
|
+
resumeAfterInterruption,
|
|
163
195
|
};
|
|
164
196
|
}
|
|
@@ -28,7 +28,7 @@ export interface SessionInfo {
|
|
|
28
28
|
/** AVAudioSession facts and events (real binding: the local tandem-audio-session module). */
|
|
29
29
|
export interface SessionInspector {
|
|
30
30
|
info(): Promise<SessionInfo>;
|
|
31
|
-
onInterruption(cb: (e: { type: 'began' | 'ended' }) => void): () => void;
|
|
31
|
+
onInterruption(cb: (e: { type: 'began' | 'ended'; shouldResume?: boolean }) => void): () => void;
|
|
32
32
|
onRouteChange(cb: (e: { reason: string; inputs?: SessionInfo['inputs'] }) => void): () => void;
|
|
33
33
|
}
|
|
34
34
|
|
|
@@ -45,6 +45,8 @@ export function createRecorderAudio(deps: {
|
|
|
45
45
|
sleep: (ms: number) => Promise<void>;
|
|
46
46
|
diag: { log(event: string, fields?: Record<string, unknown>): void };
|
|
47
47
|
onInterrupted: (reason: 'interruption' | 'route-change') => void;
|
|
48
|
+
/** The system handed the session back after an interruption that ended our recording. */
|
|
49
|
+
onInterruptionEnded?: (e: { shouldResume?: boolean }) => void;
|
|
48
50
|
/** A start step that has not answered by then counts as failed (default 8 s). */
|
|
49
51
|
stepTimeoutMs?: number;
|
|
50
52
|
}): RecorderAudio {
|
|
@@ -52,6 +54,10 @@ export function createRecorderAudio(deps: {
|
|
|
52
54
|
let tracker = createLevelTracker();
|
|
53
55
|
const cleanup: Array<() => void> = [];
|
|
54
56
|
const release = () => { cleanup.splice(0).forEach((fn) => fn()); };
|
|
57
|
+
// After an interruption the recording is stopped, but the 'ended' event still has to be heard.
|
|
58
|
+
let awaitingEnd = false;
|
|
59
|
+
let endWatch: (() => void) | null = null;
|
|
60
|
+
const dropEndWatch = () => { awaitingEnd = false; endWatch?.(); endWatch = null; };
|
|
55
61
|
|
|
56
62
|
async function settledSize(uri: string): Promise<number> {
|
|
57
63
|
let last = 0;
|
|
@@ -106,6 +112,7 @@ export function createRecorderAudio(deps: {
|
|
|
106
112
|
return {
|
|
107
113
|
async start({ onLevel }) {
|
|
108
114
|
tracker = createLevelTracker();
|
|
115
|
+
dropEndWatch();
|
|
109
116
|
await startWithRetry();
|
|
110
117
|
active = true;
|
|
111
118
|
|
|
@@ -123,7 +130,10 @@ export function createRecorderAudio(deps: {
|
|
|
123
130
|
cleanup.push(deps.session.onInterruption((e) => {
|
|
124
131
|
if (!active) return;
|
|
125
132
|
deps.diag.log('audio.interruption', e);
|
|
126
|
-
if (e.type === 'began')
|
|
133
|
+
if (e.type === 'began') {
|
|
134
|
+
awaitingEnd = true;
|
|
135
|
+
deps.onInterrupted('interruption');
|
|
136
|
+
}
|
|
127
137
|
}));
|
|
128
138
|
cleanup.push(deps.session.onRouteChange((e) => {
|
|
129
139
|
if (!active) return;
|
|
@@ -142,6 +152,14 @@ export function createRecorderAudio(deps: {
|
|
|
142
152
|
async stop(): Promise<StoppedRecording> {
|
|
143
153
|
active = false;
|
|
144
154
|
release();
|
|
155
|
+
if (awaitingEnd && !endWatch) {
|
|
156
|
+
endWatch = deps.session.onInterruption((e) => {
|
|
157
|
+
if (e.type !== 'ended' || !awaitingEnd) return;
|
|
158
|
+
deps.diag.log('audio.interruption', e);
|
|
159
|
+
dropEndWatch();
|
|
160
|
+
deps.onInterruptionEnded?.({ shouldResume: e.shouldResume });
|
|
161
|
+
});
|
|
162
|
+
}
|
|
145
163
|
const before = deps.driver.status();
|
|
146
164
|
await deps.driver.stop();
|
|
147
165
|
const uri = before.url ?? deps.driver.status().url ?? '';
|
|
@@ -8,11 +8,22 @@ export type SessionState = 'unknown' | 'signedOut' | 'signedIn';
|
|
|
8
8
|
* (in the Keychain); the password is used once and never stored. A failed
|
|
9
9
|
* refresh clears everything and flips to signedOut (the sign-in screen).
|
|
10
10
|
*/
|
|
11
|
-
export function createSession(deps: { centralUrl: string; storage: SecretStore; fetch?: typeof fetch; /** The app slug central auth knows (default 'tandem'). */ app?: string }) {
|
|
11
|
+
export function createSession(deps: { centralUrl: string; storage: SecretStore; fetch?: typeof fetch; /** The app slug central auth knows (default 'tandem'). */ app?: string; /** Receives 'auth.refresh' (ok, status or error - never a token). */ diag?: { log(event: string, fields?: Record<string, unknown>): void } }) {
|
|
12
|
+
const loggedFetch: typeof fetch = async (input, init) => {
|
|
13
|
+
const isRefresh = String(input).endsWith('/auth/token/refresh/');
|
|
14
|
+
try {
|
|
15
|
+
const res = await (deps.fetch ?? fetch)(input, init);
|
|
16
|
+
if (isRefresh) deps.diag?.log('auth.refresh', { ok: res.ok, status: res.status });
|
|
17
|
+
return res;
|
|
18
|
+
} catch (e) {
|
|
19
|
+
if (isRefresh) deps.diag?.log('auth.refresh', { ok: false, error: e instanceof Error ? e.message : String(e) });
|
|
20
|
+
throw e;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
12
23
|
const auth = new TokenAuthClient({
|
|
13
24
|
apiBaseUrl: deps.centralUrl,
|
|
14
25
|
storage: deps.storage,
|
|
15
|
-
fetch:
|
|
26
|
+
fetch: loggedFetch,
|
|
16
27
|
app: deps.app ?? 'tandem',
|
|
17
28
|
});
|
|
18
29
|
let state: SessionState = 'unknown';
|