@frontic/nuxt 0.8.4 → 1.1.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 (64) hide show
  1. package/README.md +65 -4
  2. package/dist/module.d.mts +2 -132
  3. package/dist/module.json +2 -2
  4. package/dist/module.mjs +130 -15
  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 +25 -4
  18. package/dist/runtime/composables/useFronticClient.d.ts +9 -28
  19. package/dist/runtime/composables/useFronticClient.js +59 -48
  20. package/dist/runtime/composables/useFronticContext.d.ts +12 -0
  21. package/dist/runtime/composables/useFronticContext.js +71 -9
  22. package/dist/runtime/composables/useFronticListing.d.ts +23 -19
  23. package/dist/runtime/composables/useFronticListing.js +28 -5
  24. package/dist/runtime/composables/useFronticPage.d.ts +35 -16
  25. package/dist/runtime/composables/useFronticPage.js +42 -20
  26. package/dist/runtime/composables/useFronticSearch.d.ts +4 -96
  27. package/dist/runtime/composables/useFronticSearch.js +193 -60
  28. package/dist/runtime/composables/useFronticTree.d.ts +23 -14
  29. package/dist/runtime/composables/useFronticTree.js +25 -5
  30. package/dist/runtime/server/api/frontic/[...path].js +48 -10
  31. package/dist/runtime/server/middleware/sitemap.d.ts +2 -0
  32. package/dist/runtime/server/middleware/sitemap.js +55 -0
  33. package/dist/runtime/server/plugins/fetch-secret.d.ts +2 -0
  34. package/dist/runtime/server/plugins/fetch-secret.js +20 -0
  35. package/dist/runtime/types/client.d.ts +36 -0
  36. package/dist/runtime/types/client.js +0 -0
  37. package/dist/runtime/types/errors.d.ts +47 -0
  38. package/dist/runtime/types/errors.js +1 -0
  39. package/dist/runtime/types/index.d.ts +9 -3
  40. package/dist/runtime/types/listing.d.ts +113 -251
  41. package/dist/runtime/types/options.d.ts +169 -0
  42. package/dist/runtime/types/options.js +0 -0
  43. package/dist/runtime/types/query.d.ts +88 -0
  44. package/dist/runtime/types/query.js +0 -0
  45. package/dist/runtime/types/registry.d.ts +272 -0
  46. package/dist/runtime/types/registry.js +0 -0
  47. package/dist/runtime/types/search.d.ts +90 -38
  48. package/dist/runtime/utils/describe-error.d.ts +38 -0
  49. package/dist/runtime/utils/describe-error.js +38 -0
  50. package/dist/runtime/utils/errors.d.ts +22 -0
  51. package/dist/runtime/utils/errors.js +3 -0
  52. package/dist/runtime/utils/filter-helpers.d.ts +13 -0
  53. package/dist/runtime/utils/filter-helpers.js +14 -0
  54. package/dist/runtime/utils/index.d.ts +2 -0
  55. package/dist/runtime/utils/index.js +2 -0
  56. package/dist/runtime/utils/query-keys.d.ts +27 -0
  57. package/dist/runtime/utils/query-keys.js +18 -0
  58. package/dist/runtime/utils/resolve-context-domain.d.ts +14 -0
  59. package/dist/runtime/utils/resolve-context-domain.js +9 -1
  60. package/dist/runtime/utils/state-helpers.d.ts +3 -6
  61. package/dist/runtime/utils/state-helpers.js +7 -8
  62. package/dist/types.d.mts +2 -2
  63. package/package.json +15 -15
  64. package/dist/runtime/frontic-stack.d.ts +0 -168
package/README.md CHANGED
@@ -10,6 +10,7 @@ Nuxt module for building with the [Frontic](https://frontic.com) API and [Fronti
10
10
  - **Page routing** - Dynamic page resolution with automatic redirects and 404 handling
11
11
  - **Context management** - Locale and region switching with cookie persistence
12
12
  - **Infinite scroll** - Bidirectional infinite loading with deep-link support via Pinia Colada's `useInfiniteQuery`
13
+ - **Analytics hooks** - Typed `frontic:listing:resolved`, `frontic:search:committed` and `frontic:page:resolved` events for any analytics vendor
13
14
  - **Built-in proxy** - CORS-free API requests through your Nuxt server
14
15
 
15
16
  ## Installation
@@ -25,7 +26,7 @@ npx nuxi@latest module add @frontic/nuxt
25
26
  export default defineNuxtConfig({
26
27
  modules: ['@frontic/nuxt'],
27
28
  frontic: {
28
- contextDomain: 'your-shop.com',
29
+ contextDomain: 'demo-shop.com',
29
30
  },
30
31
  })
31
32
  ```
@@ -71,7 +72,8 @@ const { result, state, searchTerm, filterResult, sortResult, loadNext } = useFro
71
72
  Simple listing access:
72
73
 
73
74
  ```typescript
74
- const { listing, status, refresh } = useFronticListing('FeaturedProducts', { limit: 10 })
75
+ // Second argument is the listing's parameters; query options go in the third
76
+ const { listing, status, error } = useFronticListing('CategoryProducts', { categoryKey: 'shoes' }, { query: { limit: 10 } })
75
77
  ```
76
78
 
77
79
  ### useFronticBlock
@@ -79,9 +81,11 @@ const { listing, status, refresh } = useFronticListing('FeaturedProducts', { lim
79
81
  Fetch single blocks (products, categories):
80
82
 
81
83
  ```typescript
82
- const { block, status } = useFronticBlock('Product', 'product-handle')
84
+ const { block, status, error } = useFronticBlock('ProductCard', 'product-handle')
83
85
  ```
84
86
 
87
+ Every data composable returns `status` and `error` alongside its data, plus `refresh` and `refetch`.
88
+
85
89
  ### useFronticTree
86
90
 
87
91
  Hierarchical menu trees:
@@ -104,7 +108,7 @@ const { contexts, current, update } = useFronticContext()
104
108
  export default defineNuxtConfig({
105
109
  frontic: {
106
110
  // Page routing
107
- contextDomain: 'your-shop.com',
111
+ contextDomain: 'demo-shop.com',
108
112
  redirectOn301: true,
109
113
  throwOn404: true,
110
114
 
@@ -112,6 +116,9 @@ export default defineNuxtConfig({
112
116
  proxy: true, // or '/api/custom-path'
113
117
  fetchApiSecret: process.env.FRONTIC_FETCH_SECRET,
114
118
 
119
+ // Sitemap
120
+ sitemap: true,
121
+
115
122
  // Context cookies
116
123
  contextCookieName: 'fs-context',
117
124
  contextCookieMaxAge: 31536000,
@@ -126,6 +133,60 @@ export default defineNuxtConfig({
126
133
  })
127
134
  ```
128
135
 
136
+ ### Sitemap
137
+
138
+ With `sitemap: true`, requests to `/sitemap.xml` (and `/sitemapN.xml` for split sitemaps) on any locale prefix serve the Frontic sitemap for the matching domain — generated from the Pages marked "Visible in Sitemap". Responses carry the upstream `ETag` and are cached with stale-while-revalidate. When your config declares domains (`sitemap: { domains: [...] }`, a `contextDomain` string, or `contextDomain: true` with i18n locales carrying `contextDomain` properties), only those domains are served — other hosts get a 404. With no declared domains the route serves any well-formed forwarded host and the module warns at build time. When `@nuxtjs/robots` is installed, the sitemap is added to `robots.txt` automatically. Not compatible with `@nuxtjs/sitemap` yet — with both installed the option is ignored with a warning.
139
+
140
+ ### Multi-locale domains
141
+
142
+ Frontic resolves scope, region and locale from the domain each request carries. Set `contextDomain: true` to take it from the locale `@nuxtjs/i18n` currently has active, instead of hardcoding one:
143
+
144
+ ```typescript
145
+ export default defineNuxtConfig({
146
+ modules: ['@frontic/nuxt', '@nuxtjs/i18n'],
147
+
148
+ frontic: {
149
+ contextDomain: true,
150
+ },
151
+
152
+ i18n: {
153
+ defaultLocale: 'en',
154
+ locales: [
155
+ { code: 'en', contextDomain: 'demo-shop.com' },
156
+ { code: 'de', contextDomain: 'demo-shop.com/de' },
157
+ ],
158
+ },
159
+ })
160
+ ```
161
+
162
+ `contextDomain` on the locale object is a property you add — the module reads it through i18n's `localeProperties`, and each value must match a domain configured in your Frontic project. The resolved domain is part of every cache key, so locales never share a cached response.
163
+
164
+ Per call, any composable accepts `contextDomain` to override it, and `useFronticClient({ contextDomain: false })` sends none at all.
165
+
166
+ ## Analytics
167
+
168
+ Listing, search and page events are announced as typed Nuxt hooks, so any vendor can be wired up in one plugin:
169
+
170
+ ```typescript
171
+ export default defineNuxtPlugin((nuxtApp) => {
172
+ nuxtApp.hook('frontic:listing:resolved', (payload) => {
173
+ if (payload.trigger === 'initial') {
174
+ track('view_item_list', { list: payload.listing, count: payload.resultCount })
175
+ }
176
+ })
177
+ })
178
+ ```
179
+
180
+ Hooks are client-only and deduplicated per route entry. Payload types are importable from `@frontic/nuxt/types` when you factor handlers out of the plugin.
181
+
182
+ ## TypeScript
183
+
184
+ Composable typing comes from your generated client (`npx @frontic/cli generate`): block, listing and tree names, listing parameters, filter and sort fields, and response types all resolve to your project's schema, and invalid names fail the typecheck. Helper types are available from `@frontic/nuxt/types`:
185
+
186
+ ```typescript
187
+ import type { ResponseOf, ListingQuery, SortString, FronticClient } from '@frontic/nuxt/types'
188
+ ```
189
+
129
190
  ## Documentation
130
191
 
131
192
  Full documentation at [docs.frontic.com](https://docs.frontic.com)
package/dist/module.d.mts CHANGED
@@ -1,137 +1,7 @@
1
1
  import { NuxtModule } from '@nuxt/schema';
2
+ import { FronticOptions } from '../dist/runtime/types/options.js';
3
+ export { FronticComposable, FronticComposablesConfig, FronticOptions } from '../dist/runtime/types/options.js';
2
4
 
3
- /**
4
- * Available Frontic composables that can be enabled/disabled
5
- *
6
- * - 'block': useFronticBlock - Fetch single blocks (products, categories)
7
- * - 'listing': useFronticListing - Fetch listings with caching
8
- * - 'search': useFronticSearch - Full-featured search with filters/sorting
9
- * - 'tree': useFronticTree - Fetch hierarchical menu trees
10
- * - 'page': useFronticPage - Dynamic page routing
11
- * - 'context': useFronticContext - Locale/region management
12
- * - 'client': useFronticClient - Low-level API client
13
- */
14
- type FronticComposable = 'block' | 'listing' | 'search' | 'tree' | 'page' | 'context' | 'client';
15
- /**
16
- * Frontic composables configuration
17
- * - true: Enable all composables (default)
18
- * - false or []: Disable all composables
19
- * - string[]: Enable only specified composables
20
- */
21
- type FronticComposablesConfig = boolean | FronticComposable[];
22
- /**
23
- * Frontic module configuration options
24
- */
25
- interface FronticOptions {
26
- /**
27
- * Prefix for all auto-imported Frontic UI components.
28
- * Set to 'Ui' to get `<UiButton>`, or leave empty for `<Button>`.
29
- * @default ''
30
- */
31
- componentsPrefix: string;
32
- /**
33
- * Directory that the components live in.
34
- * @default "@/components/ui"
35
- */
36
- componentDir: string;
37
- /**
38
- * Configure which Frontic composables to auto-import
39
- *
40
- * When a composable is disabled, it will not be auto-imported during the Nuxt build.
41
- * This means you won't get type errors or warnings—the composable simply won't exist.
42
- * Use this to reduce bundle size by excluding composables you don't need.
43
- *
44
- * Available composables:
45
- * - 'block': useFronticBlock - Fetch single blocks
46
- * - 'listing': useFronticListing - Fetch listings
47
- * - 'search': useFronticSearch - Search with filters/sorting
48
- * - 'tree': useFronticTree - Fetch hierarchical menu trees
49
- * - 'page': useFronticPage - Dynamic page routing
50
- * - 'context': useFronticContext - Locale/region management
51
- * - 'client': useFronticClient - Low-level API client
52
- *
53
- * @example
54
- * composables: true // Enable all (default)
55
- * composables: false // Disable all
56
- * composables: ['listing', 'page', 'client'] // Enable specific ones
57
- *
58
- * @default true
59
- */
60
- composables?: FronticComposablesConfig;
61
- /**
62
- * Enable/configure the API proxy for CORS prevention
63
- * - true: Enable proxy at default path '/api/frontic'
64
- * - false: Disable proxy
65
- * - string: Enable proxy at custom path
66
- *
67
- * @default true
68
- */
69
- proxy?: boolean | string;
70
- /**
71
- * Context domain for scope/region/locale resolution and page slug construction.
72
- *
73
- * Controls which Frontic domain is used across all composables:
74
- * - useFronticPage: prepended to the pathname to construct the page slug
75
- * - useFronticBlock/Listing/Context: injected as contextDomain request option
76
- *
77
- * - string: Static domain (e.g. 'shop.com')
78
- * - true: Read `contextDomain` property from current @nuxtjs/i18n locale object
79
- *
80
- * When not set, useFronticPage derives the domain from the request URL host.
81
- *
82
- * @example 'demo-shop.com'
83
- * @example true
84
- */
85
- contextDomain?: string | boolean;
86
- /**
87
- * Cookie name for persisting the context token
88
- * @default 'fs-context'
89
- */
90
- contextCookieName?: string;
91
- /**
92
- * Cookie max age in seconds for context token
93
- * @default 31536000 (1 year)
94
- */
95
- contextCookieMaxAge?: number;
96
- /**
97
- * Disable automatic context fetching and cookie management in useFronticContext
98
- *
99
- * When true:
100
- * - The context endpoint will NOT be called automatically on mount
101
- * - No context cookie will be set automatically
102
- * - You must manually call `refresh()` to fetch contexts
103
- * - You are responsible for storing and managing the context token
104
- *
105
- * Use this when you want full control over context management,
106
- * or when integrating with an existing locale/region system.
107
- *
108
- * @default false
109
- */
110
- disableContext?: boolean;
111
- /**
112
- * Automatically redirect on 301 responses
113
- * Can be overridden per-request in useFronticPage
114
- * @default true
115
- */
116
- redirectOn301?: boolean;
117
- /**
118
- * Throw a 404 error when page is not found
119
- * Can be overridden per-request in useFronticPage
120
- * @default true
121
- */
122
- throwOn404?: boolean;
123
- /**
124
- * API secret for authenticating Fetch API requests
125
- * Required for protected environments (e.g., development/staging)
126
- * Stored in private runtime config (server-only, never exposed to browser)
127
- *
128
- * For client-side requests, the secret is automatically injected by the proxy
129
- *
130
- * @example process.env.FRONTIC_FETCH_SECRET
131
- */
132
- fetchApiSecret?: string;
133
- }
134
5
  declare const module$1: NuxtModule<FronticOptions>;
135
6
 
136
7
  export { module$1 as default };
137
- export type { FronticComposable, FronticComposablesConfig, FronticOptions };
package/dist/module.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "frontic",
3
3
  "configKey": "frontic",
4
- "version": "0.7.0",
4
+ "version": "1.1.0",
5
5
  "compatibility": {
6
6
  "nuxt": ">=4.0.0"
7
7
  },
8
8
  "builder": {
9
- "@nuxt/module-builder": "1.0.2",
9
+ "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "unknown"
11
11
  }
12
12
  }
package/dist/module.mjs CHANGED
@@ -1,8 +1,7 @@
1
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
- import { createRequire } from 'node:module';
1
+ import { readFileSync, existsSync, readdirSync } from 'node:fs';
3
2
  import { dirname, join } from 'node:path';
4
3
  import { fileURLToPath } from 'node:url';
5
- import { defineNuxtModule, createResolver, addServerHandler, hasNuxtModule, installModule, addImports, addComponentsDir, addComponentExports } from '@nuxt/kit';
4
+ import { defineNuxtModule, createResolver, addServerHandler, addServerPlugin, hasNuxtModule, installModule, addImports, addTypeTemplate, addComponentsDir, addComponentExports } from '@nuxt/kit';
6
5
 
7
6
  function isFronticUiInitialized(rootDir) {
8
7
  const configPath = join(rootDir, "components.json");
@@ -15,6 +14,26 @@ function isFronticUiInitialized(rootDir) {
15
14
  }
16
15
  }
17
16
  const _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
17
+ function readGeneratorSchemaVersion(clientDir) {
18
+ try {
19
+ const metadata = JSON.parse(readFileSync(join(clientDir, "metadata.json"), "utf-8"));
20
+ return typeof metadata.generator?.schemaVersion === "number" ? metadata.generator.schemaVersion : 1;
21
+ } catch {
22
+ return 1;
23
+ }
24
+ }
25
+ function readFetchApiBaseUrl(clientPath) {
26
+ try {
27
+ const source = readFileSync(clientPath, "utf-8");
28
+ return /const servers = \[\s*\{[^}]*url:\s*'([^']+)'/.exec(source)?.[1];
29
+ } catch {
30
+ return void 0;
31
+ }
32
+ }
33
+ function collectSitemapDomains(explicitDomains, contextDomain, i18nLocales) {
34
+ const domains = explicitDomains ?? (typeof contextDomain === "string" ? [contextDomain] : contextDomain === true && Array.isArray(i18nLocales) ? i18nLocales.map((locale) => locale?.contextDomain).filter((domain) => typeof domain === "string") : []);
35
+ return domains.map((domain) => domain.toLowerCase().replace(/\/+$/, ""));
36
+ }
18
37
  const ALL_COMPOSABLES = ["block", "listing", "search", "tree", "page", "context", "client"];
19
38
  function isComposableEnabled(config, name) {
20
39
  if (config === true) return true;
@@ -22,6 +41,7 @@ function isComposableEnabled(config, name) {
22
41
  if (Array.isArray(config)) return config.includes(name);
23
42
  return true;
24
43
  }
44
+ const MODULE_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
25
45
  const module$1 = defineNuxtModule({
26
46
  defaults: {
27
47
  componentsPrefix: "",
@@ -33,12 +53,13 @@ const module$1 = defineNuxtModule({
33
53
  // 1 year
34
54
  disableContext: false,
35
55
  redirectOn301: true,
36
- throwOn404: true
56
+ throwOn404: true,
57
+ sitemap: false
37
58
  },
38
59
  meta: {
39
60
  name: "frontic",
40
61
  configKey: "frontic",
41
- version: "0.7.0",
62
+ version: MODULE_VERSION,
42
63
  compatibility: {
43
64
  nuxt: ">=4.0.0"
44
65
  }
@@ -55,6 +76,7 @@ const module$1 = defineNuxtModule({
55
76
  disableContext = false,
56
77
  redirectOn301 = true,
57
78
  throwOn404 = true,
79
+ sitemap = false,
58
80
  fetchApiSecret
59
81
  } = options;
60
82
  const COMPONENT_DIR_PATH = componentDir;
@@ -66,13 +88,50 @@ const module$1 = defineNuxtModule({
66
88
  const fronticClientDir = join(ROOT_DIR_PATH, ".frontic");
67
89
  const fronticClientPath = join(fronticClientDir, fronticClientFile);
68
90
  const hasFronticClient = existsSync(fronticClientPath);
91
+ if (hasFronticClient && readGeneratorSchemaVersion(fronticClientDir) < 2) {
92
+ console.warn(
93
+ "\n[@frontic/nuxt] Your generated Frontic client is outdated for this module version.\nComposable name and response types will not resolve (parameters typed as `never`).\nRegenerate with the current CLI: npx @frontic/cli generate\n"
94
+ );
95
+ }
69
96
  const proxyPath = typeof proxyConfig === "string" ? proxyConfig : proxyConfig !== false ? "/api/frontic" : void 0;
97
+ const proxyTimeout = options.proxyTimeout ?? 1e4;
70
98
  if (proxyPath && hasFronticClient) {
71
99
  addServerHandler({
72
100
  route: `${proxyPath}/**`,
73
101
  handler: resolveModule("./runtime/server/api/frontic/[...path]")
74
102
  });
75
103
  }
104
+ if (fetchApiSecret && hasFronticClient) {
105
+ addServerPlugin(resolveModule("./runtime/server/plugins/fetch-secret"));
106
+ }
107
+ let sitemapBaseUrl;
108
+ let sitemapDomains = [];
109
+ if (sitemap && hasFronticClient) {
110
+ if (hasNuxtModule("@nuxtjs/sitemap", nuxt)) {
111
+ console.warn("\n[@frontic/nuxt] sitemap: true is ignored while @nuxtjs/sitemap is installed.\nBoth modules would claim /sitemap.xml. Disable one of them.\n");
112
+ } else {
113
+ sitemapBaseUrl = readFetchApiBaseUrl(fronticClientPath);
114
+ if (!sitemapBaseUrl) {
115
+ console.warn("\n[@frontic/nuxt] sitemap: true but no Fetch API URL found in the generated client.\nRegenerate with the current CLI: npx @frontic/cli generate\n");
116
+ } else {
117
+ addServerHandler({
118
+ middleware: true,
119
+ handler: resolveModule("./runtime/server/middleware/sitemap")
120
+ });
121
+ sitemapDomains = collectSitemapDomains(typeof sitemap === "object" ? sitemap.domains : void 0, contextDomain, nuxt.options.i18n?.locales);
122
+ if (sitemapDomains.length === 0) {
123
+ console.warn(
124
+ "\n[@frontic/nuxt] sitemap is enabled without a domain allowlist, so the route serves\nany well-formed forwarded host through this deployment's secret.\nDeclare your domains via sitemap: { domains: [...] } or contextDomain config.\n"
125
+ );
126
+ }
127
+ if (hasNuxtModule("@nuxtjs/robots", nuxt)) {
128
+ nuxt.hook("robots:config", (robotsConfig) => {
129
+ robotsConfig.sitemap.push("/sitemap.xml");
130
+ });
131
+ }
132
+ }
133
+ }
134
+ }
76
135
  const blockEnabled = isComposableEnabled(composablesConfig, "block");
77
136
  const listingEnabled = isComposableEnabled(composablesConfig, "listing");
78
137
  const searchEnabled = isComposableEnabled(composablesConfig, "search");
@@ -101,20 +160,13 @@ frontic: { composables: false }
101
160
  );
102
161
  }
103
162
  const clientDirPath = fronticClientDir;
104
- const piniaEsmPath = anyComposableEnabled ? join(dirname(createRequire(import.meta.url).resolve("pinia/package.json")), "dist/pinia.mjs") : null;
105
163
  nuxt.options.vite ||= {};
106
164
  nuxt.options.vite.resolve ||= {};
107
165
  nuxt.options.vite.resolve.alias ||= {};
108
166
  nuxt.options.vite.resolve.alias["@frontic/stack"] = clientDirPath;
109
- if (piniaEsmPath) {
110
- nuxt.options.vite.resolve.alias["pinia"] = piniaEsmPath;
111
- }
112
167
  nuxt.hook("nitro:config", (nitroConfig) => {
113
168
  nitroConfig.alias ||= {};
114
169
  nitroConfig.alias["@frontic/stack"] = clientDirPath;
115
- if (piniaEsmPath) {
116
- nitroConfig.alias["pinia"] = piniaEsmPath;
117
- }
118
170
  });
119
171
  nuxt.hook("prepare:types", ({ tsConfig }) => {
120
172
  tsConfig.compilerOptions ||= {};
@@ -138,6 +190,7 @@ frontic: { composables: false }
138
190
  if (anyComposableEnabled) {
139
191
  const composablesDir = resolve(runtimeDir, "composables");
140
192
  const utilsDir = resolve(runtimeDir, "utils");
193
+ addImports([{ name: "isApiError", from: join(utilsDir, "errors") }]);
141
194
  if (clientEnabled) {
142
195
  addImports([{ name: "useFronticClient", from: join(composablesDir, "useFronticClient") }]);
143
196
  }
@@ -202,10 +255,69 @@ frontic: { composables: false }
202
255
  addImports([{ name: "useFronticContext", from: join(composablesDir, "useFronticContext") }]);
203
256
  }
204
257
  }
258
+ if (contextEnabled) {
259
+ addTypeTemplate({
260
+ filename: "types/frontic-context-hooks.d.ts",
261
+ getContents: () => `import type { FronticContext } from '${resolveModule("./runtime/composables/useFronticContext")}'
262
+
263
+ declare module '#app' {
264
+ interface RuntimeNuxtHooks {
265
+ 'frontic:context:ready': (context: FronticContext) => void | Promise<void>
266
+ 'frontic:context:updated': (context: FronticContext) => void | Promise<void>
267
+ }
268
+ }
269
+
270
+ export {}
271
+ `
272
+ });
273
+ }
274
+ if (searchEnabled || pageEnabled) {
275
+ const analyticsModule = resolveModule("./runtime/composables/analytics");
276
+ const listingHooks = searchEnabled ? ` 'frontic:listing:resolved': (payload: FronticListingResolved) => void | Promise<void>
277
+ 'frontic:search:committed': (payload: FronticSearchCommitted) => void | Promise<void>
278
+ ` : "";
279
+ const pageHooks = pageEnabled ? ` 'frontic:page:resolved': (payload: FronticPageResolved) => void | Promise<void>
280
+ ` : "";
281
+ const imported = [searchEnabled && "FronticListingResolved", searchEnabled && "FronticSearchCommitted", pageEnabled && "FronticPageResolved"].filter(Boolean).join(", ");
282
+ addTypeTemplate({
283
+ filename: "types/frontic-analytics-hooks.d.ts",
284
+ getContents: () => `import type { ${imported} } from '${analyticsModule}'
285
+
286
+ declare module '#app' {
287
+ interface RuntimeNuxtHooks {
288
+ ${listingHooks}${pageHooks} }
289
+ }
290
+
291
+ export {}
292
+ `
293
+ });
294
+ }
295
+ if (anyComposableEnabled || proxyPath && hasFronticClient) {
296
+ const errorsModule = resolveModule("./runtime/types/errors");
297
+ addTypeTemplate({
298
+ filename: "types/frontic-fetch-error.d.ts",
299
+ getContents: () => `import type { FronticFetchError } from '${errorsModule}'
300
+
301
+ declare module '#app' {
302
+ interface RuntimeNuxtHooks {
303
+ 'frontic:fetch:error': (payload: FronticFetchError) => void | Promise<void>
304
+ }
305
+ }
306
+
307
+ declare module 'nitropack/types' {
308
+ interface NitroRuntimeHooks {
309
+ 'frontic:fetch:error': (payload: FronticFetchError) => void | Promise<void>
310
+ }
311
+ }
312
+
313
+ export {}
314
+ `
315
+ });
316
+ }
205
317
  nuxt.options.runtimeConfig.public.frontic = {
206
318
  hasFronticClient,
207
- proxyPath,
208
- contextDomain,
319
+ proxyPath: proxyPath ?? "",
320
+ contextDomain: contextDomain ?? false,
209
321
  contextCookieName,
210
322
  contextCookieMaxAge,
211
323
  disableContext,
@@ -222,7 +334,10 @@ frontic: { composables: false }
222
334
  }
223
335
  };
224
336
  nuxt.options.runtimeConfig.frontic = {
225
- fetchApiSecret
337
+ fetchApiSecret: fetchApiSecret ?? "",
338
+ sitemapBaseUrl: sitemapBaseUrl ?? "",
339
+ sitemapDomains,
340
+ proxyTimeout
226
341
  };
227
342
  if (isFronticUiInitialized(ROOT_DIR_PATH)) {
228
343
  const componentsPath = await resolvePath(COMPONENT_DIR_PATH);
@@ -0,0 +1,82 @@
1
+ import type { Page } from '../types/registry.js';
2
+ /**
3
+ * Analytics hook payloads and per-app emission bookkeeping.
4
+ *
5
+ * Bookkeeping lives on `nuxtApp`, never in `useState`. `useState` is serialized
6
+ * into the SSR payload, so a client that hydrated a server-written fingerprint
7
+ * would treat the first paint as already counted and never emit `initial`.
8
+ */
9
+ /** Absolute position of an item within the full result set, plus its raw row. */
10
+ export interface FronticAnalyticsItem {
11
+ key: string;
12
+ index: number;
13
+ data: unknown;
14
+ }
15
+ export type FronticListingTrigger = 'initial' | 'term' | 'filter' | 'sort' | 'page' | 'loadMore' | 'reset';
16
+ export interface FronticListingResolved {
17
+ listing: string;
18
+ cacheKey: string;
19
+ trigger: FronticListingTrigger;
20
+ term?: string;
21
+ filters: Record<string, unknown>;
22
+ changedFilter?: {
23
+ field: string;
24
+ value?: unknown;
25
+ action: 'add' | 'remove';
26
+ };
27
+ sort?: {
28
+ field: string;
29
+ order: 'asc' | 'desc';
30
+ };
31
+ page: number;
32
+ resultCount: number;
33
+ totalCount: number;
34
+ items: FronticAnalyticsItem[];
35
+ version: number;
36
+ }
37
+ export interface FronticSearchCommitted {
38
+ term: string;
39
+ cacheKey: string;
40
+ resultCount: number;
41
+ page: number;
42
+ version: number;
43
+ }
44
+ export interface FronticPageResolved {
45
+ page: Page;
46
+ version: number;
47
+ }
48
+ /** Bumped only on a breaking payload shape change, never on added fields. */
49
+ export declare const FRONTIC_ANALYTICS_VERSION = 1;
50
+ /**
51
+ * Minimal view of the Nuxt app. The hook names are typed for consuming apps
52
+ * through the module's type template; inside the package `#app` is not
53
+ * resolvable, so `RuntimeNuxtHooks` cannot be augmented here and `callHook` is
54
+ * called untyped — the same reason `useFronticContext` casts.
55
+ */
56
+ type NuxtAppLike = {
57
+ callHook: unknown;
58
+ };
59
+ /**
60
+ * Reset dedup bookkeeping on navigation, so returning to a listing counts as a
61
+ * new view. `nuxtApp` survives client-side navigation; without this, the back
62
+ * button into a category would report nothing — the dominant pattern in a
63
+ * catalogue, and an undercount that inflates every per-view rate downstream.
64
+ *
65
+ * Registered once per app instance, on first use.
66
+ */
67
+ export declare function bindRouteReset(nuxtApp: NuxtAppLike): void;
68
+ /** Announce a payload. Hooks are fire-and-forget; a slow listener never blocks a refresh. */
69
+ export declare function emit(nuxtApp: NuxtAppLike, hook: string, payload: unknown): void;
70
+ /**
71
+ * Emit once per dedup key for the current route entry, for events that are not
72
+ * caused by a method call. A `data` watcher fires once per call site, so the
73
+ * first paint of a listing would otherwise be announced once per mounted
74
+ * component. Intent-driven events do not go through here: each is one user
75
+ * action already, and deduping them would swallow a filter re-applied twice.
76
+ *
77
+ * Returns whether the payload was emitted.
78
+ */
79
+ export declare function emitOnce(nuxtApp: NuxtAppLike, dedupKey: string, hook: string, payload: unknown): boolean;
80
+ /** Build the analytics item list, carrying absolute index across pages. */
81
+ export declare function toAnalyticsItems(items: unknown[], indexOffset: number): FronticAnalyticsItem[];
82
+ export {};
@@ -0,0 +1,38 @@
1
+ export const FRONTIC_ANALYTICS_VERSION = 1;
2
+ function runtimeFor(nuxtApp) {
3
+ const app = nuxtApp;
4
+ return app._fronticAnalytics ??= {};
5
+ }
6
+ export function bindRouteReset(nuxtApp) {
7
+ const runtime = runtimeFor(nuxtApp);
8
+ if (runtime.routeBound) return;
9
+ const router = nuxtApp.$router;
10
+ if (typeof router?.afterEach !== "function") return;
11
+ runtime.routeBound = true;
12
+ router.afterEach(() => {
13
+ runtime.seen?.clear();
14
+ });
15
+ }
16
+ function isServer(nuxtApp) {
17
+ return Boolean(nuxtApp.ssrContext);
18
+ }
19
+ export function emit(nuxtApp, hook, payload) {
20
+ if (isServer(nuxtApp)) return;
21
+ void nuxtApp.callHook(hook, payload);
22
+ }
23
+ export function emitOnce(nuxtApp, dedupKey, hook, payload) {
24
+ if (isServer(nuxtApp)) return false;
25
+ const runtime = runtimeFor(nuxtApp);
26
+ const seen = runtime.seen ??= /* @__PURE__ */ new Set();
27
+ if (seen.has(dedupKey)) return false;
28
+ seen.add(dedupKey);
29
+ emit(nuxtApp, hook, payload);
30
+ return true;
31
+ }
32
+ export function toAnalyticsItems(items, indexOffset) {
33
+ return items.map((data, i) => ({
34
+ key: String(data?.key ?? ""),
35
+ index: indexOffset + i,
36
+ data
37
+ }));
38
+ }