@frontic/nuxt 1.1.0 → 1.2.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.
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "frontic",
3
3
  "configKey": "frontic",
4
- "version": "1.1.0",
4
+ "version": "1.2.0",
5
5
  "compatibility": {
6
6
  "nuxt": ">=4.0.0"
7
7
  },
@@ -12,7 +12,13 @@ export interface FronticAnalyticsItem {
12
12
  index: number;
13
13
  data: unknown;
14
14
  }
15
- export type FronticListingTrigger = 'initial' | 'term' | 'filter' | 'sort' | 'page' | 'loadMore' | 'reset';
15
+ /**
16
+ * What caused a listing to resolve. `url` covers a change that arrived through the address bar —
17
+ * a back/forward navigation or an edited link under `urlQuerySync` — which no mutator reports
18
+ * because none was called. It carries no `changedFilter`: a restored URL can move several slices
19
+ * at once, and naming one of them would misreport the rest.
20
+ */
21
+ export type FronticListingTrigger = 'initial' | 'term' | 'filter' | 'sort' | 'page' | 'loadMore' | 'reset' | 'url';
16
22
  export interface FronticListingResolved {
17
23
  listing: string;
18
24
  cacheKey: string;
@@ -4,6 +4,7 @@
4
4
  * Provides query key management and query factory functions for Frontic listings.
5
5
  * Compatible with both @pinia/colada and useAsyncData patterns.
6
6
  */
7
+ import type { MaybeRefOrGetter } from 'vue';
7
8
  import type { FronticClient } from '../types/client.js';
8
9
  import type { ListingName, ResponseOf } from '../types/registry.js';
9
10
  import type { FetchListingConfig } from '../types/listing.js';
@@ -53,15 +54,57 @@ export declare const LISTING_QUERY_KEYS: {
53
54
  export declare function fetchListingQuery<TListing extends ListingName>(config: FetchListingConfig<TListing> & {
54
55
  _client?: FronticClient;
55
56
  }): {
57
+ staleTime: number;
58
+ gcTime?: number;
59
+ enabled?: MaybeRefOrGetter<boolean>;
60
+ initialData?: (() => ResponseOf<TListing> | undefined) | undefined;
61
+ initialDataUpdatedAt?: number | (() => number);
56
62
  placeholderData?: ((previousData: ResponseOf<TListing> | undefined) => ResponseOf<TListing> | undefined) | undefined;
57
- enabled?: import("vue").MaybeRefOrGetter<boolean> | undefined;
58
- gcTime?: number | undefined;
59
63
  key: () => readonly ["listings", string, Record<string, unknown>, Record<string, unknown>, {
60
64
  readonly context: string | null;
61
65
  readonly domain: string | null;
62
66
  }];
63
67
  query: () => Promise<ResponseOf<TListing>>;
68
+ };
69
+ /**
70
+ * Restricts an `initialData` getter to the key the query started on.
71
+ *
72
+ * Pinia Colada seeds *every* cache entry it creates, not just the first one.
73
+ * Unguarded, the payload describing page 1 unfiltered would be handed to page
74
+ * 2, to each filter the user picks and to each sort — and reported `success`
75
+ * with a fresh timestamp, so none of them would ever fetch.
76
+ *
77
+ * The seed key is read when the query is built, in setup, which is the state
78
+ * the caller's payload describes. Compared through the cache's own hash rather
79
+ * than a plain stringify, so that a query object written in a different
80
+ * property order still counts as the same question — the cache treats key
81
+ * objects as order-insensitive, and a stricter guard here would drop the seed
82
+ * for a key the cache considers identical.
83
+ */
84
+ export declare function seedInitialData<TData>(key: () => readonly unknown[], initialData: () => TData): () => TData | undefined;
85
+ /**
86
+ * Cache options shared by both query modes.
87
+ *
88
+ * Standard mode reaches these through `fetchListingQuery`; infinite mode builds
89
+ * its own options object and spreads this in. Kept in one place because the two
90
+ * silently diverged once already — `enabled`, `gcTime` and `keepPreviousData`
91
+ * were accepted by the composable and dropped on the infinite path, so a query
92
+ * meant to be held back fired anyway.
93
+ */
94
+ export declare function listingQueryOptions<TData>(config: {
95
+ staleTime?: number;
96
+ gcTime?: number;
97
+ enabled?: MaybeRefOrGetter<boolean>;
98
+ keepPreviousData?: boolean;
99
+ initialData?: () => TData | undefined;
100
+ initialDataUpdatedAt?: number | (() => number);
101
+ }): {
64
102
  staleTime: number;
103
+ gcTime?: number;
104
+ enabled?: MaybeRefOrGetter<boolean>;
105
+ initialData?: () => TData | undefined;
106
+ initialDataUpdatedAt?: number | (() => number);
107
+ placeholderData?: (previousData: TData | undefined) => TData | undefined;
65
108
  };
66
109
  /**
67
110
  * Creates a cache key string from query key array
@@ -1,4 +1,5 @@
1
1
  import { toValue } from "vue";
2
+ import { toCacheKey } from "@pinia/colada";
2
3
  import { DEFAULT_STALE_TIME, requestContextSlot, toKeyPart } from "../utils/query-keys.js";
3
4
  export const LISTING_QUERY_KEYS = {
4
5
  root: ["listings"],
@@ -6,19 +7,20 @@ export const LISTING_QUERY_KEYS = {
6
7
  detail: (listingName, parameters, query, contextKey, contextDomain) => [...LISTING_QUERY_KEYS.listing(listingName), toKeyPart(parameters), toKeyPart(query), requestContextSlot(contextKey, contextDomain)]
7
8
  };
8
9
  export function fetchListingQuery(config) {
10
+ const key = () => {
11
+ const query = toValue(config.query) ?? {};
12
+ const page = toValue(config.page);
13
+ const queryWithPage = page ? { ...query, page } : query;
14
+ return LISTING_QUERY_KEYS.detail(
15
+ config.name,
16
+ toValue(config.params),
17
+ queryWithPage,
18
+ toValue(config.contextKey),
19
+ toValue(config.contextDomain)
20
+ );
21
+ };
9
22
  return {
10
- key: () => {
11
- const query = toValue(config.query) ?? {};
12
- const page = toValue(config.page);
13
- const queryWithPage = page ? { ...query, page } : query;
14
- return LISTING_QUERY_KEYS.detail(
15
- config.name,
16
- toValue(config.params),
17
- queryWithPage,
18
- toValue(config.contextKey),
19
- toValue(config.contextDomain)
20
- );
21
- },
23
+ key,
22
24
  query: async () => {
23
25
  const query = toValue(config.query) ?? {};
24
26
  const page = toValue(config.page);
@@ -40,9 +42,27 @@ export function fetchListingQuery(config) {
40
42
  throw error;
41
43
  }
42
44
  },
45
+ ...listingQueryOptions({
46
+ ...config,
47
+ ...config.initialData && { initialData: seedInitialData(key, config.initialData) }
48
+ })
49
+ };
50
+ }
51
+ export function seedInitialData(key, initialData) {
52
+ const hash = () => toCacheKey(key());
53
+ const seedKey = hash();
54
+ return () => hash() === seedKey ? initialData() : void 0;
55
+ }
56
+ export function listingQueryOptions(config) {
57
+ return {
43
58
  staleTime: config.staleTime ?? DEFAULT_STALE_TIME,
44
59
  ...config.gcTime !== void 0 && { gcTime: config.gcTime },
45
60
  ...config.enabled !== void 0 && { enabled: config.enabled },
61
+ // initialData: seeds the cache and reports `success`, so the query does not
62
+ // fetch while the seed is within staleTime. Expected pre-guarded by
63
+ // seedInitialData — see the note there.
64
+ ...config.initialData !== void 0 && { initialData: config.initialData },
65
+ ...config.initialDataUpdatedAt !== void 0 && { initialDataUpdatedAt: config.initialDataUpdatedAt },
46
66
  // keepPreviousData: show the previous entry's data while a changed key
47
67
  // (new page, filter, context) loads; never written to the cache
48
68
  ...config.keepPreviousData !== false && { placeholderData: (previousData) => previousData }
@@ -6,7 +6,9 @@ import { FRONTIC_FETCH_ERROR_VERSION } from "../types/errors.js";
6
6
  function withDefaults(defaults, reqOptions) {
7
7
  if (!reqOptions) return defaults;
8
8
  const provided = Object.fromEntries(Object.entries(reqOptions).filter(([, value]) => value !== void 0));
9
- return { ...defaults, ...provided };
9
+ const merged = { ...defaults, ...provided };
10
+ if (merged.requestUrl === false) delete merged.requestUrl;
11
+ return merged;
10
12
  }
11
13
  export function useFronticClient(options) {
12
14
  const config = useRuntimeConfig();
@@ -1,8 +1,8 @@
1
1
  import type { Ref, MaybeRef } from 'vue';
2
2
  import type { ListingName, ResponseOf } from '../types/registry.js';
3
- import type { FronticRequestOptions, FronticQueryOptions, ListingArgs, ListingQuery } from '../types/listing.js';
3
+ import type { FronticRequestOptions, FronticQueryOptions, FronticInitialDataOptions, ListingArgs, ListingQuery } from '../types/listing.js';
4
4
  export type { ListingQuery } from '../types/listing.js';
5
- export interface UseFronticListingOptions<TListing extends ListingName = ListingName> extends FronticRequestOptions, FronticQueryOptions {
5
+ export interface UseFronticListingOptions<TListing extends ListingName = ListingName> extends FronticRequestOptions, FronticQueryOptions, FronticInitialDataOptions<ResponseOf<TListing>> {
6
6
  /**
7
7
  * Query options forwarded to the Fetch API — `filter`, `sort`, `search`, `limit`, `page`.
8
8
  * Same shape as `client.listing(name, params, { query })`.
@@ -43,6 +43,12 @@ export interface UseFronticListingOptions<TListing extends ListingName = Listing
43
43
  * const { listing } = useFronticListing('ProductSearch', {}, {
44
44
  * query: computed(() => ({ limit: 20, page: page.value })),
45
45
  * })
46
+ *
47
+ * // Seeded from the page payload — renders on the first paint, no request
48
+ * const { data } = useFronticPage()
49
+ * const { listing } = useFronticListing('CategoryProducts', { key: 'shoes' }, {
50
+ * initialData: () => data.value?.products,
51
+ * })
46
52
  * ```
47
53
  */
48
54
  export declare function useFronticListing<T extends ListingName>(name: T, ...args: ListingArgs<T, UseFronticListingOptions<T>>): {
@@ -71,9 +77,9 @@ export declare function useFronticListing<T extends ListingName>(name: T, ...arg
71
77
  /**
72
78
  * Manually refresh the listing data (uses cache if valid)
73
79
  */
74
- refresh: (throwOnError?: boolean) => Promise<import("@pinia/colada").DataState<ResponseOf<T>, Error, undefined>>;
80
+ refresh: (throwOnError?: boolean) => Promise<import("@pinia/colada").DataState<ResponseOf<T>, Error, ResponseOf<T> | undefined>>;
75
81
  /**
76
82
  * Force a fresh fetch of the listing data, bypassing cache
77
83
  */
78
- refetch: (throwOnError?: boolean) => Promise<import("@pinia/colada").DataState<ResponseOf<T>, Error, undefined>>;
84
+ refetch: (throwOnError?: boolean) => Promise<import("@pinia/colada").DataState<ResponseOf<T>, Error, ResponseOf<T> | undefined>>;
79
85
  };
@@ -20,6 +20,8 @@ export function useFronticListing(name, ...args) {
20
20
  gcTime: options?.gcTime,
21
21
  enabled: options?.enabled,
22
22
  keepPreviousData: options?.keepPreviousData,
23
+ initialData: options?.initialData,
24
+ initialDataUpdatedAt: options?.initialDataUpdatedAt,
23
25
  _client
24
26
  });
25
27
  const { data, status, asyncStatus, isLoading, error, refresh, refetch } = useQuery(listingQuery);
@@ -13,8 +13,10 @@ import {
13
13
  seedFilterLists
14
14
  } from "../utils/filter-helpers.js";
15
15
  import { makeFilterState, processAvailableFilters, processAvailableSorts, applyFilterConfig, countActiveFilters, parseSortString, isSortAllowed } from "../utils/state-helpers.js";
16
- import { fetchListingQuery, LISTING_QUERY_KEYS } from "./listings.js";
16
+ import { normalizeUrlQuerySyncConfig } from "../utils/search-url.js";
17
+ import { fetchListingQuery, listingQueryOptions, seedInitialData, LISTING_QUERY_KEYS } from "./listings.js";
17
18
  import { useFronticClient } from "./useFronticClient.js";
19
+ import { useSearchUrlSync } from "./useSearchUrlSync.js";
18
20
  import { emit, emitOnce, bindRouteReset, toAnalyticsItems, FRONTIC_ANALYTICS_VERSION } from "./analytics.js";
19
21
  export function useFronticSearch(name, ...args) {
20
22
  const [rawParams, options] = args;
@@ -98,6 +100,32 @@ export function useFronticSearch(name, ...args) {
98
100
  limit: toValue(options?.limit)
99
101
  })
100
102
  );
103
+ const urlSyncConfig = options?.urlQuerySync ? normalizeUrlQuerySyncConfig(options.urlQuerySync, { filterConfig, sortConfig, orFilter, disableSearch, disableFilter, disableSorting }) : void 0;
104
+ if (urlSyncConfig) {
105
+ useSearchUrlSync({
106
+ config: urlSyncConfig,
107
+ refs: { searchTerm, committedSearch: _search, orFilterList: _orFilterList, andFilterList: _andFilterList, rangeFilterList: _rangeFilterList, sortQuery: _sortQuery, page: _page },
108
+ gatedSearch: () => apiQuery.value.search,
109
+ onExternalChange: () => withIntent("url")
110
+ });
111
+ }
112
+ if (import.meta.dev && options?.initialData) {
113
+ const seededState = [
114
+ !disableFilter && (_orFilterList.value.length || _andFilterList.value.length || _rangeFilterList.value.length) ? "filters" : "",
115
+ !disableSorting && _sortQuery.value ? "a sort" : "",
116
+ !disableSearch && _search.value ? "a search term" : "",
117
+ // `_page` starts undefined and only a navigation or the URL sync writes
118
+ // it, so `initialPage` has to be read the same way the cursor below reads
119
+ // it. In infinite mode this is the one mismatch the key guard cannot
120
+ // catch at all — page is a cursor there, deliberately absent from the key.
121
+ (_page.value ?? initialPage) > 1 ? "a page" : ""
122
+ ].filter(Boolean);
123
+ if (seededState.length) {
124
+ console.warn(
125
+ `[@frontic/nuxt] useFronticSearch('${String(name)}') starts with ${seededState.join(", ")} applied and was given \`initialData\`. The seed is used for that query, so it must be the response to it \u2014 return \`undefined\` from the getter when your payload does not match.`
126
+ );
127
+ }
128
+ }
101
129
  const queryConfig = {
102
130
  name: listingName,
103
131
  params,
@@ -109,6 +137,8 @@ export function useFronticSearch(name, ...args) {
109
137
  gcTime: options?.gcTime,
110
138
  enabled: options?.enabled,
111
139
  keepPreviousData: options?.keepPreviousData,
140
+ initialData: options?.initialData,
141
+ initialDataUpdatedAt: options?.initialDataUpdatedAt,
112
142
  _client
113
143
  };
114
144
  let data;
@@ -121,9 +151,10 @@ export function useFronticSearch(name, ...args) {
121
151
  let loadNextFn;
122
152
  let loadPrevFn;
123
153
  let loadPageFn;
154
+ const infiniteKey = () => LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value, toValue(contextKey), toValue(contextDomain));
124
155
  if (infinite) {
125
156
  const infiniteResult = useInfiniteQuery({
126
- key: () => LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value, toValue(contextKey), toValue(contextDomain)),
157
+ key: infiniteKey,
127
158
  // `_page` seeds the starting cursor (e.g. deep-linked page from the URL); it deliberately does NOT enter the
128
159
  // key above — in infinite mode page is a cursor, not an identity, so keying on it would reset accumulation.
129
160
  initialPageParam: _page.value ?? initialPage,
@@ -146,7 +177,23 @@ export function useFronticSearch(name, ...args) {
146
177
  if (!page || typeof page !== "object") return void 0;
147
178
  return page.prev ?? void 0;
148
179
  },
149
- staleTime
180
+ // Shared with the standard branch rather than restated: this object is
181
+ // hand-built, so anything the composable accepts is dropped unless it is
182
+ // forwarded here.
183
+ // Typed against the accumulated page set, not a single response: in
184
+ // infinite mode `placeholderData` receives what the cache holds, which is
185
+ // every page fetched so far.
186
+ ...listingQueryOptions({
187
+ ...queryConfig,
188
+ // Assigned rather than conditionally spread: it has to *replace* the
189
+ // single-response getter `queryConfig` carries, not union with it.
190
+ // The caller hands over one response, the same as in standard mode; the
191
+ // page set it seeds is this module's shape, not theirs.
192
+ initialData: options?.initialData && seedInitialData(infiniteKey, () => {
193
+ const seed = options.initialData();
194
+ return seed === void 0 ? void 0 : { pages: [seed], pageParams: [_page.value ?? initialPage] };
195
+ })
196
+ })
150
197
  });
151
198
  const flattenedData = computed(() => {
152
199
  const pages = infiniteResult.data.value?.pages;
@@ -182,14 +229,7 @@ export function useFronticSearch(name, ...args) {
182
229
  });
183
230
  const response = await pagedQueryFactory.query();
184
231
  if (response) {
185
- const listKey = LISTING_QUERY_KEYS.detail(
186
- String(listingName),
187
- toValue(params),
188
- apiQuery.value,
189
- toValue(contextKey),
190
- toValue(contextDomain)
191
- );
192
- setInfiniteQueryData(queryCache, listKey, { pages: [response], pageParams: [page] });
232
+ setInfiniteQueryData(queryCache, infiniteKey(), { pages: [response], pageParams: [page] });
193
233
  updateState(response);
194
234
  emitListingResolved(response, "page");
195
235
  }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * useSearchUrlSync
3
+ *
4
+ * Router glue for useFronticSearch's opt-in URL query sync. Kept separate from the pure codec
5
+ * (utils/search-url) so all decisions stay testable and only this thin layer touches Nuxt.
6
+ *
7
+ * Internal — not auto-imported. Consumers enable it via `useFronticSearch(..., { urlQuerySync })`.
8
+ */
9
+ import { type Ref } from 'vue';
10
+ import type { EqualsFilter, RangeFilter } from '../utils/filter-helpers.js';
11
+ import { type SearchUrlCodecConfig } from '../utils/search-url.js';
12
+ interface SearchUrlSyncRefs {
13
+ searchTerm: Ref<string>;
14
+ /**
15
+ * The committed term the query body reads. Written alongside `searchTerm` and never gated by
16
+ * `searchTermThreshold`: the threshold exists to stop a request per keystroke, and a term that
17
+ * arrived in the URL was not typed. The watcher that normally promotes one to the other does not
18
+ * run during SSR, so a URL term that only reached `searchTerm` would never reach the request.
19
+ */
20
+ committedSearch: Ref<string | undefined>;
21
+ orFilterList: Ref<EqualsFilter[]>;
22
+ andFilterList: Ref<EqualsFilter[]>;
23
+ rangeFilterList: Ref<RangeFilter[]>;
24
+ sortQuery: Ref<{
25
+ field: string;
26
+ order: 'asc' | 'desc';
27
+ } | undefined>;
28
+ page: Ref<number | undefined>;
29
+ }
30
+ export interface UseSearchUrlSyncContext {
31
+ config: SearchUrlCodecConfig;
32
+ refs: SearchUrlSyncRefs;
33
+ /** The threshold-gated search term (apiQuery.search) — what the URL should reflect. */
34
+ gatedSearch: () => string | undefined;
35
+ /** Called after state is changed by an external URL change (back/forward), to refetch. */
36
+ onExternalChange: () => unknown;
37
+ }
38
+ export declare function useSearchUrlSync(ctx: UseSearchUrlSyncContext): void;
39
+ export {};
@@ -0,0 +1,53 @@
1
+ import { useRoute, useRouter } from "nuxt/app";
2
+ import { watch } from "vue";
3
+ import { createSearchUrlCodec } from "../utils/search-url.js";
4
+ export function useSearchUrlSync(ctx) {
5
+ const { config, refs } = ctx;
6
+ if (import.meta.dev) {
7
+ for (const warning of config.warnings) console.warn(`[@frontic/nuxt] useFronticSearch urlQuerySync: ${warning}`);
8
+ }
9
+ const route = useRoute();
10
+ const router = useRouter();
11
+ if (!route || !router) {
12
+ if (import.meta.dev) console.warn("[@frontic/nuxt] useFronticSearch `urlQuerySync` needs a Nuxt app with a router \u2014 skipping URL sync.");
13
+ return;
14
+ }
15
+ const codec = createSearchUrlCodec(config);
16
+ const readState = () => ({
17
+ search: refs.searchTerm.value,
18
+ sort: refs.sortQuery.value,
19
+ or: refs.orFilterList.value,
20
+ and: refs.andFilterList.value,
21
+ range: refs.rangeFilterList.value,
22
+ page: refs.page.value
23
+ });
24
+ function applyFromUrl() {
25
+ const current = readState();
26
+ const next = codec.decode(route.query, current);
27
+ if (codec.canonical(next) === codec.canonical(current)) return false;
28
+ refs.searchTerm.value = next.search ?? "";
29
+ refs.committedSearch.value = next.search || void 0;
30
+ refs.sortQuery.value = next.sort;
31
+ refs.orFilterList.value = next.or;
32
+ refs.andFilterList.value = next.and;
33
+ refs.rangeFilterList.value = next.range;
34
+ refs.page.value = next.page;
35
+ return true;
36
+ }
37
+ applyFromUrl();
38
+ if (import.meta.server) return;
39
+ watch(
40
+ () => codec.ownedSignature(route.query),
41
+ () => {
42
+ if (applyFromUrl()) void ctx.onExternalChange();
43
+ }
44
+ );
45
+ function flush(history) {
46
+ const owned = codec.encode({ ...readState(), search: ctx.gatedSearch() });
47
+ const { query, changed } = codec.merge(route.query, owned);
48
+ if (!changed) return;
49
+ void router[history]({ path: route.path, query, hash: route.hash });
50
+ }
51
+ watch([refs.orFilterList, refs.andFilterList, refs.rangeFilterList, refs.sortQuery, refs.page], () => flush(config.history));
52
+ watch(refs.committedSearch, () => flush("replace"));
53
+ }
@@ -11,7 +11,7 @@ export type { FronticRequestOptions, FronticQueryOptions, InclusionMode, FilterF
11
11
  export type { RangeFilterValue } from '../utils/filter-helpers.js';
12
12
  export type { FronticAnalyticsItem, FronticListingTrigger, FronticListingResolved, FronticSearchCommitted, FronticPageResolved } from '../composables/analytics.js';
13
13
  export type { FronticFetchError, FronticFetchOperation } from './errors.js';
14
- export type { SearchState, UseFronticSearchOptions, UseSearchReturn } from './search.js';
14
+ export type { SearchState, UseFronticSearchOptions, UseSearchReturn, SearchUrlSlice, SearchUrlQuerySyncOptions } from './search.js';
15
15
  export type { UseFronticClientOptions } from '../composables/useFronticClient.js';
16
16
  export type { UseFronticBlockOptions } from '../composables/useFronticBlock.js';
17
17
  export type { UseFronticPageOptions } from '../composables/useFronticPage.js';
@@ -5,7 +5,7 @@
5
5
  * factory. All schema-derived typing flows from the registry (./registry).
6
6
  */
7
7
  import type { MaybeRef, MaybeRefOrGetter } from 'vue';
8
- import type { ListingName, ListingParamsOf, ListingFiltersOf, ListingSortsOf, RequestOptions, FilterGroup, AggregationGroup, DefaultFilterOption, DefaultAggregationStats, FilterData, AggregationData, Pagination } from './registry.js';
8
+ import type { ListingName, ListingParamsOf, ListingFiltersOf, ListingSortsOf, ResponseOf, RequestOptions, FilterGroup, AggregationGroup, DefaultFilterOption, DefaultAggregationStats, FilterData, AggregationData, Pagination } from './registry.js';
9
9
  import type { Query } from './query.js';
10
10
  export type { Blocks, Listings, ListingParameters, ListingQueryFilters, ListingQuerySorts, Trees, Responses, ResponseOf, ListingParamsOf, ListingFiltersOf, ListingSortsOf, RequestOptions, TreeQuery, Pagination, FilterData, AggregationData, FilterGroup, AggregationGroup, } from './registry.js';
11
11
  export type { Query, Sort, SortField as QuerySortField, EqualsFilter, LogicalFilter, Filter, RangeFilter, ContainsFilter } from './query.js';
@@ -50,6 +50,42 @@ export interface FronticQueryOptions {
50
50
  */
51
51
  keepPreviousData?: boolean;
52
52
  }
53
+ /**
54
+ * Seeding a query with data that already arrived by another route — typically
55
+ * a listing embedded in the page or block payload that carries it, so the
56
+ * route renders without a second round trip.
57
+ *
58
+ * Separate from {@link FronticQueryOptions} because the payload type differs
59
+ * per composable, and a shared non-generic option would type it as `unknown`.
60
+ */
61
+ export interface FronticInitialDataOptions<TData> {
62
+ /**
63
+ * Data to seed the cache with, as a getter. The query reports `success`
64
+ * immediately and does not fetch while the seed is within `staleTime`.
65
+ *
66
+ * Only the query this composable starts on is seeded: the payload describes
67
+ * one set of filters, sort and page, so a later interaction fetches for real
68
+ * rather than being handed data that answers a different question.
69
+ *
70
+ * Use it only for data that *is* the response. To merely avoid a skeleton on
71
+ * data that may be wrong, let `keepPreviousData` do it — a seed reports
72
+ * `success`, so nothing downstream can tell it apart from a fetch.
73
+ *
74
+ * Returning `undefined` seeds nothing and fetches as usual, so a getter may
75
+ * read a payload that has not arrived yet without a guard of its own.
76
+ */
77
+ initialData?: () => TData | undefined;
78
+ /**
79
+ * When the seeded data was produced, as an epoch millisecond timestamp.
80
+ * Drives its staleness: with a `staleTime` of 5 minutes, a seed stamped 10
81
+ * minutes ago refetches in the background on mount instead of being trusted.
82
+ *
83
+ * Worth setting whenever the payload can outlive the request that renders it
84
+ * — an ISR or CDN-cached page hands the same block to every visitor.
85
+ * @default Date.now() (the seed counts as fresh)
86
+ */
87
+ initialDataUpdatedAt?: number | (() => number);
88
+ }
53
89
  /**
54
90
  * Resolves to the typed `Query<filter, sort>` shape for a given listing name.
55
91
  * Falls back to an untyped query when the listing isn't in the generated maps.
@@ -211,7 +247,7 @@ export interface ListingEnvelope {
211
247
  * Configuration for listing queries
212
248
  * @template TListing - The listing name, constrained to the registry's listing names
213
249
  */
214
- export interface FetchListingConfig<TListing extends ListingName = ListingName> extends FronticRequestOptions, FronticQueryOptions {
250
+ export interface FetchListingConfig<TListing extends ListingName = ListingName> extends FronticRequestOptions, FronticQueryOptions, FronticInitialDataOptions<ResponseOf<TListing>> {
215
251
  /**
216
252
  * The listing name to fetch (e.g., 'ProductSearch', 'CategoryProducts')
217
253
  */
@@ -98,7 +98,16 @@ export type ListingSortsOf<TName> = TName extends keyof FronticListingQuerySorts
98
98
  * `fs-secret` header; older clients ignore it.
99
99
  */
100
100
  export interface RequestOptions {
101
- requestUrl?: string;
101
+ /**
102
+ * URL recorded with the request for attribution and tracking. The Nuxt
103
+ * wrapper fills it in from the current URL unless told otherwise.
104
+ *
105
+ * `false` is an instruction to that wrapper, not a value: it opts the call
106
+ * out, and `useFronticClient` drops the key before the generated client sees
107
+ * it. Reach for it when the response goes behind a shared cache, where a
108
+ * per-visitor URL would vary a request that is otherwise identical.
109
+ */
110
+ requestUrl?: string | false;
102
111
  contextKey?: string;
103
112
  contextDomain?: string;
104
113
  proxyUrl?: string;
@@ -7,7 +7,7 @@
7
7
  import type { Ref, ShallowRef, MaybeRef } from 'vue';
8
8
  import type { UseQueryReturn } from '@pinia/colada';
9
9
  import type { ListingName, ListingFiltersOf, ListingSortsOf, ResponseOf } from './registry.js';
10
- import type { FronticRequestOptions, FronticQueryOptions, ListingFieldConfig, SortStringOf, UiFilter, UiSort } from './listing.js';
10
+ import type { FronticRequestOptions, FronticQueryOptions, FronticInitialDataOptions, ListingFieldConfig, SortStringOf, UiFilter, UiSort } from './listing.js';
11
11
  import type { RangeFilterValue } from '../utils/filter-helpers.js';
12
12
  export type { FronticRequestOptions, ListingFieldConfig, FilterOption, UiFilter, UiSort, AggregationStats, InclusionMode, SortString, SortStringOf } from './listing.js';
13
13
  export type { Listings, ListingQueryFilters, ListingQuerySorts, Responses, ResponseOf } from './registry.js';
@@ -70,7 +70,7 @@ export interface SearchState<TFilters = Record<string, unknown>, TSorts = Record
70
70
  * @template TFilters - Filter fields for this listing (defaults to the registry's filter map)
71
71
  * @template TSorts - Sort fields for this listing (defaults to the registry's sort map)
72
72
  */
73
- export interface UseFronticSearchOptions<TSearch extends ListingName = ListingName, TFilters = ListingFiltersOf<TSearch>, TSorts = ListingSortsOf<TSearch>> extends FronticRequestOptions, FronticQueryOptions {
73
+ export interface UseFronticSearchOptions<TSearch extends ListingName = ListingName, TFilters = ListingFiltersOf<TSearch>, TSorts = ListingSortsOf<TSearch>> extends FronticRequestOptions, FronticQueryOptions, FronticInitialDataOptions<ResponseOf<TSearch>> {
74
74
  /**
75
75
  * Cache key for the query (defaults to name)
76
76
  */
@@ -218,6 +218,67 @@ export interface UseFronticSearchOptions<TSearch extends ListingName = ListingNa
218
218
  * @default 1
219
219
  */
220
220
  initialPage?: number;
221
+ /**
222
+ * Opt-in two-way sync of search state with the URL query string.
223
+ *
224
+ * When enabled, the current search term, sorting, filters and page are reflected in the URL
225
+ * (shareable, reload-safe, back/forward-aware) and restored from it on load — server-side, so
226
+ * the first render already reflects the URL. Off by default: no router APIs are touched unless set.
227
+ *
228
+ * `true` uses all defaults. Pass an object to namespace or rename params, choose which slices to
229
+ * sync, or push history entries instead of replacing.
230
+ *
231
+ * @default false
232
+ * @example
233
+ * // Everything, default param names: ?q=…&sort=…&<field>=…&page=…
234
+ * urlQuerySync: true
235
+ *
236
+ * // Namespaced + renamed params: ?p_query=…&p_color=Red&p_price_min=20
237
+ * urlQuerySync: {
238
+ * prefix: 'p_',
239
+ * params: { search: 'query', 'properties.color': 'color', 'price.amount': 'price' },
240
+ * }
241
+ */
242
+ urlQuerySync?: boolean | SearchUrlQuerySyncOptions<TFilters>;
243
+ }
244
+ /** State slices that {@link SearchUrlQuerySyncOptions} can sync to the URL. */
245
+ export type SearchUrlSlice = 'search' | 'sort' | 'filter' | 'page';
246
+ /**
247
+ * Configuration for URL query-param sync on {@link UseFronticSearchOptions.urlQuerySync}.
248
+ *
249
+ * @template TFilters - Filter fields for this listing (provides autocomplete for `params` keys)
250
+ */
251
+ export interface SearchUrlQuerySyncOptions<TFilters = Record<string, unknown>> {
252
+ /**
253
+ * Prefix applied to every param this instance owns. Required to run two synced searches on one
254
+ * page without their params colliding (e.g. `prefix: 'a_'` and `prefix: 'b_'`).
255
+ * @default ''
256
+ */
257
+ prefix?: string;
258
+ /**
259
+ * Which state slices to sync. Also gated by the matching `disable*` option.
260
+ * @default ['search', 'sort', 'filter', 'page']
261
+ */
262
+ include?: SearchUrlSlice[];
263
+ /**
264
+ * Rename URL params. Keys are either a slice (`'search'` | `'sort'` | `'page'`) or a filter field
265
+ * name; values are the param name to use. Unlisted entries fall back to their default
266
+ * (`'search'` → `'q'`, `'sort'` → `'sort'`, `'page'` → `'page'`, filter fields → the raw field name;
267
+ * range filters get `_min`/`_max` suffixes on their param).
268
+ *
269
+ * Note: this is unrelated to the composable's second `params` argument (the backend listing
270
+ * parameters). The three slice names are reserved, so a filter field literally named
271
+ * `search`/`sort`/`page` cannot be renamed here.
272
+ *
273
+ * @example { search: 'query', 'properties.color': 'color', 'price.amount': 'price' }
274
+ */
275
+ params?: Partial<Record<'search' | 'sort' | 'page' | (keyof TFilters & string), string>>;
276
+ /**
277
+ * History strategy for URL writes. `'replace'` avoids a history entry per interaction (so Back
278
+ * leaves the page rather than stepping through filter states); `'push'` makes Back an undo.
279
+ * @default 'replace'
280
+ */
281
+ history?: 'replace' | 'push';
221
282
  }
222
283
  /**
223
284
  * Return type for the search composable — the declared contract of
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Search URL Codec
3
+ *
4
+ * Pure, framework-agnostic serialization between useFronticSearch state and a URL query object.
5
+ * All URL-sync decisions live here; the composable/router glue (useSearchUrlSync) only wires it up.
6
+ *
7
+ * URL format:
8
+ * search → ?q=shoes (renameable; omitted when empty)
9
+ * sort → ?sort=name:asc (renameable; validated; omitted when default)
10
+ * equals → ?color=Red&color=Blue (repeated params; renameable)
11
+ * range → ?price_min=20&price_max=100 (two params; open-ended omits a bound)
12
+ * page → ?page=3 (renameable; omitted for page 1)
13
+ */
14
+ import type { EqualsFilter, RangeFilter } from './filter-helpers.js';
15
+ import type { ListingFieldConfig, SearchUrlQuerySyncOptions } from '../types/search.js';
16
+ /** A single query param value as produced by a router's `route.query`. */
17
+ export type UrlQueryValue = string | null | Array<string | null> | undefined;
18
+ /** A framework-agnostic view of `route.query` (Vue Router's LocationQuery is assignable to this). */
19
+ export type UrlQuery = Record<string, UrlQueryValue>;
20
+ /** The subset of useFronticSearch state that can round-trip through the URL. */
21
+ export interface SearchUrlState {
22
+ search?: string;
23
+ sort?: {
24
+ field: string;
25
+ order: 'asc' | 'desc';
26
+ } | undefined;
27
+ or: EqualsFilter[];
28
+ and: EqualsFilter[];
29
+ range: RangeFilter[];
30
+ page?: number | undefined;
31
+ }
32
+ /** Per-filter-field URL binding, resolved once at setup. */
33
+ export interface FilterParamSpec {
34
+ field: string;
35
+ kind: 'equals' | 'range';
36
+ logic: 'or' | 'and';
37
+ /** Equals: the single param name. */
38
+ param?: string;
39
+ /** Range: lower/upper bound param names. */
40
+ minParam?: string;
41
+ maxParam?: string;
42
+ }
43
+ /** Fully-resolved, serializable codec configuration (no Vue/Nuxt references). */
44
+ export interface SearchUrlCodecConfig {
45
+ history: 'replace' | 'push';
46
+ searchParam?: string;
47
+ sortParam?: string;
48
+ pageParam?: string;
49
+ filters: FilterParamSpec[];
50
+ sortAllowList: string[];
51
+ /** Carried verbatim so decode can apply `mode: 'exclude'`, which `sortAllowList` cannot express. */
52
+ sortConfig: ListingFieldConfig;
53
+ ownedKeys: string[];
54
+ /** Dev-only advisories surfaced by the glue (kept as data so this module stays pure). */
55
+ warnings: string[];
56
+ }
57
+ /** Context the resolver needs from the composable's options. */
58
+ export interface SearchUrlResolveContext {
59
+ filterConfig: ListingFieldConfig;
60
+ sortConfig: ListingFieldConfig;
61
+ orFilter: string[];
62
+ disableSearch: boolean;
63
+ disableFilter: boolean;
64
+ disableSorting: boolean;
65
+ }
66
+ /**
67
+ * Resolves the public `urlQuerySync` option into a flat, serializable codec config.
68
+ * Returns `undefined` when the option is falsy.
69
+ */
70
+ export declare function normalizeUrlQuerySyncConfig(option: boolean | SearchUrlQuerySyncOptions | undefined, ctx: SearchUrlResolveContext): SearchUrlCodecConfig | undefined;
71
+ /** Builds the encode/decode/compare closure for a resolved config. */
72
+ export declare function createSearchUrlCodec(config: SearchUrlCodecConfig): {
73
+ encode: (state: SearchUrlState) => Record<string, string | string[]>;
74
+ decode: (query: UrlQuery, current: SearchUrlState) => SearchUrlState;
75
+ canonical: (state: SearchUrlState) => string;
76
+ merge: (current: UrlQuery, owned: Record<string, string | string[]>) => {
77
+ query: UrlQuery;
78
+ changed: boolean;
79
+ };
80
+ ownedSignature: (query: UrlQuery) => string;
81
+ ownedKeys: string[];
82
+ };
83
+ /** First value of a param as a string; `undefined` when absent, `''` when present but valueless/empty. */
84
+ export declare function firstString(value: UrlQueryValue): string | undefined;
85
+ /** All non-empty string values of a param, as an array. */
86
+ export declare function toStringArray(value: UrlQueryValue): string[];
87
+ /** Strict number parse (integer or decimal, optional sign). Rejects '', whitespace, hex, 'Infinity', etc. */
88
+ export declare function parseNumStrict(value: string | undefined): number | undefined;
89
+ /** Strict positive-integer parse for page numbers (>= 1). */
90
+ export declare function parsePageStrict(value: string | undefined): number | undefined;
@@ -0,0 +1,184 @@
1
+ import { isValidSortString, isSortAllowed, parseSortString } from "./state-helpers.js";
2
+ const RESERVED_SLICES = ["search", "sort", "page"];
3
+ const DEFAULT_SLICES = ["search", "sort", "filter", "page"];
4
+ export function normalizeUrlQuerySyncConfig(option, ctx) {
5
+ if (!option) return void 0;
6
+ const opt = option === true ? {} : option;
7
+ const prefix = opt.prefix ?? "";
8
+ const include = opt.include ?? DEFAULT_SLICES;
9
+ const params = opt.params ?? {};
10
+ const history = opt.history ?? "replace";
11
+ const warnings = [];
12
+ const searchOn = include.includes("search") && !ctx.disableSearch;
13
+ const sortOn = include.includes("sort") && !ctx.disableSorting;
14
+ const filterOn = include.includes("filter") && !ctx.disableFilter;
15
+ const pageOn = include.includes("page");
16
+ const searchParam = searchOn ? prefix + (params.search ?? "q") : void 0;
17
+ const sortParam = sortOn ? prefix + (params.sort ?? "sort") : void 0;
18
+ const pageParam = pageOn ? prefix + (params.page ?? "page") : void 0;
19
+ const filters = [];
20
+ if (filterOn) {
21
+ for (const field of collectFilterFields(ctx, params)) {
22
+ if (RESERVED_SLICES.includes(field)) {
23
+ warnings.push(`filter field "${field}" collides with a reserved slice name and cannot be synced to the URL \u2014 rename it via a listing alias.`);
24
+ continue;
25
+ }
26
+ const base = prefix + (params[field] ?? field);
27
+ const kind = ctx.filterConfig.type?.[field] === "range" ? "range" : "equals";
28
+ const logic = ctx.orFilter.includes(field) ? "or" : "and";
29
+ filters.push(kind === "range" ? { field, kind, logic, minParam: `${base}_min`, maxParam: `${base}_max` } : { field, kind, logic, param: base });
30
+ }
31
+ if (filters.length === 0) {
32
+ warnings.push('urlQuerySync includes the "filter" slice but no filter fields could be derived \u2014 configure filter.select/label/type, orFilter, or urlQuerySync.params.');
33
+ }
34
+ }
35
+ const ownedKeys = [];
36
+ for (const p of [searchParam, sortParam, pageParam]) if (p) ownedKeys.push(p);
37
+ for (const f of filters) {
38
+ if (f.kind === "range") ownedKeys.push(f.minParam, f.maxParam);
39
+ else ownedKeys.push(f.param);
40
+ }
41
+ reportDuplicateParams(ownedKeys, warnings);
42
+ const sortAllowList = sortOn ? Array.from(/* @__PURE__ */ new Set([...Object.keys(ctx.sortConfig.label ?? {}), ...ctx.sortConfig.mode !== "exclude" ? ctx.sortConfig.select ?? [] : []])) : [];
43
+ return { history, searchParam, sortParam, pageParam, filters, sortAllowList, sortConfig: ctx.sortConfig, ownedKeys, warnings };
44
+ }
45
+ function collectFilterFields(ctx, params) {
46
+ const fields = /* @__PURE__ */ new Set();
47
+ const { filterConfig } = ctx;
48
+ for (const key of Object.keys(params)) if (!RESERVED_SLICES.includes(key)) fields.add(key);
49
+ if (filterConfig.select && filterConfig.mode !== "exclude") for (const f of filterConfig.select) fields.add(f);
50
+ for (const f of Object.keys(filterConfig.label ?? {})) fields.add(f);
51
+ for (const f of Object.keys(filterConfig.type ?? {})) fields.add(f);
52
+ for (const f of ctx.orFilter) fields.add(f);
53
+ return [...fields];
54
+ }
55
+ function reportDuplicateParams(ownedKeys, warnings) {
56
+ const seen = /* @__PURE__ */ new Set();
57
+ const dupes = /* @__PURE__ */ new Set();
58
+ for (const k of ownedKeys) {
59
+ if (seen.has(k)) dupes.add(k);
60
+ seen.add(k);
61
+ }
62
+ for (const k of dupes) warnings.push(`URL param "${k}" is claimed by more than one field/slice \u2014 the last one wins. Give them distinct names via urlQuerySync.params.`);
63
+ }
64
+ export function createSearchUrlCodec(config) {
65
+ const { searchParam, sortParam, pageParam, filters, sortAllowList, ownedKeys } = config;
66
+ function encode(state) {
67
+ const out = {};
68
+ if (searchParam && state.search && state.search.trim() !== "") out[searchParam] = state.search;
69
+ if (sortParam && state.sort) out[sortParam] = `${state.sort.field}:${state.sort.order}`;
70
+ if (pageParam && state.page && state.page > 1) out[pageParam] = String(state.page);
71
+ for (const spec of filters) {
72
+ if (spec.kind === "equals") {
73
+ const list = spec.logic === "or" ? state.or : state.and;
74
+ const found = list.find((f) => f.field === spec.field);
75
+ if (!found) continue;
76
+ const values = (Array.isArray(found.value) ? found.value : [found.value]).map((v) => String(v)).filter((v) => v !== "");
77
+ if (values.length === 1) out[spec.param] = values[0];
78
+ else if (values.length > 1) out[spec.param] = values;
79
+ } else {
80
+ const found = state.range.find((r) => r.field === spec.field);
81
+ if (!found) continue;
82
+ if (found.from !== void 0) out[spec.minParam] = String(found.from);
83
+ if (found.to !== void 0) out[spec.maxParam] = String(found.to);
84
+ }
85
+ }
86
+ return out;
87
+ }
88
+ function decode(query, current) {
89
+ const next = { search: current.search, sort: current.sort, or: current.or, and: current.and, range: current.range, page: current.page };
90
+ if (searchParam) next.search = firstString(query[searchParam]) ?? "";
91
+ if (sortParam) {
92
+ const raw = firstString(query[sortParam]);
93
+ next.sort = raw && isValidSortString(raw, sortAllowList) && isSortAllowed(raw, config.sortConfig) ? parseSortString(raw) : void 0;
94
+ }
95
+ if (pageParam) {
96
+ const n = parsePageStrict(firstString(query[pageParam]));
97
+ next.page = n && n > 1 ? n : void 0;
98
+ }
99
+ if (filters.length) {
100
+ const owned = new Set(filters.map((f) => f.field));
101
+ const or = current.or.filter((f) => !owned.has(f.field));
102
+ const and = current.and.filter((f) => !owned.has(f.field));
103
+ const range = current.range.filter((f) => !owned.has(f.field));
104
+ for (const spec of filters) {
105
+ if (spec.kind === "equals") {
106
+ const values = toStringArray(query[spec.param]);
107
+ if (values.length) (spec.logic === "or" ? or : and).push({ type: "equals", field: spec.field, value: values });
108
+ } else {
109
+ const from = parseNumStrict(firstString(query[spec.minParam]));
110
+ const to = parseNumStrict(firstString(query[spec.maxParam]));
111
+ if (from !== void 0 || to !== void 0) range.push({ type: "range", field: spec.field, ...from !== void 0 && { from }, ...to !== void 0 && { to } });
112
+ }
113
+ }
114
+ next.or = or;
115
+ next.and = and;
116
+ next.range = range;
117
+ }
118
+ return next;
119
+ }
120
+ function canonical(state) {
121
+ return JSON.stringify({
122
+ s: state.search && state.search.trim() !== "" ? state.search : "",
123
+ o: state.sort ? `${state.sort.field}:${state.sort.order}` : "",
124
+ or: normEquals(state.or),
125
+ and: normEquals(state.and),
126
+ range: normRange(state.range),
127
+ p: state.page && state.page > 1 ? state.page : 1
128
+ });
129
+ }
130
+ function merge(current, owned) {
131
+ const query = { ...current };
132
+ for (const k of ownedKeys) delete query[k];
133
+ Object.assign(query, owned);
134
+ return { query, changed: !queryEqual(current, query) };
135
+ }
136
+ function ownedSignature(query) {
137
+ return JSON.stringify(ownedKeys.map((k) => [k, toStringArray(query[k])]));
138
+ }
139
+ return { encode, decode, canonical, merge, ownedSignature, ownedKeys };
140
+ }
141
+ export function firstString(value) {
142
+ if (value === void 0) return void 0;
143
+ if (Array.isArray(value)) {
144
+ const first = value[0];
145
+ return first == null ? "" : first;
146
+ }
147
+ return value == null ? "" : value;
148
+ }
149
+ export function toStringArray(value) {
150
+ if (value === void 0 || value === null) return [];
151
+ const arr = Array.isArray(value) ? value : [value];
152
+ return arr.filter((v) => v != null && v !== "");
153
+ }
154
+ export function parseNumStrict(value) {
155
+ if (value === void 0 || !/^-?\d+(\.\d+)?$/.test(value)) return void 0;
156
+ return Number(value);
157
+ }
158
+ export function parsePageStrict(value) {
159
+ if (value === void 0 || !/^\d+$/.test(value)) return void 0;
160
+ const n = Number(value);
161
+ return n >= 1 ? n : void 0;
162
+ }
163
+ function byField(a, b) {
164
+ return a.field < b.field ? -1 : a.field > b.field ? 1 : 0;
165
+ }
166
+ function normEquals(list) {
167
+ return [...list].sort(byField).map((f) => [f.field, (Array.isArray(f.value) ? f.value : [f.value]).map((v) => String(v)).sort()]);
168
+ }
169
+ function normRange(list) {
170
+ return [...list].sort(byField).map((r) => [r.field, r.from ?? null, r.to ?? null]);
171
+ }
172
+ function queryEqual(a, b) {
173
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
174
+ for (const k of keys) {
175
+ const av = JSON.stringify(normalizeForCompare(a[k]));
176
+ const bv = JSON.stringify(normalizeForCompare(b[k]));
177
+ if (av !== bv) return false;
178
+ }
179
+ return true;
180
+ }
181
+ function normalizeForCompare(value) {
182
+ if (value === void 0) return [];
183
+ return Array.isArray(value) ? value : [value];
184
+ }
@@ -128,4 +128,17 @@ export declare function parseSortString(sortString: string): {
128
128
  * @returns True if the sort is allowed
129
129
  */
130
130
  export declare function isSortAllowed(sortString: string, config?: ListingFieldConfig): boolean;
131
+ /**
132
+ * Validates a sort string sourced from untrusted input (e.g. a URL query param).
133
+ *
134
+ * Unlike {@link parseSortString} (which does no validation) and {@link isSortAllowed} (which is
135
+ * permissive when `select` is empty), this rejects anything that is not a well-formed
136
+ * `field:asc|desc` — and, when an allow-list is provided, anything not in it. `'default'` (the
137
+ * backend default order) is always considered valid.
138
+ *
139
+ * @param sortString - Candidate sort string
140
+ * @param allowList - Permitted sort strings (e.g. keys of `sorting.label`). Empty ⇒ structural check only.
141
+ * @returns True if the sort string is safe to apply
142
+ */
143
+ export declare function isValidSortString(sortString: string, allowList?: string[]): boolean;
131
144
  export {};
@@ -110,3 +110,9 @@ export function isSortAllowed(sortString, config = {}) {
110
110
  const isInSelect = select.includes(sortString);
111
111
  return mode === "include" ? isInSelect : !isInSelect;
112
112
  }
113
+ export function isValidSortString(sortString, allowList = []) {
114
+ if (sortString === "default") return true;
115
+ if (!/^[\w.]+:(asc|desc)$/.test(sortString)) return false;
116
+ if (allowList.length === 0) return true;
117
+ return allowList.includes(sortString);
118
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontic/nuxt",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Nuxt module for Frontic - data fetching composables with smart caching, page routing, and context management",
5
5
  "license": "MIT",
6
6
  "author": "Frontic",