@frontic/nuxt 0.8.3 → 1.0.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 (52) hide show
  1. package/README.md +30 -2
  2. package/dist/module.d.mts +2 -132
  3. package/dist/module.json +2 -2
  4. package/dist/module.mjs +63 -7
  5. package/dist/runtime/composables/analytics.d.ts +82 -0
  6. package/dist/runtime/composables/analytics.js +38 -0
  7. package/dist/runtime/composables/blocks.d.ts +24 -22
  8. package/dist/runtime/composables/blocks.js +16 -16
  9. package/dist/runtime/composables/index.d.ts +1 -1
  10. package/dist/runtime/composables/listings.d.ts +22 -13
  11. package/dist/runtime/composables/listings.js +24 -25
  12. package/dist/runtime/composables/pages.d.ts +21 -18
  13. package/dist/runtime/composables/pages.js +15 -16
  14. package/dist/runtime/composables/trees.d.ts +24 -22
  15. package/dist/runtime/composables/trees.js +15 -25
  16. package/dist/runtime/composables/useFronticBlock.d.ts +22 -13
  17. package/dist/runtime/composables/useFronticBlock.js +19 -2
  18. package/dist/runtime/composables/useFronticClient.d.ts +6 -3
  19. package/dist/runtime/composables/useFronticContext.d.ts +12 -0
  20. package/dist/runtime/composables/useFronticContext.js +71 -9
  21. package/dist/runtime/composables/useFronticListing.d.ts +23 -19
  22. package/dist/runtime/composables/useFronticListing.js +22 -3
  23. package/dist/runtime/composables/useFronticPage.d.ts +35 -16
  24. package/dist/runtime/composables/useFronticPage.js +36 -7
  25. package/dist/runtime/composables/useFronticSearch.d.ts +4 -96
  26. package/dist/runtime/composables/useFronticSearch.js +179 -51
  27. package/dist/runtime/composables/useFronticTree.d.ts +23 -14
  28. package/dist/runtime/composables/useFronticTree.js +19 -2
  29. package/dist/runtime/server/plugins/fetch-secret.d.ts +2 -0
  30. package/dist/runtime/server/plugins/fetch-secret.js +20 -0
  31. package/dist/runtime/types/client.d.ts +34 -0
  32. package/dist/runtime/types/client.js +0 -0
  33. package/dist/runtime/types/index.d.ts +8 -3
  34. package/dist/runtime/types/listing.d.ts +113 -251
  35. package/dist/runtime/types/options.d.ts +139 -0
  36. package/dist/runtime/types/options.js +0 -0
  37. package/dist/runtime/types/query.d.ts +88 -0
  38. package/dist/runtime/types/query.js +0 -0
  39. package/dist/runtime/types/registry.d.ts +272 -0
  40. package/dist/runtime/types/registry.js +0 -0
  41. package/dist/runtime/types/search.d.ts +56 -36
  42. package/dist/runtime/utils/errors.d.ts +22 -0
  43. package/dist/runtime/utils/errors.js +3 -0
  44. package/dist/runtime/utils/index.d.ts +2 -0
  45. package/dist/runtime/utils/index.js +2 -0
  46. package/dist/runtime/utils/query-keys.d.ts +27 -0
  47. package/dist/runtime/utils/query-keys.js +18 -0
  48. package/dist/runtime/utils/state-helpers.d.ts +3 -6
  49. package/dist/runtime/utils/state-helpers.js +7 -8
  50. package/dist/types.d.mts +2 -2
  51. package/package.json +15 -15
  52. package/dist/runtime/frontic-stack.d.ts +0 -168
@@ -1,21 +1,35 @@
1
- import { useState } from "nuxt/app";
1
+ import { useState, useNuxtApp } from "nuxt/app";
2
2
  import { computed, watch, ref, toValue } from "vue";
3
- import { useQuery, useInfiniteQuery, useQueryCache } from "@pinia/colada";
3
+ import { useQuery, useInfiniteQuery, useQueryCache, setInfiniteQueryData } from "@pinia/colada";
4
4
  import { useDebounceFn } from "@vueuse/core";
5
- import { makeLogicalFilter, manageFilter, removeFilter, isRangeFilterValue, manageRangeFilter, removeRangeFilter } from "../utils/filter-helpers.js";
5
+ import {
6
+ makeLogicalFilter,
7
+ manageFilter,
8
+ removeFilter,
9
+ isRangeFilterValue,
10
+ manageRangeFilter,
11
+ removeRangeFilter
12
+ } from "../utils/filter-helpers.js";
6
13
  import { makeFilterState, processAvailableFilters, processAvailableSorts, applyFilterConfig, countActiveFilters, parseSortString, isSortAllowed } from "../utils/state-helpers.js";
7
14
  import { fetchListingQuery, LISTING_QUERY_KEYS } from "./listings.js";
8
15
  import { useFronticClient } from "./useFronticClient.js";
9
- export function useFronticSearch(name, params, options) {
16
+ import { emit, emitOnce, bindRouteReset, toAnalyticsItems, FRONTIC_ANALYTICS_VERSION } from "./analytics.js";
17
+ export function useFronticSearch(name, ...args) {
18
+ const [rawParams, options] = args;
19
+ const params = rawParams ?? {};
10
20
  const queryCache = useQueryCache();
11
21
  const _client = useFronticClient();
12
22
  const listingName = name;
23
+ const nuxtApp = useNuxtApp();
24
+ bindRouteReset(nuxtApp);
13
25
  const cacheKey = options?.cacheKey ?? String(name);
14
26
  const contextKey = options?.contextKey;
15
27
  const contextDomain = options?.contextDomain;
16
28
  const requestUrl = options?.requestUrl;
17
29
  const searchTermThreshold = options?.searchTermThreshold ?? 2;
18
30
  const searchDebounce = options?.searchDebounce ?? 200;
31
+ const searchCommitMs = options?.analytics?.searchCommitMs ?? 1e3;
32
+ const searchMinChars = options?.analytics?.searchMinChars ?? 3;
19
33
  const orFilter = options?.orFilter ?? [];
20
34
  const filter = options?.filter;
21
35
  const sorting = options?.sorting;
@@ -26,13 +40,27 @@ export function useFronticSearch(name, params, options) {
26
40
  const staleTime = options?.staleTime ?? 1e3 * 60 * 5;
27
41
  const infinite = options?.infinite ?? false;
28
42
  const initialPage = Math.max(1, Math.floor(options?.initialPage ?? 1));
29
- const filterConfig = filter || {};
30
- const sortConfig = sorting || {};
43
+ if (import.meta.dev) {
44
+ const nuxtAppWithRegistry = nuxtApp;
45
+ const registry = nuxtAppWithRegistry._fronticSearchParams ??= /* @__PURE__ */ new Map();
46
+ const paramsSignature = JSON.stringify(toValue(params) ?? {});
47
+ const knownSignature = registry.get(cacheKey);
48
+ if (knownSignature !== void 0 && knownSignature !== paramsSignature) {
49
+ console.warn(
50
+ `[@frontic/nuxt] useFronticSearch('${String(name)}') is called with different params but the same cacheKey '${cacheKey}'. These instances share search/filter/page state. Pass a distinct \`cacheKey\` option to separate them.`
51
+ );
52
+ }
53
+ registry.set(cacheKey, paramsSignature);
54
+ }
55
+ const filterConfig = filter ?? {};
56
+ const sortConfig = sorting ?? {};
31
57
  const searchTerm = useState(`${cacheKey}-searchTerm`, () => "");
32
58
  const _orFilterList = useState(`${cacheKey}-orFilterList`, () => []);
33
59
  const _andFilterList = useState(`${cacheKey}-andFilterList`, () => []);
34
60
  const _rangeFilterList = useState(`${cacheKey}-rangeFilterList`, () => []);
35
61
  const _sortQuery = useState(`${cacheKey}-sortQuery`, () => void 0);
62
+ const _page = useState(`${cacheKey}-page`, () => void 0);
63
+ const _search = useState(`${cacheKey}-search`, () => void 0);
36
64
  const searchState = useState(`${cacheKey}-searchState`, () => ({
37
65
  active: {
38
66
  filter: {},
@@ -57,12 +85,14 @@ export function useFronticSearch(name, params, options) {
57
85
  }
58
86
  }
59
87
  }));
60
- const apiQuery = computed(() => ({
61
- sort: !disableSorting ? _sortQuery.value : void 0,
62
- search: !disableSearch && searchTerm.value && searchTerm.value.trim().length > searchTermThreshold ? searchTerm.value : void 0,
63
- filter: !disableFilter ? [...makeLogicalFilter("or", _orFilterList.value), ...makeLogicalFilter("and", _andFilterList.value), ..._rangeFilterList.value] : void 0,
64
- limit
65
- }));
88
+ const apiQuery = computed(
89
+ () => ({
90
+ sort: !disableSorting ? _sortQuery.value : void 0,
91
+ search: !disableSearch ? _search.value : void 0,
92
+ filter: !disableFilter ? [...makeLogicalFilter("or", _orFilterList.value), ...makeLogicalFilter("and", _andFilterList.value), ..._rangeFilterList.value] : void 0,
93
+ limit
94
+ })
95
+ );
66
96
  const queryConfig = {
67
97
  name: listingName,
68
98
  params,
@@ -71,32 +101,27 @@ export function useFronticSearch(name, params, options) {
71
101
  contextDomain,
72
102
  requestUrl,
73
103
  staleTime,
104
+ gcTime: options?.gcTime,
105
+ enabled: options?.enabled,
106
+ keepPreviousData: options?.keepPreviousData,
74
107
  _client
75
108
  };
76
109
  let data;
77
110
  let status;
111
+ let asyncStatus;
112
+ let isLoading;
113
+ let error;
78
114
  let refresh;
79
115
  let refetch;
80
116
  let loadNextFn;
81
117
  let loadPrevFn;
82
118
  let loadPageFn;
83
- async function fetchPage(pageNumber) {
84
- const pageQuery = fetchListingQuery({
85
- ...queryConfig,
86
- page: ref(pageNumber)
87
- });
88
- const response = await pageQuery.query();
89
- if (response) {
90
- const baseCacheKey = LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value);
91
- queryCache.setQueryData(baseCacheKey, response);
92
- updateState(response);
93
- }
94
- return response;
95
- }
96
119
  if (infinite) {
97
120
  const infiniteResult = useInfiniteQuery({
98
- key: () => LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value),
99
- initialPageParam: initialPage,
121
+ key: () => LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value, toValue(contextKey), toValue(contextDomain)),
122
+ // `_page` seeds the starting cursor (e.g. deep-linked page from the URL); it deliberately does NOT enter the
123
+ // key above — in infinite mode page is a cursor, not an identity, so keying on it would reset accumulation.
124
+ initialPageParam: _page.value ?? initialPage,
100
125
  query: async ({ pageParam }) => {
101
126
  const pagedQueryFactory = fetchListingQuery({
102
127
  ...queryConfig,
@@ -122,7 +147,7 @@ export function useFronticSearch(name, params, options) {
122
147
  const pages = infiniteResult.data.value?.pages;
123
148
  if (!pages?.length) return void 0;
124
149
  const lastPage = pages[pages.length - 1];
125
- const allItems = pages.flatMap((page) => page?.items || []);
150
+ const allItems = pages.flatMap((page) => page?.items ?? []);
126
151
  return {
127
152
  ...lastPage,
128
153
  items: allItems
@@ -130,49 +155,75 @@ export function useFronticSearch(name, params, options) {
130
155
  });
131
156
  data = flattenedData;
132
157
  status = infiniteResult.status;
158
+ asyncStatus = infiniteResult.asyncStatus;
159
+ isLoading = infiniteResult.isLoading;
160
+ error = infiniteResult.error;
133
161
  refresh = infiniteResult.refresh;
134
162
  refetch = infiniteResult.refetch;
135
- loadNextFn = () => infiniteResult.loadNextPage();
136
- loadPrevFn = () => infiniteResult.loadPreviousPage();
163
+ loadNextFn = async () => {
164
+ await infiniteResult.loadNextPage();
165
+ if (flattenedData.value) emitListingResolved(flattenedData.value, "loadMore");
166
+ return flattenedData.value;
167
+ };
168
+ loadPrevFn = async () => {
169
+ await infiniteResult.loadPreviousPage();
170
+ if (flattenedData.value) emitListingResolved(flattenedData.value, "loadMore");
171
+ return flattenedData.value;
172
+ };
137
173
  loadPageFn = async (page) => {
138
- const cacheKey2 = LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value);
139
- queryCache.setQueryData(cacheKey2, { pages: [], pageParams: [] });
140
174
  const pagedQueryFactory = fetchListingQuery({
141
175
  ...queryConfig,
142
176
  page: ref(page)
143
177
  });
144
178
  const response = await pagedQueryFactory.query();
145
179
  if (response) {
146
- queryCache.setQueryData(cacheKey2, { pages: [response], pageParams: [page] });
180
+ const listKey = LISTING_QUERY_KEYS.detail(
181
+ String(listingName),
182
+ toValue(params),
183
+ apiQuery.value,
184
+ toValue(contextKey),
185
+ toValue(contextDomain)
186
+ );
187
+ setInfiniteQueryData(queryCache, listKey, { pages: [response], pageParams: [page] });
147
188
  updateState(response);
189
+ emitListingResolved(response, "page");
148
190
  }
149
191
  return response;
150
192
  };
151
193
  } else {
152
- const queryResult = useQuery(fetchListingQuery(queryConfig));
194
+ const queryResult = useQuery(fetchListingQuery({ ...queryConfig, page: _page }));
153
195
  data = queryResult.data;
154
196
  status = queryResult.status;
197
+ asyncStatus = queryResult.asyncStatus;
198
+ isLoading = queryResult.isLoading;
199
+ error = queryResult.error;
155
200
  refresh = queryResult.refresh;
156
201
  refetch = queryResult.refetch;
202
+ async function goToPage(page) {
203
+ _page.value = page;
204
+ await withIntent("page");
205
+ return data.value;
206
+ }
157
207
  loadNextFn = async () => {
158
208
  const pageData = data.value?.page;
159
209
  if (!pageData?.next) return void 0;
160
- return await fetchPage(pageData.next);
210
+ return await goToPage(pageData.next);
161
211
  };
162
212
  loadPrevFn = async () => {
163
213
  const pageData = data.value?.page;
164
214
  if (!pageData?.prev) return void 0;
165
- return await fetchPage(pageData.prev);
215
+ return await goToPage(pageData.prev);
166
216
  };
167
217
  loadPageFn = async (page) => {
168
- return await fetchPage(page);
218
+ return await goToPage(page);
169
219
  };
170
220
  }
171
221
  if (!disableSearch) {
172
222
  watch(searchTerm, () => {
173
- if (searchTerm.value.trim().length > searchTermThreshold || searchState.value.active.search) {
223
+ if (searchTerm.value.trim().length > searchTermThreshold || _search.value !== void 0) {
174
224
  triggerSearchFromInput();
175
225
  }
226
+ commitSearchTerm();
176
227
  });
177
228
  }
178
229
  watch(
@@ -180,10 +231,36 @@ export function useFronticSearch(name, params, options) {
180
231
  (newData) => {
181
232
  if (newData) {
182
233
  updateState(newData);
234
+ emitListingResolved(newData, "initial");
183
235
  }
184
236
  },
185
237
  { immediate: true }
186
238
  );
239
+ function emitListingResolved(response, trigger, changedFilter) {
240
+ const pageData = response.page;
241
+ const page = pageData?.current ?? 1;
242
+ const limit2 = pageData?.limit ?? 0;
243
+ const items = response.items ?? [];
244
+ const payload = {
245
+ listing: String(listingName),
246
+ cacheKey,
247
+ trigger,
248
+ ...changedFilter && { changedFilter },
249
+ ...searchState.value.active.search && { term: searchState.value.active.search },
250
+ filters: searchState.value.active.filter,
251
+ ...searchState.value.active.sorting && { sort: searchState.value.active.sorting },
252
+ page,
253
+ resultCount: items.length,
254
+ totalCount: response.total ?? 0,
255
+ items: toAnalyticsItems(items, (page - 1) * limit2),
256
+ version: FRONTIC_ANALYTICS_VERSION
257
+ };
258
+ if (trigger === "initial") {
259
+ emitOnce(nuxtApp, `${cacheKey}:initial`, "frontic:listing:resolved", payload);
260
+ return;
261
+ }
262
+ emit(nuxtApp, "frontic:listing:resolved", payload);
263
+ }
187
264
  function updateState(response) {
188
265
  const rawFilters = response.filter;
189
266
  const rawAggregation = response.aggregation;
@@ -228,18 +305,45 @@ export function useFronticSearch(name, params, options) {
228
305
  filter: availableFilters.length,
229
306
  sorting: availableSorts.length,
230
307
  result: response.total ?? 0,
231
- page: pageData?.total ?? 1
308
+ page: pageData?.last ?? 1
232
309
  }
233
310
  }
234
311
  };
235
312
  }
236
313
  async function refreshListing() {
314
+ return runRefresh();
315
+ }
316
+ async function runRefresh(intent) {
237
317
  await refresh();
238
318
  if (data.value) {
239
319
  updateState(data.value);
320
+ if (intent) emitListingResolved(data.value, intent.trigger, intent.changedFilter);
240
321
  }
241
322
  }
242
- const triggerSearchFromInput = useDebounceFn(refreshListing, searchDebounce);
323
+ function resetPage() {
324
+ _page.value = void 0;
325
+ }
326
+ function withIntent(trigger, changedFilter) {
327
+ return runRefresh({ trigger, changedFilter });
328
+ }
329
+ const triggerSearchFromInput = useDebounceFn(() => {
330
+ const committed = searchTerm.value.trim().length > searchTermThreshold ? searchTerm.value : void 0;
331
+ if (committed === _search.value) return;
332
+ resetPage();
333
+ _search.value = committed;
334
+ return withIntent("term");
335
+ }, searchDebounce);
336
+ const commitSearchTerm = useDebounceFn(() => {
337
+ const term = searchTerm.value.trim();
338
+ if (term.length < searchMinChars) return;
339
+ emit(nuxtApp, "frontic:search:committed", {
340
+ term,
341
+ cacheKey,
342
+ resultCount: data.value?.items?.length ?? 0,
343
+ page: searchState.value.active.page,
344
+ version: FRONTIC_ANALYTICS_VERSION
345
+ });
346
+ }, searchCommitMs);
243
347
  async function sortResult(sortBy) {
244
348
  if (disableSorting) return;
245
349
  if (!sortBy) {
@@ -253,30 +357,34 @@ export function useFronticSearch(name, params, options) {
253
357
  _sortQuery.value = sortValue;
254
358
  }
255
359
  }
256
- await refreshListing();
360
+ resetPage();
361
+ await withIntent("sort");
257
362
  }
258
363
  async function resetSorting() {
259
364
  if (disableSorting) return;
260
365
  _sortQuery.value = void 0;
261
- await refreshListing();
366
+ resetPage();
367
+ await withIntent("sort");
262
368
  }
263
369
  async function filterResult(filterField, filterOptions) {
264
370
  if (disableFilter) return;
371
+ resetPage();
265
372
  if (filterOptions.length > 0 && isRangeFilterValue(filterOptions[0])) {
266
373
  _rangeFilterList.value = manageRangeFilter(_rangeFilterList.value, filterField, filterOptions[0]);
267
- await refreshListing();
374
+ await withIntent("filter", { field: filterField, value: filterOptions[0], action: "add" });
268
375
  return;
269
376
  }
270
377
  const shouldUseOr = orFilter.includes(filterField);
271
378
  const targetList = shouldUseOr ? _orFilterList : _andFilterList;
272
379
  targetList.value = manageFilter(targetList.value, filterField, filterOptions);
273
- await refreshListing();
380
+ await withIntent("filter", { field: filterField, value: filterOptions, action: "add" });
274
381
  }
275
382
  async function addFilterOption(filterField, filterOption) {
276
383
  if (disableFilter) return;
384
+ resetPage();
277
385
  if (isRangeFilterValue(filterOption)) {
278
386
  _rangeFilterList.value = manageRangeFilter(_rangeFilterList.value, filterField, filterOption);
279
- await refreshListing();
387
+ await withIntent("filter", { field: filterField, value: filterOption, action: "add" });
280
388
  return;
281
389
  }
282
390
  const shouldUseOr = orFilter.includes(filterField);
@@ -284,18 +392,20 @@ export function useFronticSearch(name, params, options) {
284
392
  const existingFilter = targetList.value.find((filter2) => filter2.field === filterField);
285
393
  const currentValues = existingFilter ? Array.isArray(existingFilter.value) ? existingFilter.value : [existingFilter.value] : [];
286
394
  targetList.value = manageFilter(targetList.value, filterField, [...currentValues, filterOption]);
287
- await refreshListing();
395
+ await withIntent("filter", { field: filterField, value: filterOption, action: "add" });
288
396
  }
289
397
  async function removeFilterOption(filterField, filterOption) {
290
398
  if (disableFilter) return;
399
+ resetPage();
291
400
  _rangeFilterList.value = removeRangeFilter(_rangeFilterList.value, filterField);
292
401
  const shouldUseOr = orFilter.includes(filterField);
293
402
  const targetList = shouldUseOr ? _orFilterList : _andFilterList;
294
403
  targetList.value = removeFilter(targetList.value, filterField, filterOption);
295
- await refreshListing();
404
+ await withIntent("filter", { field: filterField, value: filterOption, action: "remove" });
296
405
  }
297
406
  async function resetFilter(filterField) {
298
407
  if (disableFilter) return;
408
+ resetPage();
299
409
  if (!filterField) {
300
410
  _orFilterList.value = [];
301
411
  _andFilterList.value = [];
@@ -306,19 +416,23 @@ export function useFronticSearch(name, params, options) {
306
416
  const targetList = shouldUseOr ? _orFilterList : _andFilterList;
307
417
  targetList.value = removeFilter(targetList.value, filterField);
308
418
  }
309
- await refreshListing();
419
+ await withIntent("filter", filterField ? { field: filterField, action: "remove" } : void 0);
310
420
  }
311
421
  async function resetSearch() {
312
422
  searchTerm.value = "";
313
- await refreshListing();
423
+ _search.value = void 0;
424
+ resetPage();
425
+ await withIntent("term");
314
426
  }
315
427
  async function reset() {
316
428
  searchTerm.value = "";
429
+ _search.value = void 0;
317
430
  _orFilterList.value = [];
318
431
  _andFilterList.value = [];
319
432
  _rangeFilterList.value = [];
320
433
  _sortQuery.value = void 0;
321
- await refreshListing();
434
+ _page.value = void 0;
435
+ await withIntent("reset");
322
436
  }
323
437
  return {
324
438
  // ========== State ==========
@@ -327,9 +441,23 @@ export function useFronticSearch(name, params, options) {
327
441
  */
328
442
  result: data,
329
443
  /**
330
- * Query status: 'pending' | 'error' | 'success'
444
+ * Data status: 'pending' | 'error' | 'success'
331
445
  */
332
446
  status,
447
+ /**
448
+ * Network status: 'idle' | 'loading'. Together with `status` this
449
+ * distinguishes a first load (`pending`) from a background refresh
450
+ * (`success` + 'loading').
451
+ */
452
+ asyncStatus,
453
+ /**
454
+ * Whether a request is in flight (shortcut for `asyncStatus === 'loading'`)
455
+ */
456
+ isLoading,
457
+ /**
458
+ * Error of the last fetch, null while pending or after success
459
+ */
460
+ error,
333
461
  /**
334
462
  * Current search state including active filters, sorts, pagination, and available options.
335
463
  * Use this to build filter/sort UI components.
@@ -1,6 +1,6 @@
1
1
  import type { Ref, MaybeRef, ComputedRef } from 'vue';
2
- import type { Trees, Responses } from '@frontic/stack/generated-types';
3
- import type { FronticRequestOptions } from '../types/listing.js';
2
+ import type { TreeName, ResponseOf } from '../types/registry.js';
3
+ import type { FronticRequestOptions, FronticQueryOptions } from '../types/listing.js';
4
4
  /**
5
5
  * Extracts the `items` array type from a tree response.
6
6
  *
@@ -19,7 +19,7 @@ import type { FronticRequestOptions } from '../types/listing.js';
19
19
  type TreeItems<TResponse> = [TResponse] extends [{
20
20
  items?: infer I;
21
21
  }] ? (unknown extends I ? unknown[] : Exclude<I, undefined>) : unknown[];
22
- export interface UseFronticTreeOptions extends FronticRequestOptions {
22
+ export interface UseFronticTreeOptions extends FronticRequestOptions, FronticQueryOptions {
23
23
  /**
24
24
  * Optional starting node key. When provided, the response contains the
25
25
  * subtree rooted at this node. When omitted, all root-level nodes are returned.
@@ -30,11 +30,6 @@ export interface UseFronticTreeOptions extends FronticRequestOptions {
30
30
  * When omitted, all levels are returned (subject to the API's 250-node cap).
31
31
  */
32
32
  depth?: MaybeRef<number | undefined>;
33
- /**
34
- * Cache stale time in milliseconds
35
- * @default 300000 (5 minutes)
36
- */
37
- staleTime?: number;
38
33
  }
39
34
  /**
40
35
  * Fetch a Frontic tree by name
@@ -58,11 +53,11 @@ export interface UseFronticTreeOptions extends FronticRequestOptions {
58
53
  * const { items } = useFronticTree('CategoryNavigation', { key: startKey })
59
54
  * ```
60
55
  */
61
- export declare function useFronticTree<T extends keyof Trees>(name: T, options?: UseFronticTreeOptions): {
56
+ export declare function useFronticTree<T extends TreeName>(name: T, options?: UseFronticTreeOptions): {
62
57
  /**
63
58
  * The full tree response, typed based on the tree name
64
59
  */
65
- tree: Ref<Responses[T] | undefined>;
60
+ tree: Ref<ResponseOf<T> | undefined>;
66
61
  /**
67
62
  * The tree's top-level nodes (shortcut for `tree.value?.items`).
68
63
  * Each node carries its children on `$items`.
@@ -71,18 +66,32 @@ export declare function useFronticTree<T extends keyof Trees>(name: T, options?:
71
66
  * shape from their generated client — including the `$items` recursion
72
67
  * and the fields produced by the tree's Detail Block.
73
68
  */
74
- items: ComputedRef<TreeItems<Responses[T]> | undefined>;
69
+ items: ComputedRef<TreeItems<ResponseOf<T>> | undefined>;
75
70
  /**
76
- * Query status: 'pending' | 'error' | 'success'
71
+ * Data status: 'pending' | 'error' | 'success'
77
72
  */
78
73
  status: import("vue").ShallowRef<import("@pinia/colada").DataStateStatus>;
74
+ /**
75
+ * Network status: 'idle' | 'loading'. Together with `status` this
76
+ * distinguishes a first load (`pending`) from a background refresh
77
+ * (`success` + 'loading').
78
+ */
79
+ asyncStatus: ComputedRef<import("@pinia/colada").AsyncStatus>;
80
+ /**
81
+ * Whether a request is in flight (shortcut for `asyncStatus === 'loading'`)
82
+ */
83
+ isLoading: import("vue").ShallowRef<boolean>;
84
+ /**
85
+ * Error of the last fetch, null while pending or after success
86
+ */
87
+ error: import("vue").ShallowRef<Error | null>;
79
88
  /**
80
89
  * Manually refresh the tree data (uses cache if valid)
81
90
  */
82
- refresh: (throwOnError?: boolean) => Promise<import("@pinia/colada").DataState<unknown, Error, undefined>>;
91
+ refresh: (throwOnError?: boolean) => Promise<import("@pinia/colada").DataState<ResponseOf<T>, Error, undefined>>;
83
92
  /**
84
93
  * Force a fresh fetch of the tree data, bypassing cache
85
94
  */
86
- refetch: (throwOnError?: boolean) => Promise<import("@pinia/colada").DataState<unknown, Error, undefined>>;
95
+ refetch: (throwOnError?: boolean) => Promise<import("@pinia/colada").DataState<ResponseOf<T>, Error, undefined>>;
87
96
  };
88
97
  export {};
@@ -12,9 +12,12 @@ export function useFronticTree(name, options) {
12
12
  contextDomain: options?.contextDomain,
13
13
  requestUrl: options?.requestUrl,
14
14
  staleTime: options?.staleTime,
15
+ gcTime: options?.gcTime,
16
+ enabled: options?.enabled,
17
+ keepPreviousData: options?.keepPreviousData,
15
18
  _client
16
19
  });
17
- const { data, status, refresh, refetch } = useQuery(treeQuery);
20
+ const { data, status, asyncStatus, isLoading, error, refresh, refetch } = useQuery(treeQuery);
18
21
  return {
19
22
  /**
20
23
  * The full tree response, typed based on the tree name
@@ -30,9 +33,23 @@ export function useFronticTree(name, options) {
30
33
  */
31
34
  items: computed(() => data.value?.items),
32
35
  /**
33
- * Query status: 'pending' | 'error' | 'success'
36
+ * Data status: 'pending' | 'error' | 'success'
34
37
  */
35
38
  status,
39
+ /**
40
+ * Network status: 'idle' | 'loading'. Together with `status` this
41
+ * distinguishes a first load (`pending`) from a background refresh
42
+ * (`success` + 'loading').
43
+ */
44
+ asyncStatus,
45
+ /**
46
+ * Whether a request is in flight (shortcut for `asyncStatus === 'loading'`)
47
+ */
48
+ isLoading,
49
+ /**
50
+ * Error of the last fetch, null while pending or after success
51
+ */
52
+ error,
36
53
  /**
37
54
  * Manually refresh the tree data (uses cache if valid)
38
55
  */
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nitropack").NitroAppPlugin;
2
+ export default _default;
@@ -0,0 +1,20 @@
1
+ import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime";
2
+ const PATCHED = Symbol.for("frontic.fetchSecret");
3
+ export default defineNitroPlugin(() => {
4
+ const config = useRuntimeConfig();
5
+ const secret = config.frontic?.fetchApiSecret;
6
+ if (!secret) return;
7
+ const upstream = globalThis.fetch;
8
+ if (upstream[PATCHED]) return;
9
+ const patched = async (input, init) => {
10
+ const source = init?.headers ?? (input instanceof Request ? input.headers : void 0);
11
+ const headers = new Headers(source);
12
+ if (!headers.has("fs-version") || headers.has("fs-secret") || headers.has("fs-target-url")) {
13
+ return upstream(input, init);
14
+ }
15
+ headers.set("fs-secret", secret);
16
+ return upstream(input, { ...init, headers });
17
+ };
18
+ patched[PATCHED] = true;
19
+ globalThis.fetch = patched;
20
+ });
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Frontic Client Interface
3
+ *
4
+ * Module-owned type of the client returned by `useFronticClient`. The generated
5
+ * runtime client (`.frontic/generated-client.ts`) implements this structurally;
6
+ * all name and response typing flows from the registry, so the module never
7
+ * depends on types exported by generated files.
8
+ *
9
+ */
10
+ import type { BlockName, ListingName, TreeName, ListingParamsOf, ListingFiltersOf, ListingSortsOf, ResponseOf, RequestOptions, TreeQuery, Page, Context, ContextOption } from './registry.js';
11
+ import type { Query } from './query.js';
12
+ export interface FronticClient {
13
+ /** Fetch a block by name and key */
14
+ block<T extends BlockName>(name: T, key: string, config?: RequestOptions): Promise<ResponseOf<T>>;
15
+ /** Fetch a listing by name and parameters, with optional query options */
16
+ listing<T extends ListingName>(name: T, parameters: ListingParamsOf<T>, config?: {
17
+ query?: Query<ListingFiltersOf<T>, ListingSortsOf<T>>;
18
+ } & RequestOptions): Promise<ResponseOf<T>>;
19
+ /** Fetch a tree by name */
20
+ tree<T extends TreeName>(name: T, config?: {
21
+ query?: TreeQuery;
22
+ } & RequestOptions): Promise<ResponseOf<T>>;
23
+ /** Fetch a page by slug */
24
+ page(slug: string, config?: RequestOptions): Promise<Page>;
25
+ /** Fetch the context for a token */
26
+ context(token: string, config?: RequestOptions): Promise<Context>;
27
+ /** Fetch available context options; returns the options and the (possibly new) token */
28
+ contextList(token?: string, config?: RequestOptions): Promise<[ContextOption[], string]>;
29
+ /** Switch region/locale for the given token */
30
+ contextUpdate(context: {
31
+ region: string;
32
+ locale: string;
33
+ }, token: string, config?: RequestOptions): Promise<Context>;
34
+ }
File without changes
@@ -3,12 +3,17 @@
3
3
  *
4
4
  * Export all public types from this file.
5
5
  */
6
- export type { FronticOptions, FronticComposable, FronticComposablesConfig } from '../../module.js';
7
- export type { InclusionMode, FilterField, SortField, SortString, ListingFieldConfig, FilterOption, UiFilter, UiSort, AggregationTotal, } from './listing.js';
6
+ export type { FronticOptions, FronticComposable, FronticComposablesConfig } from './options.js';
7
+ export type { Blocks, Listings, ListingParameters, ListingQueryFilters, ListingQuerySorts, Trees, Responses, ResponseOf, ListingParamsOf, ListingFiltersOf, ListingSortsOf, RequestOptions, TreeQuery, BlockName, ListingName, TreeName, Page, PageData, PageRoute, RouteMeta, AlternateRoute, Context, ContextOption, ApiError, InternalError, FronticApiError, DefaultApiError, DefaultInternalError, } from './registry.js';
8
+ export type { Query, Sort, Filter, EqualsFilter, LogicalFilter, RangeFilter, ContainsFilter } from './query.js';
9
+ export type { FronticClient } from './client.js';
10
+ export type { FronticRequestOptions, FronticQueryOptions, InclusionMode, FilterField, SortField, SortString, SortStringOf, ListingQuery, ListingEnvelope, ListingFieldConfig, FilterOption, UiFilter, UiSort, AggregationStats, Pagination, FilterData, AggregationData, FilterGroup, AggregationGroup, } from './listing.js';
8
11
  export type { RangeFilterValue } from '../utils/filter-helpers.js';
12
+ export type { FronticAnalyticsItem, FronticListingTrigger, FronticListingResolved, FronticSearchCommitted, FronticPageResolved } from '../composables/analytics.js';
9
13
  export type { SearchState, UseFronticSearchOptions, UseSearchReturn } from './search.js';
10
14
  export type { UseFronticClientOptions } from '../composables/useFronticClient.js';
11
15
  export type { UseFronticBlockOptions } from '../composables/useFronticBlock.js';
12
16
  export type { UseFronticPageOptions } from '../composables/useFronticPage.js';
13
- export type { UseFronticContextOptions } from '../composables/useFronticContext.js';
17
+ export type { UseFronticContextOptions, FronticContext } from '../composables/useFronticContext.js';
14
18
  export type { UseFronticListingOptions } from '../composables/useFronticListing.js';
19
+ export type { UseFronticTreeOptions } from '../composables/useFronticTree.js';