@intensevisions/content-client 0.0.0-stage → 0.1.1

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) 2026 Chad Warner
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 CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # @intensevisions/content-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
+ ## Install
4
+
5
+ Outside the agency monorepo, install the published package (it brings `@intensevisions/content-contract` with it):
6
+
7
+ ```sh
8
+ pnpm add @intensevisions/content-client
9
+ ```
10
+
11
+ Packages are published under the agency's npm scope, `@intensevisions` by default (`pnpm add
12
+ @intensevisions/content-client`); inside the monorepo the same package is used from source with `workspace:*`.
13
+ Next.js sites should start from `@intensevisions/content-next`, which adds image URLs, plain text, reference helpers and the
14
+ publish-hook route. Maintainers publish all three packages with `pnpm content:packages --version <x.y.z>` (a dry run;
15
+ add `--publish` to publish).
16
+
17
+ The public, server-safe read client for published IV Content records. It never accepts a preview token and has no draft
18
+ or mutation methods. Use it from a server component, route handler, or build process; keep private preview in a separate
19
+ server-only integration. It has no dependencies beyond the contract types.
20
+
21
+ ```ts
22
+ const content = createContentClient({ siteKey: 'example.com', revalidateSeconds: 60 });
23
+
24
+ // One document by slug, with its references filled in.
25
+ const book = await content.get('book', 'low-tide', { expand: ['series', 'relatedBooks'] });
26
+
27
+ // By id (any type, or only of one type), and many by id in the order asked.
28
+ const series = await content.getById('series', 'sanity:abc');
29
+ const picks = await content.getMany(['sanity:a', 'sanity:b'], { expand: '*' });
30
+
31
+ // Filter, sort and page.
32
+ const page = await content.list('book', { where: { featured: true }, order: '-year', limit: 12, expand: ['series'] });
33
+ const next = page.nextCursor ? await content.list('book', { where: { featured: true }, order: '-year', limit: 12, cursor: page.nextCursor }) : null;
34
+
35
+ const imageUrl = content.assetUrl(book!.data.cover.assetId, { width: 800, format: 'auto' });
36
+ ```
37
+
38
+ ## Methods
39
+
40
+ | Method | Request | Answer |
41
+ | --- | --- | --- |
42
+ | `get(type, slug, { expand?, expandDepth? })` | `GET /v1/sites/:site/:type/:slug` | the document, or `null` |
43
+ | `getById(id, opts?)` / `getById(type, id, opts?)` | `GET /v1/sites/:site/documents?ids=:id` | the document (of `type`, when given), or `null` |
44
+ | `getMany(ids, { expand?, expandDepth? })` | `GET /v1/sites/:site/documents?ids=a,b,c` | documents in the order asked (more than 100 ids are split into several requests) |
45
+ | `list(type, { where?, order?, cursor?, limit?, expand?, expandDepth? })` | `GET /v1/sites/:site/:type` | `{ documents, nextCursor? }` |
46
+ | `assetUrl(assetId, transform?)` | — | the media URL (`/v1/sites/:site/assets/:id`) |
47
+
48
+ Every document is a `PublishedContentDocument`: `{ id, siteKey, type, schemaVersion, title?, slug, revision, data,
49
+ publishedAt }`. Ids that don't exist or aren't published are left out of `getMany`; `get` and `getById` answer `null`.
50
+
51
+ ## Query parameters
52
+
53
+ - **`expand`**: `*` (every reference of the type's schema) or comma-separated field names, dotted for nested ones
54
+ (`seo.ogBook`); naming an object or array field expands the references inside it. Each selected reference id is
55
+ replaced by the referenced document's published projection (the same shape as above). A reference whose target isn't
56
+ published becomes `null`; in a list (a multiple reference, an array) it is dropped. Drafts never appear.
57
+ - **`expandDepth`**: `1` (default) or `2`. At depth 2 the expanded documents expand the same field names against their
58
+ own schema; references beyond the depth stay ids, so cycles end.
59
+ - **`where[field]=value`** (lists): equality on top-level `string`, `text`, `url`, `number`, `boolean`, `date` and
60
+ `datetime` fields, read from the published revision and coerced by the field's type (`true`/`false`, numbers). Up to 10,
61
+ all must match.
62
+ - **`order`** (lists): a top-level field of those types, `-field` for descending. Ties, and the default order, go by id;
63
+ a missing value sorts first ascending and last descending.
64
+ - **`cursor`**, **`limit`** (lists, 1–100, default 25): pass `nextCursor` back unchanged with the same `where` and
65
+ `order`. A cursor from another order is refused.
66
+
67
+ A field the schema doesn't have, a field that can't be filtered or sorted, a non-reference `expand` field, or a bad
68
+ cursor answers 400 `{ error: 'invalid', message }`; the client throws an `Error` that carries the message.
69
+
70
+ ## Freshness
71
+
72
+ Delivery URLs use the public `CONTENT_BASE_URL` origin (default `https://content.intensevisions.com`). The API serves
73
+ published snapshots only; media URLs resolve only when an asset is attached to a published revision.
74
+
75
+ Answers are cached at Cloudflare's edge, and every publish or unpublish retires the site's cached answers at once (a
76
+ per-site generation in the cache key). Responses say `Cache-Control: public, max-age=0, s-maxage=5`, so a server
77
+ fetching them sees a publish within seconds; with Next.js, `revalidateSeconds` (or a publish hook that revalidates the
78
+ affected routes) decides how long your own cache keeps a page. `X-Content-Cache` says `HIT`, `MISS` or `BYPASS`.
@@ -0,0 +1,40 @@
1
+ import type { ContentExpandOptions, ContentWhereValue, PublishedContentDocument, PublishedContentDocumentPage } from '@intensevisions/content-contract';
2
+ export interface ContentClientOptions {
3
+ siteKey: string;
4
+ baseUrl?: string;
5
+ fetch?: typeof fetch;
6
+ revalidateSeconds?: number;
7
+ /**
8
+ * A preview token (from Studio's Preview, kept by the site while draft mode is on): reads return the latest saved
9
+ * versions, never cached, and image URLs carry the token so unpublished uploads show. Server-side only.
10
+ */
11
+ previewToken?: string;
12
+ }
13
+ export interface ContentImageTransform {
14
+ width?: number;
15
+ height?: number;
16
+ fit?: 'scale-down' | 'contain' | 'cover' | 'crop';
17
+ quality?: number;
18
+ format?: 'auto' | 'webp' | 'avif' | 'jpeg' | 'png';
19
+ }
20
+ /** Reference expansion: `'*'` or field names (dotted for nested), `expandDepth` 1 (default) or 2. */
21
+ export type ContentGetOptions = ContentExpandOptions;
22
+ export interface ContentListOptions extends ContentExpandOptions {
23
+ cursor?: string;
24
+ limit?: number;
25
+ /** Equality on top-level scalar fields of the type, e.g. `{ series: 'tides', featured: true }`. */
26
+ where?: Record<string, ContentWhereValue>;
27
+ /** A top-level scalar field, `-field` for descending. */
28
+ order?: string;
29
+ }
30
+ export interface ContentClient {
31
+ get(type: string, slug: string, options?: ContentGetOptions): Promise<PublishedContentDocument | null>;
32
+ /** One published document by id (any type, or only of `type`), or null. */
33
+ getById(id: string, options?: ContentGetOptions): Promise<PublishedContentDocument | null>;
34
+ getById(type: string, id: string, options?: ContentGetOptions): Promise<PublishedContentDocument | null>;
35
+ /** Published documents by id in the order asked; unpublished or unknown ids are left out. */
36
+ getMany(ids: string[], options?: ContentGetOptions): Promise<PublishedContentDocument[]>;
37
+ list(type: string, options?: ContentListOptions): Promise<PublishedContentDocumentPage>;
38
+ assetUrl(assetId: string, transform?: ContentImageTransform): string;
39
+ }
40
+ export declare function createContentClient(options: ContentClientOptions): ContentClient;
package/dist/index.js ADDED
@@ -0,0 +1,109 @@
1
+ /** The by-ids route's limit; getMany splits longer lists into requests of this size. */
2
+ const IDS_PER_REQUEST = 100;
3
+ export function createContentClient(options) {
4
+ const base = new URL(options.baseUrl ?? 'https://content.intensevisions.com');
5
+ if (base.protocol !== 'https:' && base.hostname !== 'localhost')
6
+ throw new Error('IV Content base URL must use HTTPS.');
7
+ const key = options.siteKey.trim().toLowerCase();
8
+ if (!key || key.length > 253 || /[^a-z0-9.-]/.test(key))
9
+ throw new Error('Invalid IV Content site key.');
10
+ const fetcher = options.fetch ?? fetch;
11
+ const path = `/v1/sites/${encodeURIComponent(key)}`;
12
+ const preview = options.previewToken?.trim() || undefined;
13
+ const request = async (url) => {
14
+ const init = { headers: { Accept: 'application/json' } };
15
+ if (preview) {
16
+ url.searchParams.set('perspective', 'draft');
17
+ init.headers = { Accept: 'application/json', Authorization: `Bearer ${preview}` };
18
+ init.cache = 'no-store';
19
+ }
20
+ else if (Number.isInteger(options.revalidateSeconds) && Number(options.revalidateSeconds) >= 0) {
21
+ init.next = { revalidate: Number(options.revalidateSeconds) };
22
+ }
23
+ const response = await fetcher(url, init);
24
+ if (response.status === 404)
25
+ return null;
26
+ if (!response.ok) {
27
+ // A 400 says what was wrong with the query (an unknown field, a bad cursor): pass that on.
28
+ const body = await response.json().catch(() => null);
29
+ const detail = typeof body?.message === 'string' ? ` ${body.message}` : '';
30
+ throw new Error(`IV Content delivery failed (${response.status}).${detail}`);
31
+ }
32
+ return await response.json();
33
+ };
34
+ const getMany = async (ids, expand = {}) => {
35
+ const unique = [...new Set(ids)];
36
+ const parts = [];
37
+ for (let i = 0; i < unique.length; i += IDS_PER_REQUEST)
38
+ parts.push(unique.slice(i, i + IDS_PER_REQUEST));
39
+ const pages = await Promise.all(parts.map(async (part) => {
40
+ const url = new URL(`${path}/documents`, base);
41
+ url.searchParams.set('ids', part.join(','));
42
+ addExpand(url, expand);
43
+ return (await request(url))?.documents ?? [];
44
+ }));
45
+ return pages.flat();
46
+ };
47
+ async function getById(first, second, third) {
48
+ const [type, id, expand] = typeof second === 'string' ? [first, second, third] : [undefined, first, second];
49
+ const [document] = await getMany([id], expand ?? {});
50
+ return document && (type === undefined || document.type === type) ? document : null;
51
+ }
52
+ return {
53
+ async get(type, slug, expand = {}) {
54
+ const url = new URL(`${path}/${encodeURIComponent(type)}/${encodeURIComponent(slug)}`, base);
55
+ addExpand(url, expand);
56
+ return request(url);
57
+ },
58
+ getById,
59
+ getMany,
60
+ async list(type, options = {}) {
61
+ const url = new URL(`${path}/${encodeURIComponent(type)}`, base);
62
+ if (options.cursor)
63
+ url.searchParams.set('cursor', options.cursor);
64
+ if (options.limit)
65
+ url.searchParams.set('limit', String(options.limit));
66
+ for (const [field, value] of Object.entries(options.where ?? {}))
67
+ url.searchParams.set(`where[${field}]`, String(value));
68
+ if (options.order)
69
+ url.searchParams.set('order', options.order);
70
+ addExpand(url, options);
71
+ return (await request(url)) ?? { documents: [] };
72
+ },
73
+ assetUrl(assetId, transform) {
74
+ const url = new URL(`${path}/assets/${encodeURIComponent(assetId)}`, base);
75
+ if (transform) {
76
+ if (transform.width !== undefined)
77
+ addDimension(url, 'width', transform.width);
78
+ if (transform.height !== undefined)
79
+ addDimension(url, 'height', transform.height);
80
+ if (transform.fit)
81
+ url.searchParams.set('fit', transform.fit);
82
+ if (transform.quality !== undefined) {
83
+ if (!Number.isInteger(transform.quality) || transform.quality < 1 || transform.quality > 100) {
84
+ throw new Error('Image quality must be an integer between 1 and 100.');
85
+ }
86
+ url.searchParams.set('quality', String(transform.quality));
87
+ }
88
+ if (transform.format)
89
+ url.searchParams.set('format', transform.format);
90
+ }
91
+ if (preview)
92
+ url.searchParams.set('preview', preview);
93
+ return url.toString();
94
+ },
95
+ };
96
+ }
97
+ function addDimension(url, name, value) {
98
+ if (!Number.isInteger(value) || value < 1 || value > 4096) {
99
+ throw new Error(`Image ${name} must be an integer between 1 and 4096.`);
100
+ }
101
+ url.searchParams.set(name, String(value));
102
+ }
103
+ function addExpand(url, options) {
104
+ const expand = options.expand === '*' ? '*' : options.expand?.join(',');
105
+ if (expand)
106
+ url.searchParams.set('expand', expand);
107
+ if (expand && options.expandDepth !== undefined)
108
+ url.searchParams.set('expandDepth', String(options.expandDepth));
109
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@intensevisions/content-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Typed, server-safe public delivery client for IV Content.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Intense-Visions/intensevisions.com.git",
9
+ "directory": "packages/content-client"
10
+ },
11
+ "homepage": "https://github.com/Intense-Visions/intensevisions.com/tree/main/packages/content-client#readme",
12
+ "type": "module",
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "sideEffects": false,
27
+ "engines": {
28
+ "node": ">=18.18"
29
+ },
30
+ "dependencies": {
31
+ "@intensevisions/content-contract": "0.1.1"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }