@dobbykit/lib 0.0.0-stage → 0.4.13

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 (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +347 -2
  3. package/dist/analytics/index.d.ts +64 -0
  4. package/dist/analytics/index.d.ts.map +1 -0
  5. package/dist/analytics/index.js +175 -0
  6. package/dist/analytics/index.js.map +1 -0
  7. package/dist/api/client.d.ts +36 -0
  8. package/dist/api/client.d.ts.map +1 -0
  9. package/dist/api/client.js +228 -0
  10. package/dist/api/client.js.map +1 -0
  11. package/dist/api/codes.d.ts +4 -0
  12. package/dist/api/codes.d.ts.map +1 -0
  13. package/dist/api/codes.js +58 -0
  14. package/dist/api/codes.js.map +1 -0
  15. package/dist/api/contract.d.ts +12 -0
  16. package/dist/api/contract.d.ts.map +1 -0
  17. package/dist/api/contract.js +7 -0
  18. package/dist/api/contract.js.map +1 -0
  19. package/dist/api/copy.d.ts +13 -0
  20. package/dist/api/copy.d.ts.map +1 -0
  21. package/dist/api/copy.js +253 -0
  22. package/dist/api/copy.js.map +1 -0
  23. package/dist/api/errors.d.ts +26 -0
  24. package/dist/api/errors.d.ts.map +1 -0
  25. package/dist/api/errors.js +44 -0
  26. package/dist/api/errors.js.map +1 -0
  27. package/dist/api/index.d.ts +7 -0
  28. package/dist/api/index.d.ts.map +1 -0
  29. package/dist/api/index.js +7 -0
  30. package/dist/api/index.js.map +1 -0
  31. package/dist/api/query-client.d.ts +19 -0
  32. package/dist/api/query-client.d.ts.map +1 -0
  33. package/dist/api/query-client.js +52 -0
  34. package/dist/api/query-client.js.map +1 -0
  35. package/dist/api/stream.d.ts +11 -0
  36. package/dist/api/stream.d.ts.map +1 -0
  37. package/dist/api/stream.js +82 -0
  38. package/dist/api/stream.js.map +1 -0
  39. package/dist/crypto/index.d.ts +10 -0
  40. package/dist/crypto/index.d.ts.map +1 -0
  41. package/dist/crypto/index.js +85 -0
  42. package/dist/crypto/index.js.map +1 -0
  43. package/dist/form/index.d.ts +32 -0
  44. package/dist/form/index.d.ts.map +1 -0
  45. package/dist/form/index.js +88 -0
  46. package/dist/form/index.js.map +1 -0
  47. package/dist/format/date.d.ts +15 -0
  48. package/dist/format/date.d.ts.map +1 -0
  49. package/dist/format/date.js +109 -0
  50. package/dist/format/date.js.map +1 -0
  51. package/dist/format/index.d.ts +16 -0
  52. package/dist/format/index.d.ts.map +1 -0
  53. package/dist/format/index.js +123 -0
  54. package/dist/format/index.js.map +1 -0
  55. package/dist/offline/index.d.ts +13 -0
  56. package/dist/offline/index.d.ts.map +1 -0
  57. package/dist/offline/index.js +62 -0
  58. package/dist/offline/index.js.map +1 -0
  59. package/dist/search/engine.d.ts +56 -0
  60. package/dist/search/engine.d.ts.map +1 -0
  61. package/dist/search/engine.js +140 -0
  62. package/dist/search/engine.js.map +1 -0
  63. package/dist/search/index.d.ts +5 -0
  64. package/dist/search/index.d.ts.map +1 -0
  65. package/dist/search/index.js +5 -0
  66. package/dist/search/index.js.map +1 -0
  67. package/dist/search/readers.d.ts +47 -0
  68. package/dist/search/readers.d.ts.map +1 -0
  69. package/dist/search/readers.js +227 -0
  70. package/dist/search/readers.js.map +1 -0
  71. package/dist/search/text.d.ts +6 -0
  72. package/dist/search/text.d.ts.map +1 -0
  73. package/dist/search/text.js +80 -0
  74. package/dist/search/text.js.map +1 -0
  75. package/dist/search/usage.d.ts +15 -0
  76. package/dist/search/usage.d.ts.map +1 -0
  77. package/dist/search/usage.js +45 -0
  78. package/dist/search/usage.js.map +1 -0
  79. package/dist/session/index.d.ts +28 -0
  80. package/dist/session/index.d.ts.map +1 -0
  81. package/dist/session/index.js +140 -0
  82. package/dist/session/index.js.map +1 -0
  83. package/dist/storage/file.d.ts +3 -0
  84. package/dist/storage/file.d.ts.map +1 -0
  85. package/dist/storage/file.js +47 -0
  86. package/dist/storage/file.js.map +1 -0
  87. package/dist/storage/index.d.ts +42 -0
  88. package/dist/storage/index.d.ts.map +1 -0
  89. package/dist/storage/index.js +192 -0
  90. package/dist/storage/index.js.map +1 -0
  91. package/dist/sync/index.d.ts +51 -0
  92. package/dist/sync/index.d.ts.map +1 -0
  93. package/dist/sync/index.js +61 -0
  94. package/dist/sync/index.js.map +1 -0
  95. package/dist/telemetry/index.d.ts +39 -0
  96. package/dist/telemetry/index.d.ts.map +1 -0
  97. package/dist/telemetry/index.js +134 -0
  98. package/dist/telemetry/index.js.map +1 -0
  99. package/dist/webhooks/index.d.ts +14 -0
  100. package/dist/webhooks/index.d.ts.map +1 -0
  101. package/dist/webhooks/index.js +47 -0
  102. package/dist/webhooks/index.js.map +1 -0
  103. package/package.json +127 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Dobby Kit authors
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,348 @@
1
- # Temporary Holding Version
1
+ # @dobbykit/lib
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Client primitives. The API layer, because six products hand-rolled one.
4
+
5
+ ## What the audit found
6
+
7
+ `lib/api.ts` or `services/api.ts` existed in six families. None shared an error
8
+ convention, and reading them turned up two real bugs rather than mere
9
+ duplication:
10
+
11
+ | Product | Lines | State |
12
+ |---|---|---|
13
+ | app-j | 123 | own conventions |
14
+ | app-c | 88 | handled non-JSON and 204 correctly; errors untyped (`Error` with `.status` bolted on) |
15
+ | app-a | 59 | typed `ApiError`/`AuthError`, considered retry policy — **but custom headers silently dropped Content-Type** |
16
+ | app-d | 49 | **no `res.ok` check on 5 of 9 endpoints** — a 500 HTML page reached `res.json()` |
17
+ | dhairya11 | 23 | minimal |
18
+ | app-b | 2 | stub |
19
+
20
+ ## The contract
21
+
22
+ Errors are enveloped, successes are not:
23
+
24
+ ```ts
25
+ { success: false, error: string, code?: string, details?: { formErrors, fieldErrors }, requestId?: string }
26
+ ```
27
+
28
+ `error` is human text; branch on `code`, never on `error`. Every error the
29
+ server kit raises itself has one (`VALIDATION_FAILED`, `RATE_LIMITED`,
30
+ `INTERNAL_ERROR`, …). `requestId` is present when the server runs the
31
+ `requestId` middleware, and `ApiError.requestId` falls back to the
32
+ `X-Request-Id` header, so a user's report can be traced to the log line.
33
+
34
+ `client.send(path, init)` sends with the configured headers and credentials and
35
+ turns a 401 into `AuthError`, but returns every other Response untouched —
36
+ status, `redirected`, `url` — for a flow that follows a redirect and checks
37
+ where it landed. `toApiError(res)` turns a failed Response into the same
38
+ `ApiError` the other methods throw.
39
+
40
+ `ApiError.retryAfter` is the seconds until a retry can succeed, when the server
41
+ said so (a 429 from `rateLimit` does): from `Retry-After`, else `RateLimit-Reset`,
42
+ else `X-RateLimit-Reset`. Use it to say "try again in 30 seconds".
43
+
44
+ `ERROR_CODES` (and `type ErrorCode`) lists every code the server kit emits, so
45
+ an app's user-facing copy can be checked by the compiler rather than a test:
46
+
47
+ ```ts
48
+ import type { ErrorCode } from "@dobbykit/lib/api"
49
+ const copy = { ...appCopy, RATE_LIMITED: "Slow down a little." } satisfies Record<ErrorCode | AppErrorCode, string>
50
+ ```
51
+
52
+ `DEFAULT_ERROR_COPY` gives every one of those codes plain, product-neutral copy
53
+ (`{ title, detail, action }`), so an app writes copy only for its own codes and
54
+ the few it wants to phrase differently:
55
+
56
+ ```ts
57
+ import { DEFAULT_ERROR_COPY, errorCopy, type ErrorCode, type ErrorCopy } from "@dobbykit/lib/api"
58
+
59
+ export const COPY = {
60
+ ...DEFAULT_ERROR_COPY,
61
+ RATE_LIMITED: { title: "Easy there", detail: "Search again shortly.", action: "wait" },
62
+ PROVIDER_UNAVAILABLE: { title: "Store unavailable", detail: "Try another store.", action: "go_back" },
63
+ } satisfies Record<ErrorCode | AppErrorCode, ErrorCopy>
64
+
65
+ const { title, detail, action } = errorCopy(err.code, COPY) // unknown code -> INTERNAL_ERROR's copy
66
+ ```
67
+
68
+ `action` is one of `retry`, `wait`, `edit`, `sign_in`, `go_back`; pair `wait`
69
+ with `ApiError.retryAfter`. Need a product action? `ErrorCopy` is generic:
70
+ `satisfies Record<ErrorCode | AppErrorCode, ErrorCopy<ErrorAction | "new_search">>`,
71
+ and the spread defaults still fit. A new Dobby Kit code arrives with its default; a
72
+ new app code fails the build until it has copy.
73
+
74
+ Codes are UPPER_SNAKE, except `invalid_token` and `insufficient_scope`, whose
75
+ spelling RFC 6750 fixes. The server test fails if the server emits a code the
76
+ list is missing.
77
+
78
+ Asymmetric on purpose — it matches what app-a already serves, so existing routes
79
+ adopt it without rewriting, and success payloads stay directly usable with no
80
+ unwrapping at the call site.
81
+
82
+ `@dobbykit/server/http` writes exactly what `@dobbykit/lib/api` parses.
83
+
84
+ ## Use
85
+
86
+ ```ts
87
+ import { createApiClient, ApiError, AuthError } from "@dobbykit/lib/api"
88
+
89
+ export const api = createApiClient({
90
+ baseUrl: "/api",
91
+ onAuthError: () => { window.location.href = "/login" },
92
+ headers: async () => ({ Authorization: `Bearer ${await getToken()}` }),
93
+ })
94
+
95
+ await api.get<Transaction[]>("/transactions" + qs({ from, to, q: search }))
96
+ await api.post<Transaction>("/transactions", body)
97
+ await api.postForm<ImportResult>("/import", formData)
98
+ const pdf = await api.raw("/receipt/42/pdf")
99
+ ```
100
+
101
+ `qs` appends one `k=v` per array item (`tag=a&tag=b`). A one-item array is
102
+ `tag=a`, which the server's `parseQuery` reads as a string, not an array, so
103
+ declare an array-typed query field with `queryList(z.string())` from
104
+ `@dobbykit/server/http/query-list`.
105
+
106
+ Validation errors arrive structured, not as a JSON string inside a message:
107
+
108
+ ```ts
109
+ catch (e) {
110
+ if (e instanceof ApiError && e.code === "VALIDATION_FAILED") {
111
+ setFieldErrors(e.details?.fieldErrors ?? {})
112
+ }
113
+ }
114
+ ```
115
+
116
+ ### Typed client (Hono RPC)
117
+
118
+ When the API is a Hono app, `createRpcClient` gives end-to-end types: paths,
119
+ params, bodies and responses come from the server's routes (validated with
120
+ kit-server's `zValidator`). Pass `hc<AppType>` from `hono/client`; this
121
+ package does not depend on hono.
122
+
123
+ ```ts
124
+ // api/src/app.ts: Dobby Kit's groups and the app's own routes, one chain
125
+ const app = new Hono()
126
+ .route("/api/sessions", sessionRoutes(sessionOpts))
127
+ .post("/api/notes", zValidator("json", NoteInput), (c) => c.json(save(c.req.valid("json")), 201))
128
+ export type AppType = typeof app
129
+
130
+ // web/src/api.ts
131
+ import { hc } from "hono/client"
132
+ import { createRpcClient } from "@dobbykit/lib/api"
133
+ import type { AppType } from "../../api/src/app"
134
+
135
+ export const api = createRpcClient(hc<AppType>, {
136
+ baseUrl: "/",
137
+ onAuthError: () => { window.location.href = "/login" },
138
+ })
139
+
140
+ const note = await (await api.api.notes.$post({ json: { title: "Hi" } })).json()
141
+ await api.api.notes.$post({ json: { titel: "Hi" } }) // does not compile
142
+ ```
143
+
144
+ The fetch underneath is this module's: `headers()` and credentials, an
145
+ `x-request-id` per call, and a failed response throws (`AuthError` on 401,
146
+ `ApiError` from the envelope otherwise) instead of being returned, so `.json()`
147
+ is the success type. `retries` (default 0) retries a GET or HEAD on a network
148
+ error, 5xx, 408 or 429, keeping one request id; leave it at 0 under TanStack
149
+ Query, which already retries. `fetch` swaps the transport (a Worker service
150
+ binding, or `app.request` in tests).
151
+
152
+ **Timeouts.** `timeoutMs` bounds each attempt's wait for response headers;
153
+ `timeout(ms)` in hc's `init` replaces it for one call (`timeout(0)` turns it
154
+ off). A timed-out call throws `TimeoutError`: an `ApiError` with status 408
155
+ and code `TIMEOUT`, so `errorCopy` and `isRetryable` already handle it. A
156
+ timed-out GET or HEAD counts toward `retries`; anything else is never retried.
157
+ Your own `signal` still works and its abort is not turned into a timeout.
158
+
159
+ ```ts
160
+ export const api = createRpcClient(hc<AppType>, { baseUrl: "/", timeoutMs: 10_000 })
161
+ await api.api.reports.$get({}, { init: timeout(60_000) }) // a slow one
162
+ await api.api.notes.$get({}, { init: timeout(5_000, { signal }) }) // plus your own abort
163
+ ```
164
+
165
+ **Streaming.** The body is not timed, so a stream runs as long as it needs.
166
+ Read it as an async iterator with `readText` (chunks), `readNdjson<T>` (one
167
+ JSON value per line), `readSse` (server-sent events) or `readSseJson<T>` (each
168
+ event's data as JSON, stopping at `[DONE]`). That last one reads kit-ai's
169
+ `streamChat` response directly; breaking out of the loop cancels the body.
170
+
171
+ ```ts
172
+ import type { UIMessageChunk } from "ai"
173
+ const res = await api.api.chat.$post({ json: { messages } })
174
+ for await (const chunk of readSseJson<UIMessageChunk>(res)) {
175
+ if (chunk.type === "text-delta") append(chunk.delta)
176
+ }
177
+ ```
178
+
179
+ ### TanStack Query
180
+
181
+ ```ts
182
+ import { queryDefaults, onAuthErrorRedirect } from "@dobbykit/lib/api/query-client"
183
+
184
+ const client = new QueryClient({ defaultOptions: queryDefaults() })
185
+ onAuthErrorRedirect(client, () => { window.location.href = "/login" })
186
+ ```
187
+
188
+ `AuthError` is never retried — retrying a 401 only delays the redirect and fires
189
+ more requests at a dead session. A burst of parallel 401s redirects once.
190
+
191
+ Only transient failures are retried: network errors, 5xx, 408 and 429. A 400,
192
+ 403, 404 or 422 fails identically every time, so retrying it only delays the
193
+ error. A 429 waits the server's `Retry-After`. Pass `shouldRetry` to change
194
+ the filter, `maxRetries` to change the count.
195
+
196
+ ## Fixed here
197
+
198
+ - **Every response checks `res.ok`.** ipl skipped it on 5 of 9 endpoints.
199
+ - **Caller headers extend the defaults instead of replacing them.** app-a spread
200
+ caller options after the computed headers, so any custom header dropped
201
+ Content-Type. FormData still correctly sends none, so the browser sets the
202
+ multipart boundary.
203
+ - **Error bodies are read once as text, then parsed.** Calling `res.json()`
204
+ first consumes the stream, so a `res.text()` fallback comes back empty and the
205
+ real message is lost. This one was caught by the test suite, in this package's
206
+ own first draft.
207
+ - **204 and non-JSON bodies return undefined** instead of throwing a parse
208
+ error. app-c had this; app-a did not.
209
+ - **A non-JSON error body is never the message.** A Cloudflare 502 is a whole
210
+ HTML page, and it reached a toast as `err.message`. The message is the
211
+ envelope's `error`, else a bare string `error`, else a bare string `message`,
212
+ else `"Request failed (502 Bad Gateway)"` (`"(HTTP 502)"` without status
213
+ text). `ApiError.body` holds JSON only, so it is undefined for HTML or plain
214
+ text; use `client.send()` to read such a body.
215
+
216
+ ## Test
217
+
218
+ `bun run test` — 26 assertions, with `fetch` stubbed. Covers each bug above.
219
+
220
+ ## Format
221
+
222
+ ```ts
223
+ import { createCurrencyFormatter, createCompactCurrencyFormatter } from "@dobbykit/lib/format"
224
+
225
+ const money = createCurrencyFormatter("INR", "en-IN")
226
+ money(1234) // ₹1,234
227
+ money(1234.5, true) // ₹1,234.50
228
+
229
+ const compact = createCompactCurrencyFormatter("INR", "en-IN")
230
+ compact(1_200_000) // ₹12L
231
+ compact(35_000_000) // ₹3.5Cr
232
+ ```
233
+
234
+ `Intl` compact notation renders 12 lakh as "₹1.2M", which is wrong for Indian
235
+ numbering. Locales using the lakh/crore system get that scale; every other
236
+ locale falls through to `Intl`. Detection is by locale, not by currency — the
237
+ earlier version hardcoded it to INR.
238
+
239
+ The lakh/crore locales are `en-IN`, `hi`, `bn`, `ta`, `te`, `mr`, `gu`, `kn`,
240
+ `ml`, `pa`, `or` and `as`.
241
+
242
+ Currency formatters use each currency's own fraction digits when `exact` is
243
+ true: JPY 0, USD and INR 2, KWD and BHD 3. Amounts may be a number, a decimal
244
+ string or a `bigint`. For integer minor units (cents, paise, fils) pass
245
+ `{ minorUnits: true }`; a `bigint` is then formatted exactly, with no float:
246
+
247
+ ```ts
248
+ const usd = createCurrencyFormatter("USD", "en-US", { minorUnits: true })
249
+ usd(12345, true) // $123.45
250
+ usd(900719925474099312345n, true) // $9,007,199,254,740,993,123.45
251
+ createCurrencyFormatter("KWD", "en-US")(1.2345, true) // KWD 1.235
252
+ createCompactCurrencyFormatter("INR", "en-IN", 1, { minorUnits: true })(120_000_000n) // ₹12L
253
+ ```
254
+
255
+ The date formatters take `{ timeZone }` (an IANA zone) as a second argument,
256
+ to show an instant in the user's zone rather than the server's:
257
+ `createDateTimeFormatter("en-IN", { timeZone: "Asia/Kolkata" })`. A date-only
258
+ `"YYYY-MM-DD"` string is a calendar date and is not shifted by it.
259
+
260
+ Dates use `Intl` throughout. app-a pulled in `date-fns` for what the platform
261
+ already does.
262
+
263
+ ### Date arithmetic
264
+
265
+ ```ts
266
+ import { addDays, addMonths, startOfMonth, endOfMonth, differenceInCalendarDays } from "@dobbykit/lib/format"
267
+
268
+ addMonths(new Date(2026, 0, 31), 1) // Feb 28 2026 (Feb 29 in a leap year)
269
+ addDays(today, -7) // a week ago, same time of day
270
+ const range = [startOfMonth(d), endOfMonth(d)] // 00:00:00.000 → 23:59:59.999
271
+ differenceInCalendarDays(new Date(2026, 2, 9), new Date(2026, 2, 8)) // 1, even on a 23-hour DST day
272
+ startOfYear(d) // Jan 1st, 00:00:00.000
273
+
274
+ toDateOnly(new Date(2024, 11, 25, 23, 30)) // "2024-12-25", the local calendar date
275
+ parseDateOnly("2024-12-25") // local midnight on 25 Dec
276
+ parseDateOnly("2025-02-30") // invalid Date, not rolled into March
277
+ ```
278
+
279
+ `addDays`, `addMonths`, `startOfDay`, `startOfMonth`, `startOfYear`, `endOfMonth`,
280
+ `differenceInCalendarDays`, `isSameDay` and `isSameMonth` cover what app-a kept
281
+ `date-fns` for. They behave like date-fns' defaults: local time, a `Date` or
282
+ epoch ms in, a new `Date` out, the input never mutated. `addMonths` clamps to
283
+ the end of a shorter month. `differenceInCalendarDays` compares calendar dates,
284
+ not milliseconds / 86,400,000, which floors a spring-forward day to 0. Amounts
285
+ may be negative; fractions truncate. An invalid date gives an invalid Date, NaN
286
+ or false rather than throwing.
287
+
288
+ `toDateOnly` and `parseDateOnly` convert between a local calendar date and a
289
+ "YYYY-MM-DD" string, for date inputs, query strings and date-only API fields.
290
+ `new Date("2024-12-25")` is UTC midnight, which is 24 Dec anywhere west of UTC;
291
+ `parseDateOnly` gives local midnight, and returns an invalid Date for any other
292
+ shape or for an impossible date. `toDateOnly` gives "" for an invalid date. The
293
+ date formatters (`createDateFormatter`, `createDateShortFormatter`,
294
+ `createDateTimeFormatter`, `createRelativeTimeFormatter`) read a date-only
295
+ string the same way; a string with a time or zone parses as before. The relative
296
+ formatter counts a date-only string in calendar days ("yesterday", "today",
297
+ "tomorrow"), whatever the time of day.
298
+
299
+ ## Crypto: fail-closed field decryption
300
+
301
+ For apps that encrypt user data on the client (app-a's private mode). You
302
+ bring `decrypt`; `decryptFields` enforces the rule that is easy to get wrong:
303
+ a field that should be ciphertext and does not decrypt becomes `null`, never
304
+ passes through.
305
+
306
+ ```ts
307
+ import { decryptFields } from "@dobbykit/lib/crypto"
308
+
309
+ const { data, undecrypted } = await decryptFields(
310
+ payload,
311
+ ["transactions.description", "transactions.merchant.cleanName"],
312
+ {
313
+ decrypt: (ct) => decryptField(ct, key),
314
+ // Optional. Return false only for values that are certainly legacy plaintext.
315
+ isCiphertext: (v) => looksLikeAesGcmBase64(v),
316
+ },
317
+ )
318
+ // undecrypted: ["transactions.3.description", ...] (empty when all decrypted)
319
+ ```
320
+
321
+ - Paths are dot-separated; arrays are walked without an index.
322
+ - With no `isCiphertext`, every non-empty string at a path is treated as
323
+ ciphertext. A throwing `isCiphertext` also counts as ciphertext.
324
+ - Never throws, never mutates the input. A shared object decrypts under every
325
+ reference.
326
+
327
+ ## Webhooks: Standard Webhooks signatures
328
+
329
+ `@dobbykit/lib/webhooks` signs and verifies
330
+ [Standard Webhooks](https://www.standardwebhooks.com) with Web Crypto only, so
331
+ it runs on Workers, Node, Bun and Deno.
332
+
333
+ ```ts
334
+ import { verifyWebhook } from "@dobbykit/lib/webhooks"
335
+
336
+ app.post("/hooks/signet", async (c) => {
337
+ const body = await c.req.text() // the raw text: re-serialised JSON does not verify
338
+ if (!(await verifyWebhook(env.WEBHOOK_SECRET, c.req.raw.headers, body))) return c.text("bad signature", 401)
339
+ const id = c.req.header("webhook-id") // the same on every retry: dedupe on it
340
+ // ...
341
+ })
342
+ ```
343
+
344
+ `signWebhook({ secret, id, body })` returns the three headers; a list of
345
+ secrets signs with each, for rotation. `generateWebhookSecret()` makes a
346
+ `whsec_` secret. Timestamps further than 5 minutes from now fail
347
+ (`toleranceSeconds`). `headerPrefix: "svix"` verifies Svix and Resend.
348
+ kit-db's `createWebhooks` sends with it.
@@ -0,0 +1,64 @@
1
+ export type EventProps = Record<string, string | number | boolean | null | undefined>;
2
+ export type AnalyticsEvent = {
3
+ name: string;
4
+ props?: EventProps;
5
+ ts: number;
6
+ anonymousId?: string;
7
+ sessionId?: string;
8
+ userId?: string;
9
+ };
10
+ export type SessionState = {
11
+ id: string;
12
+ lastSeen: number;
13
+ };
14
+ export type AnalyticsContext = {
15
+ anonymousId: string;
16
+ sessionId: string;
17
+ userId?: string;
18
+ };
19
+ export declare function continueSession(prev: SessionState | null | undefined, now: number, timeoutMs?: number): SessionState;
20
+ export declare const ANALYTICS_HEADERS: {
21
+ readonly anonymousId: "x-signet-anonymous-id";
22
+ readonly sessionId: "x-signet-session-id";
23
+ };
24
+ export type Transport = (events: AnalyticsEvent[]) => void | Promise<void>;
25
+ export type AnalyticsConfig = {
26
+ transport?: Transport;
27
+ batchSize?: number;
28
+ flushIntervalMs?: number;
29
+ respectDoNotTrack?: boolean;
30
+ optOutKey?: string;
31
+ requireConsent?: boolean;
32
+ sessionTimeoutMs?: number;
33
+ traitKeys?: readonly string[];
34
+ storageKey?: string;
35
+ };
36
+ export declare function beaconTransport(url: string): Transport;
37
+ export declare function createAnalytics(config?: AnalyticsConfig): {
38
+ track: (name: string, props?: EventProps) => void;
39
+ flush: () => void;
40
+ pageview: (path?: string) => void;
41
+ identify: (id: string, traits?: EventProps) => void;
42
+ reset: () => void;
43
+ readonly context: AnalyticsContext;
44
+ headers: () => Record<string, string>;
45
+ optOut: () => void;
46
+ optIn: () => void;
47
+ readonly isOptedOut: boolean;
48
+ readonly pending: number;
49
+ };
50
+ export type Analytics = ReturnType<typeof createAnalytics>;
51
+ export declare const noopAnalytics: {
52
+ track: (name: string, props?: EventProps) => void;
53
+ flush: () => void;
54
+ pageview: (path?: string) => void;
55
+ identify: (id: string, traits?: EventProps) => void;
56
+ reset: () => void;
57
+ readonly context: AnalyticsContext;
58
+ headers: () => Record<string, string>;
59
+ optOut: () => void;
60
+ optIn: () => void;
61
+ readonly isOptedOut: boolean;
62
+ readonly pending: number;
63
+ };
64
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/analytics/index.ts"],"names":[],"mappings":"AAYA,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC,CAAA;AAErF,MAAM,MAAM,cAAc,GAAG;IAC3B,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,UAAU,CAAA;IAElB,EAAE,EAAE,MAAM,CAAA;IAEV,WAAW,CAAC,EAAE,MAAM,CAAA;IAEp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kB3B,gBAAgB;mBAOlB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;;;;;EA6BtC;AAED,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAA;AAG1D,eAAO,MAAM,aAAa;kBAvFH,MAAM,UAAU,UAAU;;sBAkB3B,MAAM;mBAUT,MAAM,WAAW,UAAU;;sBAkB3B,gBAAgB;mBAOlB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;;;;;CAkCO,CAAA"}
@@ -0,0 +1,175 @@
1
+ const randomId = () => globalThis.crypto?.randomUUID?.() ??
2
+ `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
3
+ export function continueSession(prev, now, timeoutMs = 30 * 60_000) {
4
+ if (prev && now - prev.lastSeen < timeoutMs && now >= prev.lastSeen)
5
+ return { id: prev.id, lastSeen: now };
6
+ return { id: randomId(), lastSeen: now };
7
+ }
8
+ export const ANALYTICS_HEADERS = {
9
+ anonymousId: "x-signet-anonymous-id",
10
+ sessionId: "x-signet-session-id",
11
+ };
12
+ function readJson(key) {
13
+ try {
14
+ const v = localStorage.getItem(key);
15
+ return v ? JSON.parse(v) : null;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ function writeStore(key, value) {
22
+ try {
23
+ value === null ? localStorage.removeItem(key) : localStorage.setItem(key, value);
24
+ }
25
+ catch {
26
+ }
27
+ }
28
+ function readStoredOptOut(key) {
29
+ try {
30
+ const v = localStorage.getItem(key);
31
+ return v === "1" ? true : v === null ? null : false;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ export function beaconTransport(url) {
38
+ return (events) => {
39
+ const body = JSON.stringify({ events });
40
+ try {
41
+ if (typeof navigator !== "undefined" && navigator.sendBeacon) {
42
+ navigator.sendBeacon(url, new Blob([body], { type: "application/json" }));
43
+ return;
44
+ }
45
+ }
46
+ catch {
47
+ }
48
+ void fetch(url, {
49
+ method: "POST",
50
+ headers: { "Content-Type": "application/json" },
51
+ body,
52
+ keepalive: true,
53
+ }).catch(() => { });
54
+ };
55
+ }
56
+ export function createAnalytics(config = {}) {
57
+ const batchSize = config.batchSize ?? 10;
58
+ const flushIntervalMs = config.flushIntervalMs ?? 5000;
59
+ const optOutKey = config.optOutKey ?? "signet-analytics-optout";
60
+ const timeoutMs = config.sessionTimeoutMs ?? 30 * 60_000;
61
+ const idKey = `${config.storageKey ?? "signet-analytics"}-id`;
62
+ const sessionKey = `${config.storageKey ?? "signet-analytics"}-session`;
63
+ const traitKeys = new Set(config.traitKeys ?? []);
64
+ let queue = [];
65
+ let timer = null;
66
+ let optedOut = readStoredOptOut(optOutKey) ?? config.requireConsent === true;
67
+ let anonymousId = readJson(idKey) ?? "";
68
+ let session = readJson(sessionKey);
69
+ let userId;
70
+ const context = (touch) => {
71
+ if (!anonymousId) {
72
+ anonymousId = randomId();
73
+ if (!suppressed())
74
+ writeStore(idKey, JSON.stringify(anonymousId));
75
+ }
76
+ const now = Date.now();
77
+ const next = continueSession(session, now, timeoutMs);
78
+ if (touch || next.id !== session?.id) {
79
+ session = next;
80
+ if (!suppressed())
81
+ writeStore(sessionKey, JSON.stringify(session));
82
+ }
83
+ return { anonymousId, sessionId: session.id, userId };
84
+ };
85
+ const dntSaysNo = () => config.respectDoNotTrack !== false &&
86
+ typeof navigator !== "undefined" &&
87
+ navigator.doNotTrack === "1";
88
+ const suppressed = () => optedOut || dntSaysNo();
89
+ const flush = () => {
90
+ if (timer) {
91
+ clearTimeout(timer);
92
+ timer = null;
93
+ }
94
+ if (!queue.length || !config.transport) {
95
+ queue = [];
96
+ return;
97
+ }
98
+ const batch = queue;
99
+ queue = [];
100
+ try {
101
+ void config.transport(batch);
102
+ }
103
+ catch {
104
+ }
105
+ };
106
+ const track = (name, props) => {
107
+ if (!config.transport || suppressed())
108
+ return;
109
+ queue.push({ name, props, ts: Date.now(), ...context(true) });
110
+ if (queue.length >= batchSize)
111
+ return flush();
112
+ if (!timer)
113
+ timer = setTimeout(flush, flushIntervalMs);
114
+ };
115
+ if (typeof document !== "undefined") {
116
+ document.addEventListener("visibilitychange", () => {
117
+ if (document.visibilityState === "hidden")
118
+ flush();
119
+ });
120
+ }
121
+ return {
122
+ track,
123
+ flush,
124
+ pageview: (path) => track("pageview", {
125
+ path: path ?? (typeof location !== "undefined" ? location.pathname : undefined),
126
+ referrer: typeof document !== "undefined" ? document.referrer || undefined : undefined,
127
+ }),
128
+ identify: (id, traits) => {
129
+ if (!id)
130
+ return;
131
+ userId = id;
132
+ const allowed = Object.fromEntries(Object.entries(traits ?? {}).filter(([k]) => traitKeys.has(k)));
133
+ track("$identify", allowed);
134
+ },
135
+ reset: () => {
136
+ flush();
137
+ userId = undefined;
138
+ anonymousId = "";
139
+ session = null;
140
+ writeStore(idKey, null);
141
+ writeStore(sessionKey, null);
142
+ },
143
+ get context() {
144
+ return context(false);
145
+ },
146
+ headers: () => {
147
+ if (suppressed())
148
+ return {};
149
+ const c = context(false);
150
+ return {
151
+ [ANALYTICS_HEADERS.anonymousId]: c.anonymousId,
152
+ [ANALYTICS_HEADERS.sessionId]: c.sessionId,
153
+ };
154
+ },
155
+ optOut: () => {
156
+ optedOut = true;
157
+ queue = [];
158
+ writeStore(idKey, null);
159
+ writeStore(sessionKey, null);
160
+ writeStore(optOutKey, "1");
161
+ },
162
+ optIn: () => {
163
+ optedOut = false;
164
+ writeStore(optOutKey, "0");
165
+ },
166
+ get isOptedOut() {
167
+ return suppressed();
168
+ },
169
+ get pending() {
170
+ return queue.length;
171
+ },
172
+ };
173
+ }
174
+ export const noopAnalytics = createAnalytics();
175
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/analytics/index.ts"],"names":[],"mappings":"AAiCA,MAAM,QAAQ,GAAG,GAAW,EAAE,CAC5B,UAAU,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE;IACjC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAA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ACvB,CAAC;QAKD,OAAO,EAAE,GAA2B,EAAE;YACpC,IAAI,UAAU,EAAE;gBAAE,OAAO,EAAE,CAAA;YAC3B,MAAM,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;YACxB,OAAO;gBACL,CAAC,iBAAiB,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,WAAW;gBAC9C,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,SAAS;aAC3C,CAAA;QACH,CAAC;QACD,MAAM,EAAE,GAAG,EAAE;YACX,QAAQ,GAAG,IAAI,CAAA;YACf,KAAK,GAAG,EAAE,CAAA;YAEV,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;YACvB,UAAU,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;YAC5B,UAAU,CAAC,SAAS,EAAE,GAAG,CAAC,CAAA;QAC5B,CAAC;QACD,KAAK,EAAE,GAAG,EAAE;YACV,QAAQ,GAAG,KAAK,CAAA;YAEhB,UAAU,CAAC,SAAS,EAAE,GAAG,CAAC,CAAA;QAC5B,CAAC;QACD,IAAI,UAAU;YACZ,OAAO,UAAU,EAAE,CAAA;QACrB,CAAC;QAED,IAAI,OAAO;YACT,OAAO,KAAK,CAAC,MAAM,CAAA;QACrB,CAAC;KACF,CAAA;AACH,CAAC;AAKD,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,EAAE,CAAA"}
@@ -0,0 +1,36 @@
1
+ import { ApiError, AuthError } from "./errors.js";
2
+ export type ApiClientOptions = {
3
+ baseUrl?: string;
4
+ credentials?: RequestCredentials;
5
+ headers?: () => Record<string, string> | Promise<Record<string, string>>;
6
+ onAuthError?: (error: AuthError) => void;
7
+ token?: () => Promise<string | null>;
8
+ refresh?: () => Promise<string | null>;
9
+ timeoutMs?: number;
10
+ };
11
+ export type QueryValue = string | number | boolean | null | undefined;
12
+ export declare function qs(params: Record<string, QueryValue | readonly QueryValue[]>): string;
13
+ export declare function createApiClient(opts?: ApiClientOptions): {
14
+ request: <T>(path: string, init?: RequestInit, isForm?: boolean) => Promise<T>;
15
+ get: <T>(path: string, init?: RequestInit) => Promise<T>;
16
+ post: <T>(path: string, body?: unknown, init?: RequestInit) => Promise<T>;
17
+ put: <T>(path: string, body?: unknown, init?: RequestInit) => Promise<T>;
18
+ patch: <T>(path: string, body?: unknown, init?: RequestInit) => Promise<T>;
19
+ delete: <T>(path: string, body?: unknown, init?: RequestInit) => Promise<T>;
20
+ postForm: <T>(path: string, body: FormData, init?: RequestInit) => Promise<T>;
21
+ send: (path: string, init?: RequestInit) => Promise<Response>;
22
+ raw: (path: string, init?: RequestInit) => Promise<Response>;
23
+ };
24
+ export type ApiClient = ReturnType<typeof createApiClient>;
25
+ export type RpcClientOptions = ApiClientOptions & {
26
+ retries?: number;
27
+ fetch?: typeof fetch;
28
+ timeoutMs?: number;
29
+ };
30
+ export declare function timeout(ms: number, init?: RequestInit): RequestInit;
31
+ export declare function createRpcClient<C>(hc: (baseUrl: string, options: {
32
+ fetch: typeof fetch;
33
+ }) => C, opts?: RpcClientOptions): C;
34
+ export declare function retryAfterSeconds(headers: Headers, now?: number): number | undefined;
35
+ export declare function toApiError(res: Response): Promise<ApiError>;
36
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAgB,MAAM,aAAa,CAAA;AAG/D,MAAM,MAAM,gBAAgB,GAAG;IAE7B,OAAO,CAAC,EAAE,MAAM,CAAA;IAEhB,WAAW,CAAC,EAAE,kBAAkB,CAAA;IAEhC,OAAO,CAAC,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAMxE,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI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