| 133 | } |
| 134 | |
| 135 | export function installUiLog(options: InstallUiLogOptions = {}): UiLogHandle { |
| 136 | const target = options.target ?? window; |
| 137 | const con = options.console ?? console; |
| 138 | const session = options.session ?? newSessionId(); |
| 139 | const page = `${target.location.pathname}${target.location.search}`; |
| 140 | const getProject = options.getProject ?? (() => activeProject |
| 141 | ?? new URLSearchParams(target.location.search).get('project') ?? ''); |
| 142 | // A project switch changes the address and keeps the page (K24): each line names the address it was written on. |
| 143 | const getPage = (): string => `${target.location.pathname}${target.location.search}`; |
| 144 | const buffer = options.buffer |
| 145 | ?? new UiLogBuffer({ page, getPage, session, getProject, transport: options.transport ?? httpUiLogTransport() }); |
| 146 | |
| 147 | let recording = false; |
| 148 | const guarded = (fn: () => void): void => { |
| 149 | if (recording) { |
| 150 | return; |
| 151 | } |
| 152 | recording = true; |
| 153 | try { |
| 154 | fn(); |
| 155 | } catch { |
| 156 | /* Recording must never break the call that was being recorded. */ |
| 157 | } finally { |
| 158 | recording = false; |
| 159 | } |
| 160 | }; |
| 161 | |
| 162 | const originals = new Map<UiLogLevel, (...args: unknown[]) => void>(); |
| 163 | for (const level of LEVELS) { |
| 164 | const original = con[level] as (...args: unknown[]) => void; |
| 165 | originals.set(level, original); |
| 166 | con[level] = (...args: unknown[]): void => { |
| 167 | original.apply(con, args); |
| 168 | guarded(() => { |
| 169 | const described = describeArgs(args); |
| 170 | buffer.record(level, 'console', described.message, { |
| 171 | project: getProject(), stack: described.stack, |
| 172 | }); |
| 173 | }); |
| 174 | }; |
| 175 | } |
| 176 | |
| 177 | const onError = (event: ErrorEvent): void => { |
| 178 | guarded(() => { |
| 179 | const described = describeReason(event.error); |
| 180 | buffer.record('error', 'window', event.message.length > 0 ? event.message : described.message, { |
| 181 | project: getProject(), |
| 182 | stack: described.stack, |
| 183 | url: event.filename, |
| 184 | line: event.lineno, |
| 185 | col: event.colno, |
| 186 | }); |
| 187 | }); |
| 188 | }; |
| 189 | const onRejection = (event: PromiseRejectionEvent): void => { |
| 190 | guarded(() => { |
| 191 | const described = describeReason(event.reason); |
| 192 | buffer.record('error', 'promise', described.message, { |