basalt-ui 2.12.0 → 2.13.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 (93) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/MIGRATING.md +39 -12
  3. package/agent/rules/basalt-state.md +1 -1
  4. package/agent/skills/basalt-app/SKILL.md +1 -1
  5. package/agent/templates/main.tpl +1 -0
  6. package/dist/cli/basalt-install.d.ts +10 -0
  7. package/dist/cli/basalt-install.d.ts.map +1 -0
  8. package/dist/cli/basalt-install.js +0 -0
  9. package/dist/cli/check-theme.js +1 -1
  10. package/dist/cli/doctor-upgrade.d.ts +3 -3
  11. package/dist/cli/doctor-upgrade.d.ts.map +1 -1
  12. package/dist/cli/doctor-upgrade.js +28 -44
  13. package/dist/cli/doctor.js +3 -3
  14. package/dist/cli/index.d.ts +4 -28
  15. package/dist/cli/index.d.ts.map +1 -1
  16. package/dist/cli/index.js +10 -49
  17. package/dist/cli/provider-tags.d.ts +12 -0
  18. package/dist/cli/provider-tags.d.ts.map +1 -0
  19. package/dist/cli/provider-tags.js +28 -0
  20. package/dist/cli/render-imports.d.ts +24 -0
  21. package/dist/cli/render-imports.d.ts.map +1 -0
  22. package/dist/cli/render-imports.js +74 -0
  23. package/dist/cli/router-wiring.d.ts +12 -0
  24. package/dist/cli/router-wiring.d.ts.map +1 -1
  25. package/dist/cli/router-wiring.js +18 -0
  26. package/dist/cli/source-text.d.ts +7 -0
  27. package/dist/cli/source-text.d.ts.map +1 -1
  28. package/dist/cli/source-text.js +34 -0
  29. package/dist/cli/sync.d.ts.map +1 -1
  30. package/dist/cli/sync.js +18 -13
  31. package/dist/guard/fonts-hint.d.ts +3 -0
  32. package/dist/guard/fonts-hint.d.ts.map +1 -0
  33. package/dist/guard/fonts-hint.js +4 -0
  34. package/dist/guard/index.d.ts +1 -1
  35. package/dist/guard/index.d.ts.map +1 -1
  36. package/dist/guard/index.js +2 -1
  37. package/dist/index.d.ts +3 -3
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +3 -1
  40. package/dist/provider/create-router.d.ts +57 -10
  41. package/dist/provider/create-router.d.ts.map +1 -1
  42. package/dist/provider/create-router.js +28 -17
  43. package/dist/provider/index.d.ts +2 -2
  44. package/dist/provider/index.d.ts.map +1 -1
  45. package/dist/provider/index.js +23 -7
  46. package/dist/query-client.d.ts +2 -62
  47. package/dist/query-client.d.ts.map +1 -1
  48. package/dist/query-client.js +13 -18
  49. package/dist/router-tanstack/search-store-warnings.d.ts +33 -0
  50. package/dist/router-tanstack/search-store-warnings.d.ts.map +1 -0
  51. package/dist/router-tanstack/search-store-warnings.js +77 -0
  52. package/dist/router-tanstack/search-store.d.ts +2 -5
  53. package/dist/router-tanstack/search-store.d.ts.map +1 -1
  54. package/dist/router-tanstack/search-store.js +111 -110
  55. package/dist/telemetry.d.ts +31 -2
  56. package/dist/telemetry.d.ts.map +1 -1
  57. package/dist/telemetry.js +32 -12
  58. package/dist/theme/ctl-theme.d.ts.map +1 -1
  59. package/dist/theme/ctl-theme.js +17 -30
  60. package/dist/theme/extend.d.ts +18 -0
  61. package/dist/theme/extend.d.ts.map +1 -0
  62. package/dist/theme/extend.js +6 -0
  63. package/dist/theme/index.d.ts.map +1 -1
  64. package/dist/theme/index.js +44 -84
  65. package/dist/unwrap.d.ts +29 -0
  66. package/dist/unwrap.d.ts.map +1 -0
  67. package/dist/unwrap.js +18 -0
  68. package/llms.txt +9 -5
  69. package/package.json +1 -1
  70. package/src/cli/basalt-install.ts +9 -0
  71. package/src/cli/check-theme.ts +1 -1
  72. package/src/cli/doctor-upgrade.ts +40 -61
  73. package/src/cli/doctor.ts +3 -3
  74. package/src/cli/index.ts +14 -71
  75. package/src/cli/provider-tags.ts +38 -0
  76. package/src/cli/render-imports.ts +104 -0
  77. package/src/cli/router-wiring.ts +23 -0
  78. package/src/cli/source-text.ts +39 -0
  79. package/src/cli/sync.ts +27 -21
  80. package/src/guard/fonts-hint.ts +2 -0
  81. package/src/guard/index.ts +2 -2
  82. package/src/index.ts +4 -2
  83. package/src/provider/create-router.tsx +103 -39
  84. package/src/provider/index.tsx +27 -9
  85. package/src/query-client.ts +20 -78
  86. package/src/router-tanstack/search-store-warnings.ts +120 -0
  87. package/src/router-tanstack/search-store.ts +200 -206
  88. package/src/telemetry.ts +71 -13
  89. package/src/theme/__snapshots__/plain-theme.test.ts.snap +2354 -0
  90. package/src/theme/ctl-theme.tsx +20 -19
  91. package/src/theme/extend.ts +18 -0
  92. package/src/theme/index.ts +50 -49
  93. package/src/unwrap.ts +44 -0
@@ -7,6 +7,7 @@
7
7
  import type { Finding, GuardConfig, GuardKind, GuardSeverity } from './types'
8
8
  import { vxFamilyOf } from '../common/vx-family'
9
9
  import { BASALT_VX_FAMILIES } from '../common/vx-families'
10
+ import { FONTS_CSS_HINT } from './fonts-hint'
10
11
  import { BASALT_VX_NAMES } from './vx-names'
11
12
 
12
13
  export type { Finding, GuardConfig, GuardKind, GuardSeverity }
@@ -2001,8 +2002,7 @@ export const GUARD_RULES = {
2001
2002
  'raw-font-family': {
2002
2003
  kind: 'raw-font-family',
2003
2004
  pattern: RAW_FONT_FAMILY,
2004
- message:
2005
- 'Route the font stack through createBasaltTheme(overrides, { fonts }) / the shipped --basalt-font-sans|head|mono vars instead of a hardcoded fontFamily literal.',
2005
+ message: `Route the font stack through createBasaltTheme(overrides, { fonts }) / the shipped --basalt-font-sans|head|mono vars instead of a hardcoded fontFamily literal (${FONTS_CSS_HINT}).`,
2006
2006
  },
2007
2007
  'off-identity-accent': {
2008
2008
  kind: 'off-identity-accent',
package/src/index.ts CHANGED
@@ -6,10 +6,12 @@
6
6
  * `docs/waves/v2-surface.md`.
7
7
  */
8
8
 
9
- export { BasaltProvider } from './provider'
9
+ export { BasaltProvider, type BasaltProviderProps } from './provider'
10
10
  export {
11
+ basaltRouterOptions,
11
12
  createBasaltRouter,
12
13
  type BasaltRouter,
14
+ type BasaltRouterOptions,
13
15
  type BasaltRouterContext,
14
16
  } from './provider/create-router'
15
17
  export type { BasaltEvent, ChatTurnEnd, ChatTurnTrace, Telemetry, TraceHeaders } from './telemetry'
@@ -47,7 +49,7 @@ export {
47
49
  SettingsRow,
48
50
  DangerZone,
49
51
  } from './dashboard'
50
- export { unwrap } from './query-client'
52
+ export { unwrap } from './unwrap'
51
53
 
52
54
  // The one augmentable seam: `declare module 'basalt-ui' { interface BasaltRegister { … } }` only
53
55
  // merges when the entry exports the interface. `v2-surface.md` marks it `delete` (no consumer
@@ -1,7 +1,7 @@
1
1
  /**
2
- * `createBasaltRouter` — the router + QueryClient wiring (V2-SPEC § 2). One `QueryClient` per call
3
- * (so an SSR entry gets one per request), carried on `context.queryClient`, plus the router
4
- * defaults basalt owns: intent preloading with Query-owned freshness, scroll restoration, the
2
+ * `basaltRouterOptions` / `createBasaltRouter` — the router + QueryClient wiring (V2-SPEC § 2). One
3
+ * `QueryClient` per call (so an SSR entry gets one per request), carried on `context.queryClient`,
4
+ * plus the router defaults basalt owns: intent preloading with Query-owned freshness, scroll restoration, the
5
5
  * pending / error / not-found components, and the route view transition (direction from the
6
6
  * `BasaltShell` nav order, V2-SPEC § 5).
7
7
  */
@@ -11,7 +11,7 @@ import { Router, createRouter } from '@tanstack/react-router'
11
11
  import type { AnyRoute, ErrorComponentProps, RouterHistory } from '@tanstack/react-router'
12
12
  import { toErrorMessage } from '../common/errors'
13
13
  import { makeQueryClient } from '../query-client'
14
- import { errorName, now, routerTelemetry } from '../telemetry'
14
+ import type { RouterHook } from '../telemetry'
15
15
  import {
16
16
  guardViewTransitionRejections,
17
17
  routeViewTransition,
@@ -21,6 +21,8 @@ import {
21
21
  /** The root route's context: `createRootRouteWithContext<BasaltRouterContext>()`. */
22
22
  export type BasaltRouterContext = {
23
23
  queryClient: QueryClient
24
+ /** Set by `basaltRouterOptions`; the mounted provider points `onRouteError` at its emitter. */
25
+ __basalt?: RouterHook
24
26
  }
25
27
 
26
28
  type BasaltRouterBase<TRouteTree extends AnyRoute> = Router<
@@ -80,36 +82,69 @@ function NotFoundComponent() {
80
82
  )
81
83
  }
82
84
 
85
+ /** The options `createBasaltRouter` owns. Each is `never` on it: basalt's, not a consumer knob. */
86
+ type ManagedKeys = Exclude<keyof BasaltRouterOptions, 'context'>
87
+
88
+ /** `queryClient` and `__basalt` are basalt's: a consumer's would be replaced, so the type rejects them. */
89
+ type ExtraContext = { queryClient?: never; __basalt?: never }
90
+ type NoContext = Record<never, never>
91
+
92
+ type RouterOptionsInput<TContext extends object> = {
93
+ /** Context beyond `queryClient`; the root route's context type extends `BasaltRouterContext`. */
94
+ context?: (TContext & ExtraContext) | undefined
95
+ /** Merged over basalt's QueryClient defaults (`staleTime` 30 s, `gcTime` 5 min, `retry` twice, never a 4xx but 408/425/429, no refetch on focus). */
96
+ query?: QueryClientConfig | undefined
97
+ }
98
+
99
+ /** What `basaltRouterOptions` returns: the router options basalt owns, plus the context. */
100
+ export type BasaltRouterOptions<TContext extends object = NoContext> = {
101
+ context: TContext & BasaltRouterContext
102
+ defaultPreload: 'intent'
103
+ defaultPreloadStaleTime: number
104
+ scrollRestoration: boolean
105
+ /** Route transitions are basalt's (V2-SPEC § 5): the router's own would double them. */
106
+ defaultViewTransition: typeof routeViewTransition | false
107
+ defaultPendingComponent: typeof PendingComponent
108
+ defaultErrorComponent: typeof ErrorComponent
109
+ defaultNotFoundComponent: typeof NotFoundComponent
110
+ defaultOnCatch: (error: unknown) => void
111
+ }
112
+
83
113
  /**
114
+ * Everything `createBasaltRouter` sets, for a router the app builds itself (TanStack Start's
115
+ * `getRouter()`): spread it into `createRouter`, and the provider mounted inside gets `route.error`
116
+ * telemetry, intent preloading, the route transition and the default pending/error/not-found UI.
117
+ * A `TContext` with required keys makes `context` required. Spread it LAST: the keys are basalt's.
84
118
  * Side effect, once per document: wraps `document.startViewTransition` so a skipped route
85
119
  * transition (`AbortError`) never becomes an unhandled rejection (`guardViewTransitionRejections`).
86
- * Nothing else global is touched.
87
120
  *
88
121
  * @example
89
- * const router = createBasaltRouter({ routeTree })
90
- * declare module '@tanstack/react-router' {
91
- * interface Register { router: typeof router }
92
- * }
93
- * // extra context (argo's auth) extends BasaltRouterContext:
94
- * const router = createBasaltRouter({ routeTree, context: { auth }, query: { queryCache } })
122
+ * export const getRouter = () => createRouter({ routeTree, ...basaltRouterOptions() })
95
123
  */
96
- export function createBasaltRouter<
97
- TRouteTree extends AnyRoute,
98
- TContext extends object = Record<never, never>,
99
- >(options: {
100
- routeTree: TRouteTree
101
- /** Context beyond `queryClient`; the root route's context type extends `BasaltRouterContext`. */
102
- context?: TContext
103
- /** Merged over basalt's QueryClient defaults (`staleTime` 30 s, `gcTime` 5 min, `retry` 2, no refetch on focus). */
104
- query?: QueryClientConfig
105
- /** Route transitions are basalt's (V2-SPEC § 5): the router's would double them. */
106
- defaultViewTransition?: never
107
- }): BasaltRouter<TRouteTree> {
124
+ export function basaltRouterOptions(options?: RouterOptionsInput<NoContext>): BasaltRouterOptions
125
+ export function basaltRouterOptions<TContext extends object>(
126
+ options: RouterOptionsInput<TContext> & { context: TContext & ExtraContext },
127
+ ): BasaltRouterOptions<TContext>
128
+ export function basaltRouterOptions<TContext extends object>(
129
+ options: RouterOptionsInput<TContext> = {},
130
+ ): BasaltRouterOptions<TContext> {
131
+ return buildRouterOptions(options)
132
+ }
133
+
134
+ function buildRouterOptions<TContext extends object>(
135
+ options: RouterOptionsInput<TContext>,
136
+ ): BasaltRouterOptions<TContext> {
108
137
  guardViewTransitionRejections()
109
- const queryClient = makeQueryClient(options.query)
110
- const router: BasaltRouterBase<TRouteTree> = createRouter({
111
- routeTree: options.routeTree,
112
- context: { ...options.context, queryClient },
138
+ const hook: RouterHook = {}
139
+ // The overloads of `basaltRouterOptions` and `createBasaltRouter` make `context` present whenever
140
+ // `TContext` has required keys, so the spread is the whole `TContext`: the one cast, here.
141
+ const context = {
142
+ ...options.context,
143
+ queryClient: makeQueryClient(options.query),
144
+ __basalt: hook,
145
+ } as TContext & BasaltRouterContext
146
+ return {
147
+ context,
113
148
  defaultPreload: 'intent',
114
149
  // Query owns freshness: a preload must not be cached a second time by the router.
115
150
  defaultPreloadStaleTime: 0,
@@ -120,19 +155,48 @@ export function createBasaltRouter<
120
155
  defaultPendingComponent: PendingComponent,
121
156
  defaultErrorComponent: ErrorComponent,
122
157
  defaultNotFoundComponent: NotFoundComponent,
123
- defaultOnCatch: (error: unknown) => {
124
- if (process.env.NODE_ENV !== 'production') console.error('[basalt] route error', error)
125
- routerTelemetry(router)({
126
- type: 'route.error',
127
- failed: true,
128
- start: now(),
129
- attributes: {
130
- 'basalt.route.id': router.state.matches.at(-1)?.routeId ?? 'unknown',
131
- 'exception.type': errorName(error),
132
- 'basalt.error.kind': 'route',
133
- },
134
- })
158
+ defaultOnCatch: (error) => {
159
+ // Unbound (before the provider's first effect): the console is the only report, in every env.
160
+ if (process.env.NODE_ENV !== 'production' || !hook.onRouteError)
161
+ console.error('[basalt] route error', error)
162
+ hook.onRouteError?.(error)
135
163
  },
164
+ }
165
+ }
166
+
167
+ type CreateRouterInput<TRouteTree extends AnyRoute> = {
168
+ routeTree: TRouteTree
169
+ history?: RouterHistory
170
+ basepath?: string
171
+ } & { [K in ManagedKeys]?: never }
172
+
173
+ /**
174
+ * @example
175
+ * const router = createBasaltRouter({ routeTree })
176
+ * declare module '@tanstack/react-router' {
177
+ * interface Register { router: typeof router }
178
+ * }
179
+ * // extra context (argo's auth) extends BasaltRouterContext:
180
+ * const router = createBasaltRouter({ routeTree, context: { auth }, query: { queryCache } })
181
+ */
182
+ export function createBasaltRouter<TRouteTree extends AnyRoute>(
183
+ options: CreateRouterInput<TRouteTree> & RouterOptionsInput<NoContext>,
184
+ ): BasaltRouter<TRouteTree>
185
+ export function createBasaltRouter<TRouteTree extends AnyRoute, TContext extends object>(
186
+ options: CreateRouterInput<TRouteTree> &
187
+ RouterOptionsInput<TContext> & { context: TContext & ExtraContext },
188
+ ): BasaltRouter<TRouteTree>
189
+ export function createBasaltRouter<TRouteTree extends AnyRoute, TContext extends object>({
190
+ routeTree,
191
+ context,
192
+ query,
193
+ ...passthrough
194
+ }: CreateRouterInput<TRouteTree> & RouterOptionsInput<TContext>): BasaltRouter<TRouteTree> {
195
+ const router: BasaltRouterBase<TRouteTree> = createRouter({
196
+ ...passthrough,
197
+ routeTree,
198
+ ...buildRouterOptions<TContext>({ context, query }),
136
199
  })
200
+ // The brand is type-level only (see `BasaltRouter`), so the one cast adds nothing at runtime.
137
201
  return router as BasaltRouter<TRouteTree>
138
202
  }
@@ -36,9 +36,11 @@ import { SizeClassHintContext } from '../shell/use-size-class'
36
36
  import type { SizeClass } from '../shell/use-size-class'
37
37
  import {
38
38
  TelemetryContext,
39
- bindRouterTelemetry,
39
+ bindRouteError,
40
40
  createLiveEmitter,
41
+ devConsoleSink,
41
42
  errorName,
43
+ groupingId,
42
44
  now,
43
45
  } from '../telemetry'
44
46
  import type { Telemetry } from '../telemetry'
@@ -54,7 +56,7 @@ type BasaltProviderCommonProps = {
54
56
  /**
55
57
  * Typed events (V2-SPEC § 7) — navigations, route/query/mutation/render/window errors. Called
56
58
  * synchronously and wrapped in `try/catch`, so a throwing sink never breaks a render. Events carry
57
- * ids, hashes, counts and durations only; no sink, no events.
59
+ * ids, hashes, counts and durations only. No sink, no events in production; in development an unset sink logs query and mutation failures to the console.
58
60
  */
59
61
  telemetry?: Telemetry
60
62
  /** The root error boundary's UI. Unset → a minimal page with a reload button; `null` renders nothing. */
@@ -101,7 +103,7 @@ type BasaltProviderCommonProps = {
101
103
  * Two modes, never both: pass a `createBasaltRouter` `router` and the provider mounts it, or pass
102
104
  * `children` and render the provider INSIDE a router the app does not own (around the `<Outlet />`
103
105
  * of TanStack Start's root route component) — the router then comes from `useRouter()` and must carry
104
- * `context.queryClient` (its `getRouter()` builds the same context `createBasaltRouter` does).
106
+ * `context.queryClient`: spread `basaltRouterOptions()` into its `createRouter` (Start's `getRouter()`).
105
107
  */
106
108
  export type BasaltProviderProps = BasaltProviderCommonProps &
107
109
  (
@@ -354,7 +356,20 @@ function useWindowErrors(emit: Telemetry): void {
354
356
  /** Router navigations and the QueryClient's caches → `route.*`, `query.error`, `mutation.error`. */
355
357
  function useDataTelemetry(router: AnyRouter, client: QueryClient, emit: Telemetry): void {
356
358
  useEffect(() => {
357
- const unbind = bindRouterTelemetry(router, emit)
359
+ // `basaltRouterOptions`' `defaultOnCatch` reports to the handler bound here.
360
+ const routeId = (): string => router.state.matches.at(-1)?.routeId ?? 'unknown'
361
+ const onRouteError = (error: unknown): void =>
362
+ emit({
363
+ type: 'route.error',
364
+ failed: true,
365
+ start: now(),
366
+ attributes: {
367
+ 'basalt.route.id': routeId(),
368
+ 'exception.type': errorName(error),
369
+ 'basalt.error.kind': 'route',
370
+ },
371
+ })
372
+ const unbind = bindRouteError(router, onRouteError)
358
373
 
359
374
  // Keyed by the target href: a newer navigation overwrites, and a resolve for any other target
360
375
  // (a superseded or redirected navigation) is dropped rather than paired with the wrong start.
@@ -372,7 +387,7 @@ function useDataTelemetry(router: AnyRouter, client: QueryClient, emit: Telemetr
372
387
  start,
373
388
  duration: now() - start,
374
389
  attributes: {
375
- 'basalt.route.id': router.state.matches.at(-1)?.routeId ?? 'unknown',
390
+ 'basalt.route.id': routeId(),
376
391
  'basalt.route.from': from,
377
392
  'url.path': ev.toLocation.pathname,
378
393
  },
@@ -386,7 +401,7 @@ function useDataTelemetry(router: AnyRouter, client: QueryClient, emit: Telemetr
386
401
  failed: true,
387
402
  start: now(),
388
403
  attributes: {
389
- 'basalt.query.hash': ev.query.queryHash,
404
+ 'basalt.query.hash': groupingId(ev.query.queryHash),
390
405
  'basalt.query.failure_count': ev.query.state.fetchFailureCount,
391
406
  'exception.type': errorName(ev.action.error),
392
407
  'basalt.error.kind': 'query',
@@ -400,7 +415,9 @@ function useDataTelemetry(router: AnyRouter, client: QueryClient, emit: Telemetr
400
415
  failed: true,
401
416
  start: now(),
402
417
  attributes: {
403
- 'basalt.mutation.key': JSON.stringify(ev.mutation.options.mutationKey ?? null),
418
+ 'basalt.mutation.key': groupingId(
419
+ JSON.stringify(ev.mutation.options.mutationKey ?? null),
420
+ ),
404
421
  'exception.type': errorName(ev.action.error),
405
422
  'basalt.error.kind': 'mutation',
406
423
  },
@@ -472,9 +489,10 @@ export function BasaltProvider({
472
489
  useHostAttribute()
473
490
 
474
491
  // The sink is read through a ref, so an inline `telemetry` function does not re-subscribe.
475
- const sinkRef = useRef(telemetry)
492
+ const sink = telemetry ?? (process.env.NODE_ENV === 'production' ? undefined : devConsoleSink)
493
+ const sinkRef = useRef(sink)
476
494
  useEffect(() => {
477
- sinkRef.current = telemetry
495
+ sinkRef.current = sink
478
496
  })
479
497
  const emit = useMemo(() => createLiveEmitter(() => sinkRef.current), [])
480
498
  useWindowErrors(emit)
@@ -1,14 +1,31 @@
1
1
  /**
2
- * `unwrap` plus the QueryClient factory `createBasaltRouter` owns (V2-SPEC § 2): one client per
3
- * router, so an SSR entry gets one per request. Optional peer: @tanstack/react-query.
2
+ * The QueryClient factory `basaltRouterOptions` owns (V2-SPEC § 2): one client per router, so an
3
+ * SSR entry gets one per request. Optional peer: @tanstack/react-query.
4
4
  */
5
5
  import { QueryClient } from '@tanstack/react-query'
6
6
  import type { QueryClientConfig } from '@tanstack/react-query'
7
7
 
8
+ const MAX_RETRIES = 2
9
+ /** The 4xx that are transient: request timeout, too early, too many requests. */
10
+ const TRANSIENT_4XX: ReadonlySet<number> = new Set([408, 425, 429])
11
+
12
+ const statusOf = (error: unknown): number | undefined => {
13
+ if (typeof error !== 'object' || error === null || !('status' in error)) return undefined
14
+ return typeof error.status === 'number' ? error.status : undefined
15
+ }
16
+
17
+ /** Twice, and not on a 4xx (the same request cannot start succeeding; a 401 is the app's to handle). */
18
+ const retry = (failureCount: number, error: unknown): boolean => {
19
+ const status = statusOf(error)
20
+ const retryable =
21
+ status === undefined || status < 400 || status >= 500 || TRANSIENT_4XX.has(status)
22
+ return failureCount < MAX_RETRIES && retryable
23
+ }
24
+
8
25
  const BASALT_QUERY_DEFAULTS = {
9
26
  staleTime: 30_000,
10
27
  gcTime: 5 * 60 * 1000,
11
- retry: 2,
28
+ retry,
12
29
  refetchOnWindowFocus: false,
13
30
  } as const
14
31
 
@@ -22,78 +39,3 @@ export function makeQueryClient(config?: QueryClientConfig): QueryClient {
22
39
  },
23
40
  })
24
41
  }
25
-
26
- // ── unwrap ────────────────────────────────────────────────────────────────────────────────────────
27
-
28
- /**
29
- * Transport-agnostic unwrap for any `{ data, error }` envelope (Eden Treaty, raw fetch wrappers,
30
- * etc.). TData is inferred from the data field. Throws on the error branch so failures surface
31
- * to the nearest error boundary or TanStack Query's error state.
32
- *
33
- * Absence guard: if `error` is falsy but `data` is `null` OR `undefined`, unwrap throws with a
34
- * descriptive message. This catches 204 No Content responses and silent transport failures that
35
- * return `{ data: null, error: null }` — both signal an unexpected absence of data and should not
36
- * silently resolve. `undefined` joined `null` here (C5 consolidation) so a hand-rolled fetch
37
- * wrapper that leaves `data` unset on a miss — rather than explicitly `null` — is caught the same
38
- * way; the two envelope shapes argo's own pre-basalt `unwrap` and basalt's ONLY differed on.
39
- *
40
- * **One generic signature, a conditional return** — a Promise of the envelope (basalt's original
41
- * shape, `queryFn: () => unwrap(api.x.get())`) or the ALREADY-RESOLVED envelope itself
42
- * (`unwrap(await api.x.get())`), both resolve `TData` off the same conditional. The two-overload
43
- * form this replaced (1.29.0) resolved `unwrap` to `unknown` whenever it was passed as a bare
44
- * callback — `.then(unwrap)` never applies an overload, it just reads the declared type of the
45
- * `unwrap` reference — so `api.threads.get().then(unwrap)` silently widened. A single generic
46
- * signature has exactly one type to read regardless of how the reference is used.
47
- *
48
- * **The conditional infers the raw `data` type and strips `null`/`undefined` from it**, rather
49
- * than inferring the already-narrowed `Envelope<TData>`'s `TData` directly — Eden Treaty's
50
- * response type is a UNION of envelope shapes (`{ data: T; error: null } | { data: null; error:
51
- * EdenFetchError }`), and inferring through `Envelope<infer TData>` reads `TData` off whichever
52
- * union member the conditional happens to match, landing on `T | null` at every Eden call site. A
53
- * conditional type distributes over a union input when the checked type is a bare type parameter,
54
- * so inferring `D` from `{ data: infer D; error: unknown }` and wrapping the result in
55
- * `NonNullable` runs the check per union member and unions the results back together —
56
- * `NonNullable<T> | NonNullable<null>` collapses to `T`.
57
- *
58
- * @example
59
- * import { unwrap } from 'basalt-ui'
60
- *
61
- * // Promise-of-envelope — queryFn:
62
- * queryFn: () => unwrap(api.users.get({ query: params }))
63
- * // mutation:
64
- * mutationFn: (body) => unwrap(api.resource.post({ body }))
65
- *
66
- * // resolved-envelope — either shape, including a bare `.then(unwrap)` callback:
67
- * const rows = unwrap(await api.users.get())
68
- * const rows2 = await api.users.get().then(unwrap)
69
- */
70
- export function unwrap<R extends Envelope | Promise<Envelope>>(response: R): UnwrapResult<R> {
71
- if (response instanceof Promise) {
72
- return response.then((envelope) => unwrapEnvelope(envelope)) as unknown as UnwrapResult<R>
73
- }
74
- return unwrapEnvelope(response as Envelope) as unknown as UnwrapResult<R>
75
- }
76
-
77
- /** Transport-agnostic `{ data, error }` result shape — Eden Treaty, a raw fetch wrapper, etc. */
78
- type Envelope<TData = unknown> = { data: TData | null | undefined; error: unknown }
79
-
80
- /** `unwrap`'s conditional return: a `Promise<TData>` when `R` is a promised envelope, `TData` when
81
- * it is an already-resolved one — inferred off the SAME `R` the overload used to split on, and
82
- * distributing over a union `R` (see the JSDoc above) so an Eden Treaty response's null branch
83
- * never leaks into the resolved type. */
84
- type UnwrapResult<R> =
85
- R extends Promise<{ data: infer TData; error: unknown }>
86
- ? Promise<NonNullable<TData>>
87
- : R extends { data: infer TData; error: unknown }
88
- ? NonNullable<TData>
89
- : never
90
-
91
- function unwrapEnvelope<TData>(envelope: Envelope<TData>): TData {
92
- const { data, error } = envelope
93
- if (error) throw error
94
- if (data === null || data === undefined)
95
- throw new Error(
96
- 'unwrap: null/undefined data with no error — check for a 204 response or a transport failure',
97
- )
98
- return data
99
- }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * `createSearchStore`'s dev diagnostics and the once-only bookkeeping behind them, so the store
3
+ * body is the lane logic only. Every method is silent in production except `patchOwned`, which
4
+ * keeps the write and logs it. Each reads `process.env['NODE_ENV']` literally at its own branch —
5
+ * a shared helper would keep the dev text in a production bundle (`src/common/dev-gate.test.ts`).
6
+ */
7
+
8
+ /** True the first time `name` is seen in `seen`. */
9
+ function first(seen: Set<string>, name: string): boolean {
10
+ if (seen.has(name)) return false
11
+ seen.add(name)
12
+ return true
13
+ }
14
+
15
+ function describeValue(value: unknown): string {
16
+ return typeof value === 'string' ? value : JSON.stringify(value)
17
+ }
18
+
19
+ function patchOwnsFieldMessage(input: {
20
+ key: string
21
+ name: string
22
+ owner: string
23
+ param: string
24
+ }): string {
25
+ const { key, name, owner, param } = input
26
+ return (
27
+ `basalt-ui: createSearchStore('${key}'): set('${name}', …, { patch }) carries \`${param}\`, ` +
28
+ `which this store's field '${owner}' owns — the URL would take it while the localStorage ` +
29
+ 'mirror kept the old value, so the next paramless visit and every `linkSearch` link disagree ' +
30
+ `with the page the write happened on. Write it through \`field.${owner}.use()[1]\` instead; ` +
31
+ 'a `patch` is for keys the store does NOT own.'
32
+ )
33
+ }
34
+
35
+ export type StoreWarnings = {
36
+ linkPinsFallback: (input: { param: string; urlValue: unknown; storedValue: unknown }) => void
37
+ writeHasNowhereToGo: (input: { name: string; param: string }) => void
38
+ patchWasDropped: (input: { name: string; param: string }) => void
39
+ patchOwned: (input: { name: string; owner: string; param: string }) => void
40
+ foreignParam: (input: { name: string; param: string; path: string }) => void
41
+ }
42
+
43
+ export function createStoreWarnings(key: string): StoreWarnings {
44
+ let pinned = false
45
+ const nowhere = new Set<string>()
46
+ const patchDropped = new Set<string>()
47
+ const patchOwner = new Set<string>()
48
+ const foreign = new Set<string>()
49
+
50
+ const warn = (message: string): void =>
51
+ // oxlint-disable-next-line no-console -- a dev-time wiring warning has no other channel
52
+ console.warn(`[basalt-ui] createSearchStore('${key}'): ${message}`)
53
+
54
+ return {
55
+ /**
56
+ * Once per store: the URL pins `fallback` while something else is persisted and no reader was
57
+ * ever called — almost always a nav link declaring the param as a module-scope literal.
58
+ */
59
+ linkPinsFallback(input: { param: string; urlValue: unknown; storedValue: unknown }): void {
60
+ if (process.env['NODE_ENV'] === 'production' || pinned) return
61
+ pinned = true
62
+ const { param } = input
63
+ const urlValue = describeValue(input.urlValue)
64
+ warn(
65
+ `the URL pinned \`${param}=${urlValue}\` (the fallback) while '${describeValue(input.storedValue)}' ` +
66
+ 'was persisted, and nothing has read this store back. A nav link is almost certainly ' +
67
+ `declaring \`search: { ${param}: '${urlValue}' }\` at module scope, which overrides the ` +
68
+ "stored value on every click — pass the store's own reader instead: " +
69
+ '`search: <store>.linkSearch`. (dev only)',
70
+ )
71
+ },
72
+ /** Once per field: a `persist: false` write from a route that does not validate it goes nowhere. */
73
+ writeHasNowhereToGo(input: { name: string; param: string }): void {
74
+ if (process.env['NODE_ENV'] === 'production' || !first(nowhere, input.name)) return
75
+ warn(
76
+ `wrote field '${input.name}' from a route that does not validate \`${input.param}\`, and ` +
77
+ 'the field is `persist: false` — so the write was dropped. Either render this control on ' +
78
+ 'the route wired to `validateSearch`, or give the field the localStorage lane (drop ' +
79
+ '`persist: false`) so a write from elsewhere survives until the owning route reads it. ' +
80
+ '(dev only)',
81
+ )
82
+ },
83
+ /** Once per field: a patched write from a route that does not validate the field. */
84
+ patchWasDropped(input: { name: string; param: string }): void {
85
+ if (process.env['NODE_ENV'] === 'production' || !first(patchDropped, input.name)) return
86
+ warn(
87
+ `wrote field '${input.name}' with a \`patch\` from a route that does not validate ` +
88
+ `\`${input.param}\` — the field's value persisted (A1), but the patch was DROPPED: there ` +
89
+ 'is no navigate to merge it into. Render the control on the route wired to ' +
90
+ '`validateSearch`, or apply that sibling param on the route that owns it. (dev only)',
91
+ )
92
+ },
93
+ /**
94
+ * A `patch` named a param another field of this store owns: thrown in dev (one-line fix, silent
95
+ * damage), kept and logged once in production so a stale param cannot take a page down.
96
+ */
97
+ patchOwned(input: { name: string; owner: string; param: string }): void {
98
+ const message = patchOwnsFieldMessage({ key, ...input })
99
+ if (process.env['NODE_ENV'] !== 'production') throw new Error(message)
100
+ if (!first(patchOwner, input.param)) return
101
+ // oxlint-disable-next-line no-console -- production keeps the write; the log is the record
102
+ console.error(message)
103
+ },
104
+ /**
105
+ * Once per field and path: the param is in the URL, yet this store's `validateSearch` did not run for the location — so
106
+ * a different store or a hand-rolled schema owns it, and presence-based ownership will let this
107
+ * store's setter navigate on its behalf.
108
+ */
109
+ foreignParam(input: { name: string; param: string; path: string }): void {
110
+ if (process.env['NODE_ENV'] === 'production') return
111
+ if (!first(foreign, `${input.name}@${input.path}`)) return
112
+ warn(
113
+ `\`${input.param}\` (field '${input.name}') is in the URL but this store's ` +
114
+ '`validateSearch` has never run — another store or schema owns the param, and a write ' +
115
+ 'here will navigate for it. Wire `validateSearch: <store>.validateSearch` (or spread it ' +
116
+ 'into your own) on the route that owns the param. (dev only)',
117
+ )
118
+ },
119
+ }
120
+ }