nuxt-kirby 1.1.0 โ†’ 3.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-PRESENT Johann Schopplich <https://github.com/johannschopplich>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ [![Nuxt Kirby module](./docs/public/og.jpg)](https://nuxt-kirby.byjohann.dev)
2
+
3
+ # Nuxt Kirby
4
+
5
+ [Nuxt](https://nuxt.com) module to interact with [Kirby CMS](https://getkirby.com) with support for [Kirby's Query Language](https://github.com/getkirby/kql) API.
6
+
7
+ - [โœจ &nbsp;Release Notes](https://github.com/johannschopplich/nuxt-kirby/releases)
8
+ - [๐Ÿ“– &nbsp;Read the documentation](https://nuxt-kirby.byjohann.dev)
9
+
10
+ ## Features
11
+
12
+ - ๐Ÿ”’ Protected Kirby credentials when sending queries
13
+ - ๐Ÿชข Supports token-based authentication with the [Kirby Headless plugin](https://kirby.tools/docs/headless/getting-started/) (recommended)
14
+ - ๐Ÿฑ Handle request just like with the [`useFetch`](https://nuxt.com/docs/getting-started/data-fetching/#usefetch) composable
15
+ - ๐Ÿฆฆ [Multiple starter kits](https://nuxt-kirby.byjohann.dev/essentials/starter-kits) available
16
+ - ๐Ÿ—ƒ Cached query responses
17
+ - ๐Ÿคน No CORS issues!
18
+ - ๐Ÿฆพ Strongly typed
19
+
20
+ ## Setup
21
+
22
+ > [!TIP]
23
+ > [๐Ÿ“– Read the documentation](https://nuxt-kirby.byjohann.dev)
24
+
25
+ ```bash
26
+ npx nuxi@latest module add kirby
27
+ ```
28
+
29
+ ## Basic Usage
30
+
31
+ > [!TIP]
32
+ > [๐Ÿ“– Read the documentation](https://nuxt-kirby.byjohann.dev)
33
+
34
+ Add the Nuxt Kirby module to your Nuxt config:
35
+
36
+ ```ts
37
+ // `nuxt.config.ts`
38
+ export default defineNuxtConfig({
39
+ modules: ['nuxt-kirby']
40
+ })
41
+ ```
42
+
43
+ And send queries in your template:
44
+
45
+ ```vue
46
+ <script setup lang="ts">
47
+ const { data, error, status } = await useKql({
48
+ query: 'site'
49
+ })
50
+ </script>
51
+
52
+ <template>
53
+ <div>
54
+ <h1>{{ data?.result?.title }}</h1>
55
+ <pre>{{ JSON.stringify(data?.result, undefined, 2) }}</pre>
56
+ </div>
57
+ </template>
58
+ ```
59
+
60
+ ## ๐Ÿ’ป Development
61
+
62
+ 1. Clone this repository
63
+ 2. Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`
64
+ 3. Install dependencies using `pnpm install`
65
+ 4. Run `pnpm run dev:prepare`
66
+ 5. Start development server using `pnpm run dev`
67
+
68
+ ## License
69
+
70
+ [MIT](./LICENSE) License ยฉ 2022-PRESENT [Johann Schopplich](https://github.com/johannschopplich)
@@ -0,0 +1,116 @@
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
+ import { KirbyQueryRequest } from 'kirby-types';
3
+
4
+ interface ModuleOptions {
5
+ /**
6
+ * Kirby base URL, like `https://kirby.example.com`
7
+ *
8
+ * @default process.env.KIRBY_BASE_URL
9
+ */
10
+ url?: string;
11
+ /**
12
+ * Kirby KQL API route path
13
+ *
14
+ * @default 'api/query' // for `basic` authentication
15
+ * @default 'api/kql' // for `bearer` authentication
16
+ */
17
+ prefix?: string;
18
+ /**
19
+ * Kirby API authentication method
20
+ *
21
+ * @remarks
22
+ * Set to `none` to disable authentication
23
+ *
24
+ * @default 'basic'
25
+ */
26
+ auth?: 'basic' | 'bearer' | 'none';
27
+ /**
28
+ * Token for bearer authentication
29
+ *
30
+ * @default process.env.KIRBY_API_TOKEN
31
+ */
32
+ token?: string;
33
+ /**
34
+ * Username/password pair for basic authentication
35
+ *
36
+ * @default { username: process.env.KIRBY_API_USERNAME, password: process.env.KIRBY_API_PASSWORD }
37
+ */
38
+ credentials?: {
39
+ username: string;
40
+ password: string;
41
+ };
42
+ /**
43
+ * Send client-side requests instead of using the server-side proxy
44
+ *
45
+ * @remarks
46
+ * By default, data from Kirby is fetched safely with a server-side proxy.
47
+ * If enabled, query requests will be be sent directly from the client.
48
+ * Note: This means your token or user credentials will be publicly visible.
49
+ * If Nuxt SSR is disabled, this option is enabled by default.
50
+ *
51
+ * @default false
52
+ */
53
+ client?: boolean;
54
+ /**
55
+ * Prefetch custom KQL queries at build-time
56
+ *
57
+ * @remarks
58
+ * The queries will be fully typed and importable from `#nuxt-kirby`.
59
+ *
60
+ * @default {}
61
+ */
62
+ prefetch?: Record<string, KirbyQueryRequest | {
63
+ query: KirbyQueryRequest;
64
+ language: string;
65
+ }>;
66
+ /**
67
+ * Server-side features
68
+ */
69
+ server?: {
70
+ /**
71
+ * Enable server-side caching of queries using the Nitro cache API
72
+ *
73
+ * @see https://nitro.unjs.io/guide/cache
74
+ */
75
+ cache?: boolean;
76
+ /**
77
+ * Name of the storage mountpoint to use for caching
78
+ *
79
+ * @see https://nitro.unjs.io/guide/cache
80
+ * @default 'cache'
81
+ */
82
+ storage?: string;
83
+ /**
84
+ * Enable stale-while-revalidate behavior (cache is returned while it is being updated)
85
+ *
86
+ * @see https://nitro.unjs.io/guide/cache#options
87
+ * @default false
88
+ */
89
+ swr?: boolean;
90
+ /**
91
+ * Number of seconds to cache the query response
92
+ *
93
+ * @see https://nitro.unjs.io/guide/cache#options
94
+ * @default 1
95
+ */
96
+ maxAge?: number;
97
+ /**
98
+ * Log verbose errors to the console if a query fails
99
+ *
100
+ * @remarks
101
+ * This will log the full query to the console. Depending on the content of the query, this could be a security risk.
102
+ *
103
+ * @default false
104
+ */
105
+ verboseErrors?: boolean;
106
+ };
107
+ }
108
+ declare module '@nuxt/schema' {
109
+ interface RuntimeConfig {
110
+ kirby: ModuleOptions;
111
+ }
112
+ }
113
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
114
+
115
+ export { _default as default };
116
+ export type { ModuleOptions };
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "nuxt-kirby",
3
+ "configKey": "kirby",
4
+ "compatibility": {
5
+ "nuxt": ">=4.0.0"
6
+ },
7
+ "version": "3.0.0",
8
+ "builder": {
9
+ "@nuxt/module-builder": "1.0.2",
10
+ "unbuild": "3.6.1"
11
+ }
12
+ }
@@ -0,0 +1,193 @@
1
+ import process from 'node:process';
2
+ import { useLogger, defineNuxtModule, createResolver, addServerHandler, addImports, addTemplate } from '@nuxt/kit';
3
+ import { defu } from 'defu';
4
+ import { join } from 'pathe';
5
+ import { pascalCase } from 'scule';
6
+ import { withLeadingSlash } from 'ufo';
7
+ import { ofetch } from 'ofetch';
8
+ import { createAuthHeader } from '../dist/runtime/utils.js';
9
+
10
+ const name = "nuxt-kirby";
11
+
12
+ const logger = useLogger("nuxt-kirby");
13
+
14
+ async function prefetchQueries(options) {
15
+ const results = /* @__PURE__ */ new Map();
16
+ if (!options.prefetch || Object.keys(options.prefetch).length === 0)
17
+ return results;
18
+ if (!options.url) {
19
+ logger.error("Skipping KQL prefetch, since no Kirby base URL is provided");
20
+ return results;
21
+ }
22
+ for (const key of Object.keys(options.prefetch)) {
23
+ if (key === pascalCase(key)) {
24
+ logger.error(`Prefetch query key "${key}" conflicts with its PascalCase type name. Please use a different key (e.g., "${key.charAt(0).toLowerCase() + key.slice(1)}")`);
25
+ }
26
+ }
27
+ const start = Date.now();
28
+ for (const [key, query] of Object.entries(options.prefetch)) {
29
+ const language = "language" in query ? query.language : void 0;
30
+ if (language && !query.query) {
31
+ logger.error(`Prefetch KQL query "${key}" requires the "query" property in multi-language mode`);
32
+ continue;
33
+ }
34
+ try {
35
+ results.set(
36
+ key,
37
+ await ofetch(options.prefix, {
38
+ baseURL: options.url,
39
+ method: "POST",
40
+ body: language ? query.query : query,
41
+ headers: {
42
+ ...createAuthHeader(options),
43
+ ...language && { "X-Language": language }
44
+ }
45
+ })
46
+ );
47
+ } catch (error) {
48
+ const _error = error;
49
+ logger.error(
50
+ `Prefetch KQL query "${key}" failed${_error.status ? ` with status code ${_error.status}:
51
+ ${JSON.stringify(_error.data, void 0, 2)}` : `: ${_error}`}`
52
+ );
53
+ }
54
+ }
55
+ if (results.size > 0) {
56
+ const firstKey = results.keys().next().value;
57
+ logger.info(
58
+ `Prefetched ${results.size === 1 ? "" : `${results.size} `}KQL ${results.size === 1 ? `query "${firstKey}"` : "queries"} in ${Date.now() - start}ms`
59
+ );
60
+ }
61
+ return results;
62
+ }
63
+
64
+ const KIRBY_TYPES_PKG_EXPORT_NAMES = [
65
+ "KirbyApiResponse",
66
+ "KirbyBlock",
67
+ "KirbyDefaultBlocks",
68
+ "KirbyDefaultBlockType",
69
+ "KirbyLayout",
70
+ "KirbyLayoutColumn",
71
+ "KirbyQuery",
72
+ "KirbyQueryChain",
73
+ "KirbyQueryModel",
74
+ "KirbyQueryRequest",
75
+ "KirbyQueryResponse",
76
+ "KirbyQuerySchema"
77
+ ];
78
+ const module = defineNuxtModule({
79
+ meta: {
80
+ name,
81
+ configKey: "kirby",
82
+ compatibility: {
83
+ nuxt: ">=4.0.0"
84
+ }
85
+ },
86
+ defaults: {
87
+ url: process.env.KIRBY_BASE_URL || "",
88
+ prefix: "",
89
+ auth: "basic",
90
+ token: process.env.KIRBY_API_TOKEN || "",
91
+ credentials: {
92
+ username: process.env.KIRBY_API_USERNAME || "",
93
+ password: process.env.KIRBY_API_PASSWORD || ""
94
+ },
95
+ client: false,
96
+ prefetch: {},
97
+ server: {
98
+ cache: false,
99
+ storage: "cache",
100
+ swr: false,
101
+ maxAge: 1,
102
+ verboseErrors: false
103
+ }
104
+ },
105
+ async setup(options, nuxt) {
106
+ const moduleName = name;
107
+ if (!options.url)
108
+ logger.error("Missing `KIRBY_BASE_URL` environment variable");
109
+ if (options.auth === "basic" && (!options.credentials || !options.credentials.username || !options.credentials.password))
110
+ logger.error("Missing `KIRBY_API_USERNAME` and `KIRBY_API_PASSWORD` environment variable for basic authentication");
111
+ if (options.auth === "bearer" && !options.token)
112
+ logger.error("Missing `KIRBY_API_TOKEN` environment variable for bearer authentication");
113
+ if (!options.prefix) {
114
+ if (options.auth === "basic")
115
+ options.prefix = "api/query";
116
+ else if (options.auth === "bearer")
117
+ options.prefix = "api/kql";
118
+ }
119
+ if (!nuxt.options.ssr) {
120
+ logger.info("Kirby requests are client-only because SSR is disabled");
121
+ options.client = true;
122
+ }
123
+ if (options.server) {
124
+ options.server.storage ||= "cache";
125
+ options.server.storage = withLeadingSlash(options.server.storage);
126
+ }
127
+ nuxt.options.runtimeConfig.kirby = defu(
128
+ nuxt.options.runtimeConfig.kirby,
129
+ options
130
+ );
131
+ nuxt.options.runtimeConfig.public.kirby = defu(
132
+ nuxt.options.runtimeConfig.public.kirby,
133
+ options.client ? options : { client: false }
134
+ );
135
+ const { resolve } = createResolver(import.meta.url);
136
+ nuxt.options.build.transpile.push(resolve("runtime"));
137
+ addServerHandler({
138
+ route: "/api/__kirby__/:key",
139
+ handler: resolve("runtime/server/handler"),
140
+ method: "post"
141
+ });
142
+ addImports(
143
+ ["$kirby", "$kql", "useKirbyData", "useKql"].map((name2) => ({
144
+ name: name2,
145
+ as: name2,
146
+ from: resolve(`runtime/composables/${name2}`)
147
+ }))
148
+ );
149
+ nuxt.hooks.hook("nitro:config", (config) => {
150
+ config.externals ||= {};
151
+ config.externals.inline ||= [];
152
+ config.externals.inline.push(resolve("runtime/utils"));
153
+ config.imports = defu(config.imports, {
154
+ presets: [{
155
+ from: resolve("runtime/server/imports"),
156
+ imports: ["$kirby", "$kql"]
157
+ }]
158
+ });
159
+ });
160
+ nuxt.options.alias[`#${moduleName}`] = join(nuxt.options.buildDir, `module/${moduleName}`);
161
+ nuxt.options.alias["#nuxt-kql"] = join(nuxt.options.buildDir, `module/${moduleName}`);
162
+ const prefetchedQueries = await prefetchQueries(options);
163
+ addTemplate({
164
+ filename: `module/${moduleName}.mjs`,
165
+ write: true,
166
+ getContents() {
167
+ return `
168
+ // Generated by ${moduleName}
169
+ ${[...prefetchedQueries.entries()].map(([key, response]) => `
170
+ export const ${key} = ${JSON.stringify(response?.result || null, void 0, 2)}
171
+ `.trimStart()).join("") || `export {}
172
+ `}`.trimStart();
173
+ }
174
+ });
175
+ addTemplate({
176
+ filename: `module/${moduleName}.d.ts`,
177
+ write: true,
178
+ getContents() {
179
+ return `
180
+ // Generated by ${moduleName}
181
+ export type { ${KIRBY_TYPES_PKG_EXPORT_NAMES.join(", ")} } from 'kirby-types'
182
+
183
+ ${[...prefetchedQueries.entries()].map(([key, response]) => `
184
+ export declare const ${key}: ${JSON.stringify(response?.result || null, void 0, 2)}
185
+ export type ${pascalCase(key)} = typeof ${key}
186
+ `.trimStart()).join("") || `export {}
187
+ `}`.trimStart();
188
+ }
189
+ });
190
+ }
191
+ });
192
+
193
+ export { module as default };
@@ -0,0 +1,19 @@
1
+ import type { NitroFetchOptions } from 'nitropack';
2
+ export type KirbyFetchOptions = Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'method' | 'headers' | 'query' | 'body' | 'retry' | 'retryDelay' | 'retryStatusCodes' | 'timeout' | 'signal'> & {
3
+ /**
4
+ * Language code to fetch data for in multi-language Kirby setups.
5
+ */
6
+ language?: string;
7
+ /**
8
+ * Cache the response between function calls for the same path.
9
+ * @default true
10
+ */
11
+ cache?: boolean;
12
+ /**
13
+ * By default, a cache key will be generated from the request options.
14
+ * With this option, you can provide a custom cache key.
15
+ * @default undefined
16
+ */
17
+ key?: string;
18
+ };
19
+ export declare function $kirby<T = any>(path: string, opts?: KirbyFetchOptions): Promise<T>;
@@ -0,0 +1,69 @@
1
+ import { useNuxtApp, useRequestFetch, useRuntimeConfig } from "#imports";
2
+ import { hash } from "ohash";
3
+ import { joinURL } from "ufo";
4
+ import { buildApiProxyPath, createAuthHeader, headersToObject } from "../utils.js";
5
+ export function $kirby(path, opts = {}) {
6
+ const nuxt = useNuxtApp();
7
+ const promiseMap = nuxt._pendingRequests ||= /* @__PURE__ */ new Map();
8
+ const {
9
+ method,
10
+ headers,
11
+ query,
12
+ body,
13
+ language,
14
+ cache = true,
15
+ key,
16
+ ...fetchOptions
17
+ } = opts;
18
+ const kirby = useRuntimeConfig().public.kirby;
19
+ if (language)
20
+ path = joinURL(language, path);
21
+ const _key = key || `$kirby${hash([
22
+ path,
23
+ method,
24
+ query,
25
+ body,
26
+ language
27
+ ])}`;
28
+ if ((nuxt.isHydrating || cache) && nuxt.payload.data[_key])
29
+ return Promise.resolve(nuxt.payload.data[_key]);
30
+ if (promiseMap.has(_key))
31
+ return promiseMap.get(_key);
32
+ const sharedHeaders = headersToObject(headers);
33
+ const _serverFetchOptions = {
34
+ method: "POST",
35
+ body: {
36
+ path,
37
+ method,
38
+ query,
39
+ body,
40
+ headers: sharedHeaders,
41
+ cache
42
+ }
43
+ };
44
+ const _clientFetchOptions = {
45
+ baseURL: kirby.url,
46
+ query,
47
+ method,
48
+ headers: {
49
+ ...sharedHeaders,
50
+ ...createAuthHeader(kirby)
51
+ },
52
+ body
53
+ };
54
+ const request = useRequestFetch()(kirby.client ? path : buildApiProxyPath(_key), {
55
+ ...fetchOptions,
56
+ ...kirby.client ? _clientFetchOptions : _serverFetchOptions
57
+ }).then((response) => {
58
+ if (import.meta.server || cache)
59
+ nuxt.payload.data[_key] = response;
60
+ return response;
61
+ }).catch((error) => {
62
+ nuxt.payload.data[_key] = void 0;
63
+ throw error;
64
+ }).finally(() => {
65
+ promiseMap.delete(_key);
66
+ });
67
+ promiseMap.set(_key, request);
68
+ return request;
69
+ }
@@ -0,0 +1,20 @@
1
+ import type { KirbyQueryRequest, KirbyQueryResponse } from 'kirby-types';
2
+ import type { NitroFetchOptions } from 'nitropack';
3
+ export type KqlOptions = Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'headers' | 'retry' | 'retryDelay' | 'retryStatusCodes' | 'timeout' | 'signal'> & {
4
+ /**
5
+ * Language code to fetch data for in multi-language Kirby setups.
6
+ */
7
+ language?: string;
8
+ /**
9
+ * Cache the response between function calls for the same query.
10
+ * @default true
11
+ */
12
+ cache?: boolean;
13
+ /**
14
+ * By default, a cache key will be generated from the request options.
15
+ * With this option, you can provide a custom cache key.
16
+ * @default undefined
17
+ */
18
+ key?: string;
19
+ };
20
+ export declare function $kql<T extends KirbyQueryResponse<any, boolean> = KirbyQueryResponse>(query: KirbyQueryRequest, opts?: KqlOptions): Promise<T>;
@@ -0,0 +1,56 @@
1
+ import { useNuxtApp, useRequestFetch, useRuntimeConfig } from "#imports";
2
+ import { hash } from "ohash";
3
+ import { buildApiProxyPath, createAuthHeader, headersToObject } from "../utils.js";
4
+ export function $kql(query, opts = {}) {
5
+ const nuxt = useNuxtApp();
6
+ const promiseMap = nuxt._pendingRequests ||= /* @__PURE__ */ new Map();
7
+ const kirby = useRuntimeConfig().public.kirby;
8
+ const {
9
+ headers,
10
+ language,
11
+ cache = true,
12
+ key,
13
+ ...fetchOptions
14
+ } = opts;
15
+ const _key = key || `$kql${hash([query, language])}`;
16
+ if ((nuxt.isHydrating || cache) && nuxt.payload.data[_key])
17
+ return Promise.resolve(nuxt.payload.data[_key]);
18
+ if (promiseMap.has(_key))
19
+ return promiseMap.get(_key);
20
+ const sharedHeaders = {
21
+ ...headersToObject(headers),
22
+ ...language && { "X-Language": language }
23
+ };
24
+ const _serverFetchOptions = {
25
+ method: "POST",
26
+ body: {
27
+ query,
28
+ headers: sharedHeaders,
29
+ cache
30
+ }
31
+ };
32
+ const _clientFetchOptions = {
33
+ baseURL: kirby.url,
34
+ method: "POST",
35
+ headers: {
36
+ ...sharedHeaders,
37
+ ...createAuthHeader(kirby)
38
+ },
39
+ body: query
40
+ };
41
+ const request = useRequestFetch()(kirby.client ? kirby.prefix : buildApiProxyPath(_key), {
42
+ ...fetchOptions,
43
+ ...kirby.client ? _clientFetchOptions : _serverFetchOptions
44
+ }).then((response) => {
45
+ if (import.meta.server || cache)
46
+ nuxt.payload.data[_key] = response;
47
+ return response;
48
+ }).catch((error) => {
49
+ nuxt.payload.data[_key] = void 0;
50
+ throw error;
51
+ }).finally(() => {
52
+ promiseMap.delete(_key);
53
+ });
54
+ promiseMap.set(_key, request);
55
+ return request;
56
+ }
@@ -0,0 +1,22 @@
1
+ import type { NitroFetchOptions } from 'nitropack';
2
+ import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app';
3
+ import type { MaybeRefOrGetter, MultiWatchSources } from 'vue';
4
+ type UseKirbyDataOptions<T> = Omit<AsyncDataOptions<T>, 'watch'> & Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'method' | 'headers' | 'query' | 'body' | 'retry' | 'retryDelay' | 'retryStatusCodes' | 'timeout'> & {
5
+ /**
6
+ * Language code to fetch data for in multi-language Kirby setups.
7
+ */
8
+ language?: MaybeRefOrGetter<string>;
9
+ /**
10
+ * Cache the response between function calls for the same path.
11
+ * @default true
12
+ */
13
+ cache?: boolean;
14
+ /**
15
+ * Watch an array of reactive sources and auto-refresh the fetch result when they change.
16
+ * Path and language are watched by default. You can completely ignore reactive sources by using `watch: false`.
17
+ * @default undefined
18
+ */
19
+ watch?: MultiWatchSources | false;
20
+ };
21
+ export declare function useKirbyData<T = any>(path: MaybeRefOrGetter<string>, opts?: UseKirbyDataOptions<T>): AsyncData<T | undefined, NuxtError>;
22
+ export {};
@@ -0,0 +1,60 @@
1
+ import { useAsyncData } from "#imports";
2
+ import { hash } from "ohash";
3
+ import { joinURL } from "ufo";
4
+ import { computed, toValue } from "vue";
5
+ import { $kirby } from "./$kirby.js";
6
+ export function useKirbyData(path, opts = {}) {
7
+ const {
8
+ server,
9
+ lazy,
10
+ default: defaultFn,
11
+ transform,
12
+ pick,
13
+ watch: watchSources,
14
+ immediate,
15
+ method,
16
+ headers,
17
+ query,
18
+ body,
19
+ language,
20
+ cache = true,
21
+ ...fetchOptions
22
+ } = opts;
23
+ const _language = computed(() => toValue(language));
24
+ const _path = computed(() => {
25
+ const value = toValue(path).replace(/^\//, "");
26
+ return _language.value ? joinURL(_language.value, value) : value;
27
+ });
28
+ const key = computed(() => `$kirby${hash([
29
+ _path.value,
30
+ query,
31
+ method
32
+ ])}`);
33
+ if (!_path.value || _language.value && !_path.value.replace(new RegExp(`^${_language.value}/`), ""))
34
+ console.warn("[useKirbyData] Empty Kirby path");
35
+ const asyncDataOptions = {
36
+ server,
37
+ lazy,
38
+ default: defaultFn,
39
+ transform,
40
+ pick,
41
+ watch: watchSources === false ? [] : [...watchSources || [], key],
42
+ immediate
43
+ };
44
+ let controller;
45
+ return useAsyncData(
46
+ watchSources === false ? key.value : key,
47
+ () => {
48
+ controller?.abort?.();
49
+ controller = new AbortController();
50
+ return $kirby(_path.value, {
51
+ ...fetchOptions,
52
+ signal: controller.signal,
53
+ language: _language.value,
54
+ cache,
55
+ key: key.value
56
+ });
57
+ },
58
+ asyncDataOptions
59
+ );
60
+ }
@@ -0,0 +1,22 @@
1
+ import type { KirbyQueryRequest, KirbyQueryResponse } from 'kirby-types';
2
+ import type { NitroFetchOptions } from 'nitropack';
3
+ import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app';
4
+ import type { MaybeRefOrGetter, MultiWatchSources } from 'vue';
5
+ export type UseKqlOptions<T> = Omit<AsyncDataOptions<T>, 'watch'> & Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'headers' | 'retry' | 'retryDelay' | 'retryStatusCodes' | 'timeout'> & {
6
+ /**
7
+ * Language code to fetch data for in multi-language Kirby setups.
8
+ */
9
+ language?: MaybeRefOrGetter<string>;
10
+ /**
11
+ * Cache the response between function calls for the same query.
12
+ * @default true
13
+ */
14
+ cache?: boolean;
15
+ /**
16
+ * Watch an array of reactive sources and auto-refresh the fetch result when they change.
17
+ * Query and language are watched by default. You can completely ignore reactive sources by using `watch: false`.
18
+ * @default undefined
19
+ */
20
+ watch?: MultiWatchSources | false;
21
+ };
22
+ export declare function useKql<ResT extends KirbyQueryResponse<any, boolean> = KirbyQueryResponse, ReqT extends KirbyQueryRequest = KirbyQueryRequest>(query: MaybeRefOrGetter<ReqT>, opts?: UseKqlOptions<ResT>): AsyncData<ResT | undefined, NuxtError>;
@@ -0,0 +1,49 @@
1
+ import { useAsyncData } from "#imports";
2
+ import { hash } from "ohash";
3
+ import { computed, toValue } from "vue";
4
+ import { $kql } from "./$kql.js";
5
+ export function useKql(query, opts = {}) {
6
+ const {
7
+ server,
8
+ lazy,
9
+ default: defaultFn,
10
+ transform,
11
+ pick,
12
+ watch: watchSources,
13
+ immediate,
14
+ headers,
15
+ language,
16
+ cache = true,
17
+ ...fetchOptions
18
+ } = opts;
19
+ const _query = computed(() => toValue(query));
20
+ const _language = computed(() => toValue(language));
21
+ const key = computed(() => `$kql${hash([_query.value, _language.value])}`);
22
+ if (Object.keys(_query.value).length === 0 || !_query.value.query)
23
+ console.error("[useKql] Empty KQL query");
24
+ const asyncDataOptions = {
25
+ server,
26
+ lazy,
27
+ default: defaultFn,
28
+ transform,
29
+ pick,
30
+ watch: watchSources === false ? [] : [...watchSources || [], key],
31
+ immediate
32
+ };
33
+ let controller;
34
+ return useAsyncData(
35
+ watchSources === false ? key.value : key,
36
+ () => {
37
+ controller?.abort?.();
38
+ controller = new AbortController();
39
+ return $kql(_query.value, {
40
+ ...fetchOptions,
41
+ signal: controller.signal,
42
+ language: _language.value,
43
+ cache,
44
+ key: key.value
45
+ });
46
+ },
47
+ asyncDataOptions
48
+ );
49
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<Uint8Array<ArrayBuffer>>>;
2
+ export default _default;
@@ -0,0 +1,114 @@
1
+ import { useRuntimeConfig } from "#imports";
2
+ import { consola } from "consola";
3
+ import { destr } from "destr";
4
+ import { createError, defineEventHandler, getRouterParam, readBody, setResponseHeader, setResponseStatus, splitCookiesString } from "h3";
5
+ import { defineCachedFunction } from "nitropack/runtime/internal/cache";
6
+ import { base64ToUint8Array, uint8ArrayToBase64, uint8ArrayToString } from "uint8array-extras";
7
+ import { createAuthHeader } from "../utils.js";
8
+ const EXCLUDED_HEADERS = /* @__PURE__ */ new Set([
9
+ // https://github.com/h3js/h3/blob/fe9800bbbe9bda2972cc5d11db7353f4ab70f0ba/src/utils/proxy.ts#L97
10
+ "content-encoding",
11
+ "content-length",
12
+ // Reduce information leakage
13
+ "server",
14
+ "x-powered-by"
15
+ ]);
16
+ export default defineEventHandler(async (event) => {
17
+ const kirby = useRuntimeConfig(event).kirby;
18
+ const body = await readBody(event);
19
+ const key = decodeURIComponent(getRouterParam(event, "key"));
20
+ const isQueryRequest = key.startsWith("$kql");
21
+ const fetcher = async (event2, {
22
+ key: key2,
23
+ query,
24
+ path,
25
+ headers,
26
+ method,
27
+ body: body2
28
+ }) => {
29
+ const isQueryRequest2 = key2.startsWith("$kql");
30
+ const response = await globalThis.$fetch.raw(isQueryRequest2 ? kirby.prefix : path, {
31
+ responseType: "arrayBuffer",
32
+ ignoreResponseError: true,
33
+ baseURL: kirby.url,
34
+ ...isQueryRequest2 ? {
35
+ method: "POST",
36
+ body: query
37
+ } : {
38
+ method,
39
+ query,
40
+ body: body2
41
+ },
42
+ headers: {
43
+ ...headers,
44
+ ...createAuthHeader(kirby)
45
+ }
46
+ });
47
+ const dataArray = new Uint8Array(response._data ?? []);
48
+ const data = uint8ArrayToBase64(dataArray);
49
+ return {
50
+ status: response.status,
51
+ statusText: response.statusText,
52
+ headers: [...response.headers.entries()],
53
+ data
54
+ };
55
+ };
56
+ const cachedFetcher = defineCachedFunction(fetcher, {
57
+ name: "nuxt-kirby",
58
+ base: kirby.server.storage,
59
+ swr: kirby.server.swr,
60
+ maxAge: kirby.server.maxAge,
61
+ getKey: (event2, { key: key2 }) => key2
62
+ });
63
+ if (isQueryRequest) {
64
+ if (!body.query?.query) {
65
+ throw createError({
66
+ statusCode: 400,
67
+ statusMessage: "KQL query is empty"
68
+ });
69
+ }
70
+ } else {
71
+ if (body.path && new URL(body.path, "http://localhost").origin !== "http://localhost") {
72
+ throw createError({
73
+ statusCode: 400,
74
+ statusMessage: "Absolute URLs are not allowed"
75
+ });
76
+ }
77
+ }
78
+ try {
79
+ const response = kirby.server.cache && body.cache ? await cachedFetcher(event, { key, ...body }) : await fetcher(event, { key, ...body });
80
+ const dataArray = base64ToUint8Array(response.data);
81
+ if (response.status >= 400 && response.status < 600) {
82
+ if (isQueryRequest) {
83
+ consola.error(`Failed KQL query "${body.query?.query}" (...) with status code ${response.status}:
84
+ `, destr(
85
+ uint8ArrayToString(dataArray)
86
+ ));
87
+ if (kirby.server.verboseErrors)
88
+ consola.log("Full KQL query request:", body.query);
89
+ } else {
90
+ consola.error(`Failed ${(body.method || "get").toUpperCase()} request to "${body.path}"`);
91
+ }
92
+ }
93
+ const cookies = [];
94
+ for (const [key2, value] of response.headers) {
95
+ if (EXCLUDED_HEADERS.has(key2))
96
+ continue;
97
+ if (key2 === "set-cookie") {
98
+ cookies.push(...splitCookiesString(value));
99
+ continue;
100
+ }
101
+ setResponseHeader(event, key2, value);
102
+ }
103
+ if (cookies.length > 0)
104
+ setResponseHeader(event, "set-cookie", cookies);
105
+ setResponseStatus(event, response.status, response.statusText);
106
+ return dataArray;
107
+ } catch (error) {
108
+ consola.error(error);
109
+ throw createError({
110
+ statusCode: 503,
111
+ statusMessage: "Service Unavailable"
112
+ });
113
+ }
114
+ });
@@ -0,0 +1,16 @@
1
+ import type { KirbyQueryRequest, KirbyQueryResponse } from 'kirby-types';
2
+ import type { NitroFetchOptions } from 'nitropack';
3
+ export type KirbyFetchOptions = Omit<NitroFetchOptions<string>, 'baseURL'> & {
4
+ /**
5
+ * Language code to fetch data for in multi-language Kirby setups.
6
+ */
7
+ language?: string;
8
+ };
9
+ export type KqlFetchOptions = Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'headers' | 'retry' | 'retryDelay' | 'retryStatusCodes' | 'timeout' | 'signal'> & {
10
+ /**
11
+ * Language code to fetch data for in multi-language Kirby setups.
12
+ */
13
+ language?: string;
14
+ };
15
+ export declare function $kirby<T = any>(path: string, opts?: KirbyFetchOptions): Promise<T>;
16
+ export declare function $kql<T extends KirbyQueryResponse<any, boolean> = KirbyQueryResponse>(query: KirbyQueryRequest, opts?: KqlFetchOptions): Promise<T>;
@@ -0,0 +1,32 @@
1
+ import { useRuntimeConfig } from "#imports";
2
+ import { joinURL } from "ufo";
3
+ import { createAuthHeader, headersToObject } from "../utils.js";
4
+ export function $kirby(path, opts = {}) {
5
+ const { headers, language, ...fetchOptions } = opts;
6
+ const kirby = useRuntimeConfig().kirby;
7
+ if (language)
8
+ path = joinURL(language, path);
9
+ return globalThis.$fetch(path, {
10
+ ...fetchOptions,
11
+ baseURL: kirby.url,
12
+ headers: {
13
+ ...headersToObject(headers),
14
+ ...createAuthHeader(kirby)
15
+ }
16
+ });
17
+ }
18
+ export function $kql(query, opts = {}) {
19
+ const { headers, language, ...fetchOptions } = opts;
20
+ const kirby = useRuntimeConfig().kirby;
21
+ return globalThis.$fetch(kirby.prefix, {
22
+ ...fetchOptions,
23
+ baseURL: kirby.url,
24
+ method: "POST",
25
+ body: query,
26
+ headers: {
27
+ ...headersToObject(headers),
28
+ ...createAuthHeader(kirby),
29
+ ...language && { "X-Language": language }
30
+ }
31
+ });
32
+ }
@@ -0,0 +1,7 @@
1
+ import type { KirbyQueryRequest } from 'kirby-types';
2
+ import type { NitroFetchOptions } from 'nitropack';
3
+ export interface ServerFetchOptions extends Pick<NitroFetchOptions<string>, 'method' | 'headers' | 'query' | 'body'> {
4
+ query?: Partial<KirbyQueryRequest>;
5
+ path?: string;
6
+ cache?: boolean;
7
+ }
File without changes
@@ -0,0 +1,12 @@
1
+ export declare function buildApiProxyPath(key: string): string;
2
+ export declare function headersToObject(headers?: HeadersInit): Record<string, string>;
3
+ export declare function createAuthHeader({ auth, token, credentials, }: {
4
+ auth?: string;
5
+ token?: string;
6
+ credentials?: {
7
+ username: string;
8
+ password: string;
9
+ };
10
+ }): {
11
+ Authorization: string;
12
+ } | undefined;
@@ -0,0 +1,19 @@
1
+ export function buildApiProxyPath(key) {
2
+ return `/api/__kirby__/${encodeURIComponent(key)}`;
3
+ }
4
+ export function headersToObject(headers = {}) {
5
+ return Object.fromEntries(new Headers(headers));
6
+ }
7
+ export function createAuthHeader({
8
+ auth,
9
+ token,
10
+ credentials
11
+ }) {
12
+ if (auth === "basic" && credentials) {
13
+ const { username, password } = credentials;
14
+ const encoded = globalThis.btoa(`${username}:${password}`);
15
+ return { Authorization: `Basic ${encoded}` };
16
+ }
17
+ if (auth === "bearer")
18
+ return { Authorization: `Bearer ${token}` };
19
+ }
@@ -0,0 +1,3 @@
1
+ export { default } from './module.mjs'
2
+
3
+ export { type ModuleOptions } from './module.mjs'
package/package.json CHANGED
@@ -1,12 +1,74 @@
1
1
  {
2
2
  "name": "nuxt-kirby",
3
- "version": "1.1.0",
4
- "description": "",
5
- "license": "ISC",
6
- "author": "",
7
- "type": "commonjs",
8
- "main": "index.js",
3
+ "type": "module",
4
+ "version": "3.0.0",
5
+ "packageManager": "pnpm@10.17.0",
6
+ "description": "Kirby CMS Integration for Nuxt with KQL support",
7
+ "author": "Johann Schopplich <hello@johannschopplich.com>",
8
+ "license": "MIT",
9
+ "homepage": "https://nuxt-kirby.byjohann.dev",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/johannschopplich/nuxt-kirby.git"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/johannschopplich/nuxt-kirby/issues"
16
+ },
17
+ "keywords": [
18
+ "getkirby",
19
+ "kirby",
20
+ "kql",
21
+ "nuxt",
22
+ "query"
23
+ ],
24
+ "sideEffects": false,
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/types.d.mts",
28
+ "default": "./dist/module.mjs"
29
+ }
30
+ },
31
+ "main": "./dist/module.mjs",
32
+ "types": "./dist/types.d.mts",
33
+ "files": [
34
+ "dist"
35
+ ],
9
36
  "scripts": {
10
- "test": "echo \"Error: no test specified\" && exit 1"
37
+ "prepack": "nuxt-module-build build",
38
+ "dev": "nuxt dev playground",
39
+ "dev:build": "nuxt build playground",
40
+ "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground && nuxt prepare test/fixture",
41
+ "docs:dev": "vitepress dev docs",
42
+ "docs:build": "vitepress build docs",
43
+ "docs:preview": "vitepress preview docs",
44
+ "lint": "eslint .",
45
+ "lint:fix": "eslint . --fix",
46
+ "test": "vitest",
47
+ "test:types": "tsc --noEmit",
48
+ "release": "bumpp"
49
+ },
50
+ "dependencies": {
51
+ "@nuxt/kit": "^4.1.2",
52
+ "@vueuse/core": "^13.9.0",
53
+ "defu": "^6.1.4",
54
+ "kirby-types": "^1.0.0",
55
+ "ofetch": "^1.4.1",
56
+ "ohash": "^2.0.11",
57
+ "pathe": "^2.0.3",
58
+ "scule": "^1.3.0",
59
+ "ufo": "^1.6.1",
60
+ "uint8array-extras": "^1.5.0"
61
+ },
62
+ "devDependencies": {
63
+ "@antfu/eslint-config": "^5.3.0",
64
+ "@nuxt/module-builder": "^1.0.2",
65
+ "@nuxt/test-utils": "^3.19.2",
66
+ "@types/node": "^24.5.2",
67
+ "bumpp": "^10.2.3",
68
+ "destr": "^2.0.5",
69
+ "eslint": "^9.35.0",
70
+ "nuxt": "^4.1.2",
71
+ "typescript": "^5.9.2",
72
+ "vitest": "^3.2.4"
11
73
  }
12
74
  }