@tinyzoo/client 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,10 @@
1
+ Copyright (c) 2026 Vojtěch Moravec. All rights reserved.
2
+
3
+ This software and its source code are proprietary. They are published so that
4
+ sites built with the author's permission can install them; no licence to use,
5
+ copy, modify, merge, publish, distribute, sublicense or sell the software, in
6
+ whole or in part, is granted without the author's prior written permission.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9
+ IMPLIED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
10
+ LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR ITS USE.
package/README.md CHANGED
@@ -1,3 +1,68 @@
1
- # Temporary Holding Version
1
+ # @tinyzoo/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A tiny (~2 kB), dependency-free, **strictly-typed** client for the public content
4
+ API of a [tinyzoo](https://github.com/tinyzookeeper/tinyzoo) instance. Works in any framework or runtime with
5
+ `fetch` (browser, Node 18+, Workers, Deno, Bun).
6
+
7
+ It carries no knowledge of your specific schema — all types come from a generated
8
+ `cms-content.ts`, so this runtime is stable across schema changes.
9
+
10
+ ## Setup (separate frontend app)
11
+
12
+ 1. Generate the typed bindings from your running CMS:
13
+
14
+ ```sh
15
+ curl https://cms.example.com/api/content-types.ts -o src/cms-content.ts
16
+ # or, with repo access: `tinyzoo client --stdout > src/cms-content.ts`
17
+ ```
18
+
19
+ 2. Install this runtime:
20
+
21
+ ```sh
22
+ npm i @tinyzoo/client
23
+ ```
24
+
25
+ 3. Use it — fully typed, with autocomplete on collections, fields, sort keys and filters:
26
+
27
+ ```ts
28
+ import { createClient } from './cms-content'
29
+
30
+ const cms = createClient({ baseUrl: 'https://cms.example.com' })
31
+
32
+ const { items, total } = await cms.post.list({
33
+ filter: { status: 'published' }, // ← typed: 'draft' | 'published'
34
+ sort: 'publishedAt', // ← typed to this collection's sort keys
35
+ dir: 'desc',
36
+ limit: 10,
37
+ })
38
+ // ^? Post[]
39
+
40
+ const post = await cms.post.get('hello-world')
41
+ // ^? Post — post.author.name, post.hero?.url, post.tags[0].slug all typed
42
+ ```
43
+
44
+ ## API
45
+
46
+ - `createClient(options)` / `createCmsClient<Schema>(options)` — build a client.
47
+ - `baseUrl` — CMS origin (use `''` for same-origin in the browser).
48
+ - `token` — sent as `x-api-key` when the content API is gated.
49
+ - `headers`, `fetch` — optional overrides.
50
+ - `client.<collection>.list(params?)` → `{ items, total, page, limit }`.
51
+ - `client.<collection>.get(slugOrId)` → the item (throws `CmsError` on 404).
52
+ - `client.collection(name)` — same, with a runtime name.
53
+ - `client.search(query, { locale?, limit?, collections? })` — the website search: published entries of every collection with an address, best first, each with its `path`, an `excerpt` and highlight ranges.
54
+ - `client.openapi()` — fetch the OpenAPI 3.1 document.
55
+
56
+ Non-2xx responses throw `CmsError` (`.status`, `.statusText`, `.url`, `.body`).
57
+
58
+ ## Prefer OpenAPI / another language?
59
+
60
+ Every CMS also serves an OpenAPI 3.1 document at `/api/openapi.json` (docs UI at
61
+ `/api/openapi`). Generate a client in any language from it — e.g.
62
+ `npx openapi-typescript https://cms.example.com/api/openapi.json -o cms.d.ts`.
63
+
64
+ ## Documentation and licence
65
+
66
+ The docs are on GitHub, not in the package: [Getting started](https://github.com/tinyzookeeper/tinyzoo/blob/main/docs/guide/getting-started.md) and
67
+ [the content API](https://github.com/tinyzookeeper/tinyzoo/blob/main/docs/guide/content-api.md).
68
+ Proprietary, all rights reserved (see `LICENSE`).
@@ -0,0 +1,152 @@
1
+ interface ClientOptions {
2
+ /** Origin of the CMS, e.g. 'https://cms.example.com'. May be '' for same-origin (browser only). */
3
+ baseUrl: string;
4
+ /** Content API token (sent as `x-api-key`) when the API is gated. */
5
+ token?: string;
6
+ /** Extra headers merged into every request. */
7
+ headers?: Record<string, string>;
8
+ /** Fetch implementation override (defaults to global `fetch`). */
9
+ fetch?: typeof globalThis.fetch;
10
+ }
11
+ interface ListResponse<T> {
12
+ items: T[];
13
+ total: number;
14
+ page: number;
15
+ limit: number;
16
+ }
17
+ interface ListParams<Sort extends string = string, Filters = Record<string, never>> {
18
+ page?: number;
19
+ limit?: number;
20
+ sort?: Sort;
21
+ dir?: 'asc' | 'desc';
22
+ /** Substring search against the collection's title field. */
23
+ q?: string;
24
+ /** Filters (collection-specific): exact matches, yes/no, and date ranges (`'startsAt.from'`). */
25
+ filter?: Filters;
26
+ /** Language to serve (collections with translations). Untranslated fields fall back to the default. */
27
+ locale?: string;
28
+ }
29
+ interface GetOptions {
30
+ /** Language to serve (collections with translations). */
31
+ locale?: string;
32
+ }
33
+ interface SearchParams {
34
+ /** Language to search in (sites with translations): only entries translated into it. */
35
+ locale?: string;
36
+ /** Most results (1–50, default 10). */
37
+ limit?: number;
38
+ /** Only these collections. */
39
+ collections?: string[];
40
+ }
41
+ /** One website search result: the entry's address and a snippet around the words found. */
42
+ interface SearchItem {
43
+ /** The collection it is in. */
44
+ entity: string;
45
+ id: string;
46
+ title: string;
47
+ /** Where the words are in the title, as [start, end) character ranges. */
48
+ titleHighlights: [number, number][];
49
+ /** A sentence or two of its text around the first word found ('' when only the title matched). */
50
+ excerpt: string;
51
+ highlights: [number, number][];
52
+ /** Its address on the website, in the searched language. */
53
+ path: string | null;
54
+ locale: string | null;
55
+ updatedAt: string;
56
+ }
57
+ interface SearchResponse {
58
+ query: string;
59
+ items: SearchItem[];
60
+ total: number;
61
+ }
62
+ /** One page of the published page tree (`cms.page.tree()`): a navigation entry with the pages below it. */
63
+ interface CmsTreeNode {
64
+ id: string;
65
+ title: string;
66
+ /** Its address in the language asked for (language prefix included). */
67
+ path: string | null;
68
+ children: CmsTreeNode[];
69
+ }
70
+ interface TreeOptions {
71
+ /** Language to serve. Pages not translated into it show the default language's title and address. */
72
+ locale?: string;
73
+ }
74
+ interface CollectionSpec {
75
+ item: unknown;
76
+ /** Set (by the generated types) for a page tree: the collection then has `tree()`. */
77
+ tree?: boolean;
78
+ sort?: string;
79
+ filters?: object;
80
+ }
81
+ type AnyContentSchema = Record<string, CollectionSpec>;
82
+ type Collection<C extends CollectionSpec> = {
83
+ /** List published items, paginated, filtered and sorted. */
84
+ list: (params?: ListParams<Extract<C['sort'], string>, C['filters']>) => Promise<ListResponse<C['item']>>;
85
+ /**
86
+ * Fetch a single published item by slug (falling back to id). Throws CmsError on 404.
87
+ * In a page tree pass the address, from the top down: `get('o-nas/tym')` (or `'/o-nas/tym'`
88
+ * without the language prefix); the item then carries `path` and `breadcrumbs`.
89
+ */
90
+ get: (slugOrId: string, options?: GetOptions) => Promise<C['item']>;
91
+ } & (C extends {
92
+ tree: true;
93
+ } ? {
94
+ /** The published page tree for navigation: top level first, each page with its children. */
95
+ tree: (options?: TreeOptions) => Promise<CmsTreeNode[]>;
96
+ } : unknown);
97
+ type CmsClient<S extends AnyContentSchema, G extends object = Record<string, unknown>> = {
98
+ readonly [K in keyof S]: Collection<S[K]>;
99
+ } & {
100
+ /** Same as `client[name]`, but accepts a runtime collection name. */
101
+ collection: <K extends keyof S & string>(name: K) => Collection<S[K]>;
102
+ /** A global (site settings and other one-of-a-kind content), or null before it is first saved. */
103
+ global: <K extends keyof G & string>(name: K, options?: GetOptions) => Promise<G[K] | null>;
104
+ /** Fetch the OpenAPI 3.1 document for this CMS. */
105
+ openapi: () => Promise<unknown>;
106
+ /**
107
+ * The website search: published entries of every public collection with an address,
108
+ * best matches first (accents and case do not matter; every word must appear).
109
+ * A collection named `search` is reached with `client.collection('search')`.
110
+ */
111
+ search: (query: string, params?: SearchParams) => Promise<SearchResponse>;
112
+ };
113
+ /** Thrown for any non-2xx content API response. */
114
+ declare class CmsError extends Error {
115
+ readonly status: number;
116
+ readonly statusText: string;
117
+ readonly url: string;
118
+ readonly body: unknown;
119
+ constructor(message: string, status: number, statusText: string, url: string, body: unknown);
120
+ }
121
+ declare function createCmsClient<S extends AnyContentSchema, G extends object = Record<string, unknown>>(options: ClientOptions): CmsClient<S, G>;
122
+ /**
123
+ * A menu link as the content API returns it (defineNavigation). `url` is null when the
124
+ * link points at a page that is gone or not published (links follow their target, so a
125
+ * renamed page keeps working, and a missing one has no address).
126
+ */
127
+ interface CmsMenuLink {
128
+ id: string;
129
+ label: string;
130
+ url: string | null;
131
+ newTab?: boolean | null;
132
+ sub?: boolean | null;
133
+ }
134
+ /** A top-level menu link with the links of its dropdown. */
135
+ type CmsMenuItem<L extends CmsMenuLink = CmsMenuLink> = L & {
136
+ children: L[];
137
+ };
138
+ /**
139
+ * Nest a menu: a link marked `sub` ("under the link above") goes into the dropdown of
140
+ * the nearest top-level link before it; a `sub` link with nothing above stays on top.
141
+ *
142
+ * A link without an address (its page is gone or not published) is left out, together
143
+ * with its dropdown links, unless it has dropdown links of its own that still work: it
144
+ * then stays as a heading without a `url`, so the dropdown does not vanish.
145
+ *
146
+ * const nav = await cms.global('navigation')
147
+ * const main = cmsMenuTree(nav.main) // [{ label: 'O nás', url: '/o-nas', children: [{ label: 'Tým', … }] }, …]
148
+ */
149
+ declare function cmsMenuTree<L extends CmsMenuLink>(links: readonly L[] | null | undefined): CmsMenuItem<L>[];
150
+
151
+ export { CmsError, cmsMenuTree, createCmsClient };
152
+ export type { AnyContentSchema, ClientOptions, CmsClient, CmsMenuItem, CmsMenuLink, CmsTreeNode, Collection, CollectionSpec, GetOptions, ListParams, ListResponse, SearchItem, SearchParams, SearchResponse, TreeOptions };
@@ -0,0 +1,152 @@
1
+ interface ClientOptions {
2
+ /** Origin of the CMS, e.g. 'https://cms.example.com'. May be '' for same-origin (browser only). */
3
+ baseUrl: string;
4
+ /** Content API token (sent as `x-api-key`) when the API is gated. */
5
+ token?: string;
6
+ /** Extra headers merged into every request. */
7
+ headers?: Record<string, string>;
8
+ /** Fetch implementation override (defaults to global `fetch`). */
9
+ fetch?: typeof globalThis.fetch;
10
+ }
11
+ interface ListResponse<T> {
12
+ items: T[];
13
+ total: number;
14
+ page: number;
15
+ limit: number;
16
+ }
17
+ interface ListParams<Sort extends string = string, Filters = Record<string, never>> {
18
+ page?: number;
19
+ limit?: number;
20
+ sort?: Sort;
21
+ dir?: 'asc' | 'desc';
22
+ /** Substring search against the collection's title field. */
23
+ q?: string;
24
+ /** Filters (collection-specific): exact matches, yes/no, and date ranges (`'startsAt.from'`). */
25
+ filter?: Filters;
26
+ /** Language to serve (collections with translations). Untranslated fields fall back to the default. */
27
+ locale?: string;
28
+ }
29
+ interface GetOptions {
30
+ /** Language to serve (collections with translations). */
31
+ locale?: string;
32
+ }
33
+ interface SearchParams {
34
+ /** Language to search in (sites with translations): only entries translated into it. */
35
+ locale?: string;
36
+ /** Most results (1–50, default 10). */
37
+ limit?: number;
38
+ /** Only these collections. */
39
+ collections?: string[];
40
+ }
41
+ /** One website search result: the entry's address and a snippet around the words found. */
42
+ interface SearchItem {
43
+ /** The collection it is in. */
44
+ entity: string;
45
+ id: string;
46
+ title: string;
47
+ /** Where the words are in the title, as [start, end) character ranges. */
48
+ titleHighlights: [number, number][];
49
+ /** A sentence or two of its text around the first word found ('' when only the title matched). */
50
+ excerpt: string;
51
+ highlights: [number, number][];
52
+ /** Its address on the website, in the searched language. */
53
+ path: string | null;
54
+ locale: string | null;
55
+ updatedAt: string;
56
+ }
57
+ interface SearchResponse {
58
+ query: string;
59
+ items: SearchItem[];
60
+ total: number;
61
+ }
62
+ /** One page of the published page tree (`cms.page.tree()`): a navigation entry with the pages below it. */
63
+ interface CmsTreeNode {
64
+ id: string;
65
+ title: string;
66
+ /** Its address in the language asked for (language prefix included). */
67
+ path: string | null;
68
+ children: CmsTreeNode[];
69
+ }
70
+ interface TreeOptions {
71
+ /** Language to serve. Pages not translated into it show the default language's title and address. */
72
+ locale?: string;
73
+ }
74
+ interface CollectionSpec {
75
+ item: unknown;
76
+ /** Set (by the generated types) for a page tree: the collection then has `tree()`. */
77
+ tree?: boolean;
78
+ sort?: string;
79
+ filters?: object;
80
+ }
81
+ type AnyContentSchema = Record<string, CollectionSpec>;
82
+ type Collection<C extends CollectionSpec> = {
83
+ /** List published items, paginated, filtered and sorted. */
84
+ list: (params?: ListParams<Extract<C['sort'], string>, C['filters']>) => Promise<ListResponse<C['item']>>;
85
+ /**
86
+ * Fetch a single published item by slug (falling back to id). Throws CmsError on 404.
87
+ * In a page tree pass the address, from the top down: `get('o-nas/tym')` (or `'/o-nas/tym'`
88
+ * without the language prefix); the item then carries `path` and `breadcrumbs`.
89
+ */
90
+ get: (slugOrId: string, options?: GetOptions) => Promise<C['item']>;
91
+ } & (C extends {
92
+ tree: true;
93
+ } ? {
94
+ /** The published page tree for navigation: top level first, each page with its children. */
95
+ tree: (options?: TreeOptions) => Promise<CmsTreeNode[]>;
96
+ } : unknown);
97
+ type CmsClient<S extends AnyContentSchema, G extends object = Record<string, unknown>> = {
98
+ readonly [K in keyof S]: Collection<S[K]>;
99
+ } & {
100
+ /** Same as `client[name]`, but accepts a runtime collection name. */
101
+ collection: <K extends keyof S & string>(name: K) => Collection<S[K]>;
102
+ /** A global (site settings and other one-of-a-kind content), or null before it is first saved. */
103
+ global: <K extends keyof G & string>(name: K, options?: GetOptions) => Promise<G[K] | null>;
104
+ /** Fetch the OpenAPI 3.1 document for this CMS. */
105
+ openapi: () => Promise<unknown>;
106
+ /**
107
+ * The website search: published entries of every public collection with an address,
108
+ * best matches first (accents and case do not matter; every word must appear).
109
+ * A collection named `search` is reached with `client.collection('search')`.
110
+ */
111
+ search: (query: string, params?: SearchParams) => Promise<SearchResponse>;
112
+ };
113
+ /** Thrown for any non-2xx content API response. */
114
+ declare class CmsError extends Error {
115
+ readonly status: number;
116
+ readonly statusText: string;
117
+ readonly url: string;
118
+ readonly body: unknown;
119
+ constructor(message: string, status: number, statusText: string, url: string, body: unknown);
120
+ }
121
+ declare function createCmsClient<S extends AnyContentSchema, G extends object = Record<string, unknown>>(options: ClientOptions): CmsClient<S, G>;
122
+ /**
123
+ * A menu link as the content API returns it (defineNavigation). `url` is null when the
124
+ * link points at a page that is gone or not published (links follow their target, so a
125
+ * renamed page keeps working, and a missing one has no address).
126
+ */
127
+ interface CmsMenuLink {
128
+ id: string;
129
+ label: string;
130
+ url: string | null;
131
+ newTab?: boolean | null;
132
+ sub?: boolean | null;
133
+ }
134
+ /** A top-level menu link with the links of its dropdown. */
135
+ type CmsMenuItem<L extends CmsMenuLink = CmsMenuLink> = L & {
136
+ children: L[];
137
+ };
138
+ /**
139
+ * Nest a menu: a link marked `sub` ("under the link above") goes into the dropdown of
140
+ * the nearest top-level link before it; a `sub` link with nothing above stays on top.
141
+ *
142
+ * A link without an address (its page is gone or not published) is left out, together
143
+ * with its dropdown links, unless it has dropdown links of its own that still work: it
144
+ * then stays as a heading without a `url`, so the dropdown does not vanish.
145
+ *
146
+ * const nav = await cms.global('navigation')
147
+ * const main = cmsMenuTree(nav.main) // [{ label: 'O nás', url: '/o-nas', children: [{ label: 'Tým', … }] }, …]
148
+ */
149
+ declare function cmsMenuTree<L extends CmsMenuLink>(links: readonly L[] | null | undefined): CmsMenuItem<L>[];
150
+
151
+ export { CmsError, cmsMenuTree, createCmsClient };
152
+ export type { AnyContentSchema, ClientOptions, CmsClient, CmsMenuItem, CmsMenuLink, CmsTreeNode, Collection, CollectionSpec, GetOptions, ListParams, ListResponse, SearchItem, SearchParams, SearchResponse, TreeOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,100 @@
1
+ class CmsError extends Error {
2
+ status;
3
+ statusText;
4
+ url;
5
+ body;
6
+ constructor(message, status, statusText, url, body) {
7
+ super(message);
8
+ this.name = "CmsError";
9
+ this.status = status;
10
+ this.statusText = statusText;
11
+ this.url = url;
12
+ this.body = body;
13
+ }
14
+ }
15
+ function buildQuery(query) {
16
+ if (!query) return "";
17
+ const sp = new URLSearchParams();
18
+ for (const [k, v] of Object.entries(query)) {
19
+ if (v === void 0 || v === null || v === "") continue;
20
+ sp.set(k, v instanceof Date ? v.toISOString() : String(v));
21
+ }
22
+ const s = sp.toString();
23
+ return s ? `?${s}` : "";
24
+ }
25
+ function createCmsClient(options) {
26
+ const base = options.baseUrl.replace(/\/+$/, "");
27
+ const doFetch = options.fetch ?? globalThis.fetch;
28
+ if (typeof doFetch !== "function") {
29
+ throw new Error("@tinyzoo/client: no fetch available \u2014 pass options.fetch");
30
+ }
31
+ async function request(path, query) {
32
+ const target = base + path + buildQuery(query);
33
+ const headers = { accept: "application/json", ...options.headers ?? {} };
34
+ if (options.token) headers["x-api-key"] = options.token;
35
+ const res = await doFetch(target, { headers });
36
+ if (!res.ok) {
37
+ let body;
38
+ try {
39
+ body = await res.clone().json();
40
+ } catch {
41
+ try {
42
+ body = await res.text();
43
+ } catch {
44
+ }
45
+ }
46
+ throw new CmsError(`Content API ${res.status} ${res.statusText} for ${path}`, res.status, res.statusText, target, body);
47
+ }
48
+ return res.json();
49
+ }
50
+ function collection(name) {
51
+ const seg = encodeURIComponent(name);
52
+ const list = (params = {}) => {
53
+ const { filter, ...rest } = params;
54
+ return request(`/api/content/${seg}`, { ...filter ?? {}, ...rest });
55
+ };
56
+ const get = async (slugOrId, opts = {}) => {
57
+ const res = await request(`/api/content/${seg}/${encodeURIComponent(slugOrId)}`, { locale: opts.locale });
58
+ return res.item;
59
+ };
60
+ const tree = async (opts = {}) => {
61
+ const res = await request(`/api/content/_tree/${seg}`, { locale: opts.locale });
62
+ return res.items;
63
+ };
64
+ return { list, get, tree };
65
+ }
66
+ const global = async (name, opts = {}) => {
67
+ const res = await request(`/api/content/_global/${encodeURIComponent(name)}`, { locale: opts.locale });
68
+ return res.item;
69
+ };
70
+ const root = {
71
+ collection,
72
+ global,
73
+ openapi: () => request("/api/openapi.json"),
74
+ search: (query, params = {}) => request("/api/content/_search", {
75
+ q: query,
76
+ locale: params.locale,
77
+ limit: params.limit,
78
+ entity: params.collections?.length ? params.collections.join(",") : void 0
79
+ })
80
+ };
81
+ return new Proxy(root, {
82
+ get(target, prop, receiver) {
83
+ if (typeof prop !== "string" || prop === "then" || prop in Object.prototype || Object.hasOwn(target, prop)) {
84
+ return Reflect.get(target, prop, receiver);
85
+ }
86
+ return collection(prop);
87
+ }
88
+ });
89
+ }
90
+ function cmsMenuTree(links) {
91
+ const out = [];
92
+ for (const link of links ?? []) {
93
+ const parent = out[out.length - 1];
94
+ if (link.sub && parent) parent.children.push(link);
95
+ else out.push({ ...link, children: [] });
96
+ }
97
+ return out.map((item) => ({ ...item, children: item.children.filter((c) => !!c.url) })).filter((item) => !!item.url || item.children.length > 0);
98
+ }
99
+
100
+ export { CmsError, cmsMenuTree, createCmsClient };
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@tinyzoo/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "description": "Tiny, dependency-free, strictly-typed client for the tinyzoo content API.",
6
+ "license": "UNLICENSED",
7
+ "homepage": "https://github.com/tinyzookeeper/tinyzoo/tree/main/packages/client#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/tinyzookeeper/tinyzoo.git",
11
+ "directory": "packages/client"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/tinyzookeeper/tinyzoo/issues"
15
+ },
16
+ "keywords": [
17
+ "cms",
18
+ "headless-cms",
19
+ "client",
20
+ "typescript",
21
+ "fetch",
22
+ "tinyzoo"
23
+ ],
24
+ "sideEffects": false,
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.mjs"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "main": "./dist/index.mjs",
33
+ "types": "./dist/index.d.ts",
34
+ "files": [
35
+ "README.md",
36
+ "LICENSE",
37
+ "src",
38
+ "dist"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "devDependencies": {
44
+ "typescript": "^5.7.0",
45
+ "unbuild": "^3.0.0"
46
+ },
47
+ "engines": {
48
+ "node": ">=22"
49
+ },
50
+ "scripts": {
51
+ "build": "unbuild"
52
+ }
6
53
  }
package/src/index.ts ADDED
@@ -0,0 +1,264 @@
1
+ // @tinyzoo/client — a tiny, dependency-free, strictly-typed client for the public
2
+ // content API. It carries ZERO knowledge of any specific CMS: all types come from
3
+ // a generated `ContentSchema` (see `tinyzoo client`), so the runtime is stable across
4
+ // schema changes and the same build serves every CMS instance.
5
+ //
6
+ // import { createClient } from './cms-content' // generated
7
+ // const cms = createClient({ baseUrl: 'https://cms.example.com' })
8
+ // const { items } = await cms.post.list({ filter: { status: 'published' }, sort: 'publishedAt' })
9
+ // const post = await cms.post.get('hello-world')
10
+
11
+ export interface ClientOptions {
12
+ /** Origin of the CMS, e.g. 'https://cms.example.com'. May be '' for same-origin (browser only). */
13
+ baseUrl: string
14
+ /** Content API token (sent as `x-api-key`) when the API is gated. */
15
+ token?: string
16
+ /** Extra headers merged into every request. */
17
+ headers?: Record<string, string>
18
+ /** Fetch implementation override (defaults to global `fetch`). */
19
+ fetch?: typeof globalThis.fetch
20
+ }
21
+
22
+ export interface ListResponse<T> {
23
+ items: T[]
24
+ total: number
25
+ page: number
26
+ limit: number
27
+ }
28
+
29
+ export interface ListParams<Sort extends string = string, Filters = Record<string, never>> {
30
+ page?: number
31
+ limit?: number
32
+ sort?: Sort
33
+ dir?: 'asc' | 'desc'
34
+ /** Substring search against the collection's title field. */
35
+ q?: string
36
+ /** Filters (collection-specific): exact matches, yes/no, and date ranges (`'startsAt.from'`). */
37
+ filter?: Filters
38
+ /** Language to serve (collections with translations). Untranslated fields fall back to the default. */
39
+ locale?: string
40
+ }
41
+
42
+ export interface GetOptions {
43
+ /** Language to serve (collections with translations). */
44
+ locale?: string
45
+ }
46
+
47
+ export interface SearchParams {
48
+ /** Language to search in (sites with translations): only entries translated into it. */
49
+ locale?: string
50
+ /** Most results (1–50, default 10). */
51
+ limit?: number
52
+ /** Only these collections. */
53
+ collections?: string[]
54
+ }
55
+
56
+ /** One website search result: the entry's address and a snippet around the words found. */
57
+ export interface SearchItem {
58
+ /** The collection it is in. */
59
+ entity: string
60
+ id: string
61
+ title: string
62
+ /** Where the words are in the title, as [start, end) character ranges. */
63
+ titleHighlights: [number, number][]
64
+ /** A sentence or two of its text around the first word found ('' when only the title matched). */
65
+ excerpt: string
66
+ highlights: [number, number][]
67
+ /** Its address on the website, in the searched language. */
68
+ path: string | null
69
+ locale: string | null
70
+ updatedAt: string
71
+ }
72
+
73
+ export interface SearchResponse { query: string; items: SearchItem[]; total: number }
74
+
75
+ /** One page of the published page tree (`cms.page.tree()`): a navigation entry with the pages below it. */
76
+ export interface CmsTreeNode {
77
+ id: string
78
+ title: string
79
+ /** Its address in the language asked for (language prefix included). */
80
+ path: string | null
81
+ children: CmsTreeNode[]
82
+ }
83
+
84
+ export interface TreeOptions {
85
+ /** Language to serve. Pages not translated into it show the default language's title and address. */
86
+ locale?: string
87
+ }
88
+
89
+ export interface CollectionSpec {
90
+ item: unknown
91
+ /** Set (by the generated types) for a page tree: the collection then has `tree()`. */
92
+ tree?: boolean
93
+ sort?: string
94
+ // `object` (not Record<string, unknown>) so a generated `interface XFilters`
95
+ // still satisfies it — interfaces don't satisfy index-signature constraints.
96
+ filters?: object
97
+ }
98
+ export type AnyContentSchema = Record<string, CollectionSpec>
99
+
100
+ export type Collection<C extends CollectionSpec> = {
101
+ /** List published items, paginated, filtered and sorted. */
102
+ list: (params?: ListParams<Extract<C['sort'], string>, C['filters']>) => Promise<ListResponse<C['item']>>
103
+ /**
104
+ * Fetch a single published item by slug (falling back to id). Throws CmsError on 404.
105
+ * In a page tree pass the address, from the top down: `get('o-nas/tym')` (or `'/o-nas/tym'`
106
+ * without the language prefix); the item then carries `path` and `breadcrumbs`.
107
+ */
108
+ get: (slugOrId: string, options?: GetOptions) => Promise<C['item']>
109
+ } & (C extends { tree: true }
110
+ ? {
111
+ /** The published page tree for navigation: top level first, each page with its children. */
112
+ tree: (options?: TreeOptions) => Promise<CmsTreeNode[]>
113
+ }
114
+ : unknown)
115
+
116
+ export type CmsClient<S extends AnyContentSchema, G extends object = Record<string, unknown>> =
117
+ & { readonly [K in keyof S]: Collection<S[K]> }
118
+ & {
119
+ /** Same as `client[name]`, but accepts a runtime collection name. */
120
+ collection: <K extends keyof S & string>(name: K) => Collection<S[K]>
121
+ /** A global (site settings and other one-of-a-kind content), or null before it is first saved. */
122
+ global: <K extends keyof G & string>(name: K, options?: GetOptions) => Promise<G[K] | null>
123
+ /** Fetch the OpenAPI 3.1 document for this CMS. */
124
+ openapi: () => Promise<unknown>
125
+ /**
126
+ * The website search: published entries of every public collection with an address,
127
+ * best matches first (accents and case do not matter; every word must appear).
128
+ * A collection named `search` is reached with `client.collection('search')`.
129
+ */
130
+ search: (query: string, params?: SearchParams) => Promise<SearchResponse>
131
+ }
132
+
133
+ /** Thrown for any non-2xx content API response. */
134
+ export class CmsError extends Error {
135
+ readonly status: number
136
+ readonly statusText: string
137
+ readonly url: string
138
+ readonly body: unknown
139
+ constructor(message: string, status: number, statusText: string, url: string, body: unknown) {
140
+ super(message)
141
+ this.name = 'CmsError'
142
+ this.status = status
143
+ this.statusText = statusText
144
+ this.url = url
145
+ this.body = body
146
+ }
147
+ }
148
+
149
+ function buildQuery(query?: Record<string, unknown>): string {
150
+ if (!query) return ''
151
+ const sp = new URLSearchParams()
152
+ for (const [k, v] of Object.entries(query)) {
153
+ if (v === undefined || v === null || v === '') continue
154
+ sp.set(k, v instanceof Date ? v.toISOString() : String(v))
155
+ }
156
+ const s = sp.toString()
157
+ return s ? `?${s}` : ''
158
+ }
159
+
160
+ export function createCmsClient<S extends AnyContentSchema, G extends object = Record<string, unknown>>(options: ClientOptions): CmsClient<S, G> {
161
+ const base = options.baseUrl.replace(/\/+$/, '')
162
+ const doFetch = options.fetch ?? globalThis.fetch
163
+ if (typeof doFetch !== 'function') {
164
+ throw new Error('@tinyzoo/client: no fetch available — pass options.fetch')
165
+ }
166
+
167
+ async function request<T>(path: string, query?: Record<string, unknown>): Promise<T> {
168
+ const target = base + path + buildQuery(query)
169
+ const headers: Record<string, string> = { accept: 'application/json', ...(options.headers ?? {}) }
170
+ if (options.token) headers['x-api-key'] = options.token
171
+
172
+ const res = await doFetch(target, { headers })
173
+ if (!res.ok) {
174
+ let body: unknown
175
+ try { body = await res.clone().json() }
176
+ catch { try { body = await res.text() } catch { /* ignore */ } }
177
+ throw new CmsError(`Content API ${res.status} ${res.statusText} for ${path}`, res.status, res.statusText, target, body)
178
+ }
179
+ return res.json() as Promise<T>
180
+ }
181
+
182
+ function collection(name: string): Collection<CollectionSpec> {
183
+ const seg = encodeURIComponent(name)
184
+ const list = (params: ListParams = {}) => {
185
+ const { filter, ...rest } = params
186
+ // reserved params (rest) spread LAST so a filter key can never clobber page/limit/sort/dir/q
187
+ return request(`/api/content/${seg}`, { ...((filter as Record<string, unknown>) ?? {}), ...rest })
188
+ }
189
+ const get = async (slugOrId: string, opts: GetOptions = {}) => {
190
+ // A page tree's address has slashes: sent as one escaped segment (%2F), which the server reads as the chain.
191
+ const res = await request<{ item: unknown }>(`/api/content/${seg}/${encodeURIComponent(slugOrId)}`, { locale: opts.locale })
192
+ return res.item
193
+ }
194
+ const tree = async (opts: TreeOptions = {}) => {
195
+ const res = await request<{ items: CmsTreeNode[] }>(`/api/content/_tree/${seg}`, { locale: opts.locale })
196
+ return res.items
197
+ }
198
+ return { list, get, tree } as unknown as Collection<CollectionSpec>
199
+ }
200
+
201
+ const global = async (name: string, opts: GetOptions = {}) => {
202
+ const res = await request<{ item: unknown }>(`/api/content/_global/${encodeURIComponent(name)}`, { locale: opts.locale })
203
+ return res.item
204
+ }
205
+
206
+ const root = {
207
+ collection,
208
+ global,
209
+ openapi: () => request('/api/openapi.json'),
210
+ search: (query: string, params: SearchParams = {}) => request<SearchResponse>('/api/content/_search', {
211
+ q: query,
212
+ locale: params.locale,
213
+ limit: params.limit,
214
+ entity: params.collections?.length ? params.collections.join(',') : undefined,
215
+ }),
216
+ }
217
+
218
+ // Access-only proxy: the runtime is schema-agnostic, so collections are resolved
219
+ // lazily on property access and are NOT enumerable (`Object.keys`/`in` won't list
220
+ // them). `then` is trapped so the client is never mistaken for a thenable, and
221
+ // Object.prototype members keep their normal meaning (so a collection named e.g.
222
+ // `toString` is reachable only via `client.collection('toString')`).
223
+ return new Proxy(root, {
224
+ get(target, prop, receiver) {
225
+ if (typeof prop !== 'string' || prop === 'then' || prop in Object.prototype || Object.hasOwn(target, prop)) {
226
+ return Reflect.get(target, prop, receiver)
227
+ }
228
+ return collection(prop)
229
+ },
230
+ }) as unknown as CmsClient<S>
231
+ }
232
+
233
+ /**
234
+ * A menu link as the content API returns it (defineNavigation). `url` is null when the
235
+ * link points at a page that is gone or not published (links follow their target, so a
236
+ * renamed page keeps working, and a missing one has no address).
237
+ */
238
+ export interface CmsMenuLink { id: string; label: string; url: string | null; newTab?: boolean | null; sub?: boolean | null }
239
+ /** A top-level menu link with the links of its dropdown. */
240
+ export type CmsMenuItem<L extends CmsMenuLink = CmsMenuLink> = L & { children: L[] }
241
+
242
+ /**
243
+ * Nest a menu: a link marked `sub` ("under the link above") goes into the dropdown of
244
+ * the nearest top-level link before it; a `sub` link with nothing above stays on top.
245
+ *
246
+ * A link without an address (its page is gone or not published) is left out, together
247
+ * with its dropdown links, unless it has dropdown links of its own that still work: it
248
+ * then stays as a heading without a `url`, so the dropdown does not vanish.
249
+ *
250
+ * const nav = await cms.global('navigation')
251
+ * const main = cmsMenuTree(nav.main) // [{ label: 'O nás', url: '/o-nas', children: [{ label: 'Tým', … }] }, …]
252
+ */
253
+ export function cmsMenuTree<L extends CmsMenuLink>(links: readonly L[] | null | undefined): CmsMenuItem<L>[] {
254
+ const out: CmsMenuItem<L>[] = []
255
+ for (const link of links ?? []) {
256
+ const parent = out[out.length - 1]
257
+ if (link.sub && parent) parent.children.push(link)
258
+ else out.push({ ...link, children: [] })
259
+ }
260
+ // Dropdown links that lead nowhere go; a top link that leads nowhere goes unless a dropdown link remains.
261
+ return out
262
+ .map((item) => ({ ...item, children: item.children.filter((c) => !!c.url) }))
263
+ .filter((item) => !!item.url || item.children.length > 0)
264
+ }