@connie-ai/next-js-blog 0.0.0-stage → 0.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.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Connie contributors
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,235 @@
1
- # Temporary Holding Version
1
+ # Connie blog for Next.js
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
+ `@connie-ai/next-js-blog` provides a server-only client, customizable blog pages,
4
+ and SEO metadata for articles published through Connie.
5
+
6
+ Version `0.1.0` is the first public version prepared for release. Preparing
7
+ an archive does not publish it to npm or deploy the Connie API.
8
+
9
+ ## Supported setup
10
+
11
+ The initial target is Node 22, Next.js 16.4.5 App Router and React 19.2.4, with
12
+ TypeScript and a root `app/layout.tsx` or `src/app/layout.tsx`. Use a running
13
+ Node.js Next server; static export, Cache Components, a Next `basePath`, grouped-only
14
+ root layouts, custom rewrites/proxies and other versions need separate review.
15
+ The CLI conservatively refuses configurations it can identify as unsupported;
16
+ it does not execute or fully interpret a dynamic Next config. Review inherited
17
+ configuration yourself. This package has no Pages Router adapter.
18
+
19
+ The client caches successful API reads for one hour using the Next.js Data Cache.
20
+ The API origin defaults to `https://connie.ai`, with a server-only override for
21
+ a local Connie backend.
22
+
23
+ Once this version is published, install and initialize it in your website:
24
+
25
+ ```sh
26
+ npm install @connie-ai/next-js-blog@0.1.0
27
+ npx --no-install connie-blog init
28
+ ```
29
+
30
+ Before publication, install the reviewed `connie-ai-next-js-blog-0.1.0.tgz`
31
+ archive with `npm install --ignore-scripts /path/to/the/archive.tgz`, then run
32
+ `npx --no-install connie-blog init`. The CLI also supports
33
+ `connie-blog init --cwd <real-project-directory>`.
34
+
35
+ Init creates only `app/blog/**` (or `src/app/blog/**`). It first checks roots,
36
+ layout, route groups, existing App/Pages Router blog contents and symlinks. An exact repeat does
37
+ nothing; a customized/existing blog is refused intact. Files are created
38
+ exclusively. It finishes writes in a private staging directory on the destination
39
+ filesystem, then atomically creates each customer file using an exclusive hard
40
+ link. A disk write failure therefore exposes no partial customer file; the
41
+ filesystem must support hard links. On failure it removes only unchanged files it created. It never
42
+ installs dependencies or writes `.env`, package manifests, Next configuration,
43
+ root sitemaps or robots files. No telemetry or install lifecycle hooks run.
44
+ Treat init as a local developer operation; do not run it while another process
45
+ is replacing the same project's directory tree.
46
+
47
+ Manual alternative: review and copy `node_modules/@connie-ai/next-js-blog/starter/app/blog/`
48
+ into the chosen App Router root **only if no blog exists**; otherwise merge it
49
+ deliberately. JavaScript users must convert the TypeScript annotations themselves
50
+ and validate their consumer build. The CLI refuses JavaScript before writing.
51
+
52
+ ## Server configuration
53
+
54
+ Only the server API key is required:
55
+
56
+ ```dotenv
57
+ CONNIE_BLOG_API_KEY=<your-workspace-blog-read-key>
58
+ ```
59
+
60
+ Optional settings:
61
+
62
+ ```dotenv
63
+ # Preferred public site origin; no /blog path. Otherwise use request headers.
64
+ NEXT_PUBLIC_SITE_URL=https://www.example.com
65
+ # Developer override only. Defaults to https://connie.ai.
66
+ CONNIE_BLOG_API_ORIGIN=http://localhost:3000
67
+ ```
68
+
69
+ The API origin accepts HTTPS, or HTTP for exact lowercase `localhost`,
70
+ `127.0.0.1` or `[::1]`, optionally with a port. No extra local-mode flag is
71
+ needed, including for a locally run production build. Public/private-network
72
+ HTTP and alternative numeric/hex/octal loopback spellings are refused.
73
+ The API origin never comes from request headers or article data. It has no path,
74
+ credentials, query or fragment; `/api/blog/v1` is appended by the client.
75
+ Normal TLS verification and redirect refusal stay enabled. Use the key belonging
76
+ to the selected backend workspace. Never expose it with a `NEXT_PUBLIC_` prefix,
77
+ pass it to Client Components, paste it into a prompt or put it in a URL.
78
+
79
+ The site origin resolves from `NEXT_PUBLIC_SITE_URL` first, then the request's
80
+ `x-forwarded-host` / `host` and protocol, then the request URL where available.
81
+ Only one valid host is accepted; malformed/list headers fail. Public fallback
82
+ origins use HTTPS; exact localhost previews may use HTTP. Your reverse proxy must
83
+ replace forwarded headers with trusted values. Set `NEXT_PUBLIC_SITE_URL` when
84
+ preview domains or host aliases should use one preferred origin. Invalid explicit
85
+ configuration fails rather than silently switching to another domain.
86
+ The API key remains private; the site origin is public metadata.
87
+
88
+ Restart/redeploy the consumer when changing environment settings. Article
89
+ publication, update and unpublish appear through hourly cache revalidation without
90
+ rebuilding. Init never writes environment files. To upgrade an existing customized
91
+ blog, merge the changed starter deliberately; init refuses to overwrite it.
92
+ Remove the old `_connie` route when upgrading. No integration identifier is needed.
93
+
94
+ Review the generated routes, run your production build, and deploy once. API
95
+ reads use Next.js server Data Cache: cache: 'force-cache' with
96
+ next: { revalidate: 3600 }. Successful responses are reused across page views,
97
+ scoped by the complete API URL and Authorization header. Lists, detail pages,
98
+ tags and sitemap enumeration all use this same hourly policy. The response is
99
+ still parsed/validated before rendering. Non-200 upstream errors are not stored
100
+ by the Next.js fetch cache.
101
+
102
+ The starter keeps request-aware rendering and its connection() calls so host
103
+ metadata and unknown slugs are resolved at request time, without prebuilding
104
+ all articles. Its layout uses revalidate = 3600, without force-dynamic or a
105
+ zero-revalidation override. Article metadata and body share one React cache
106
+ read during each render; that read uses the cross-request API cache underneath.
107
+ The sitemap HTTP response stays no-store to avoid sharing one hostname's URLs
108
+ with another; its API inputs are cached for one hour.
109
+
110
+ New publications, updates and unpublishing do not require a rebuild, but a
111
+ cached list/article may remain stale until revalidation. Next.js refreshes stale
112
+ data on demand in the background, so the first request after an hour may still
113
+ receive the older data; an upstream failure can retain it longer. Likewise,
114
+ revoking a key does not purge previously cached public content. Replacing the
115
+ server key changes the cache identity and the new key is checked on its first
116
+ upstream read. For deliberately uncached reads, use
117
+ createBlogClient({ revalidateSeconds: 0 }); the default is 3600. A native Node
118
+ fetch outside Next.js does not implement the Next Data Cache. Development hard
119
+ refreshes may bypass it. No private key is sent to a browser/CDN cache.
120
+
121
+ Credential/environment changes may still require restarting or redeploying your
122
+ hosting environment. Check custom proxies/CDNs do not override cache headers.
123
+
124
+ The client uses its validated server API origin (default `https://connie.ai`),
125
+ the fixed `/api/blog/v1/` path, Bearer authentication and redirect refusal. The
126
+ key/origin are read at client creation; an existing client keeps
127
+ its original key/origin. It makes no automatic retries. A read has an 8-second timeout
128
+ (configurable 1–30,000 ms) and a 32 MiB transport bound. Body representations are
129
+ each limited to 2 MiB by the public schema. Enumeration follows every cursor,
130
+ fails on loops or over 500 pages/30 seconds, and never returns partial success.
131
+ The monotonic enumeration deadline also bounds each in-flight read and is checked
132
+ after final decoding, so a late final response cannot succeed. Public Retry-After
133
+ values contain only delta seconds or a canonical HTTP date, without arbitrary
134
+ upstream comments.
135
+ A local fixture override requires explicit `development: { origin, apiKey }`:
136
+ only HTTP loopback origins and keys beginning `connie_blog_test_` are accepted.
137
+ Explicit `development` options take precedence and are self-contained: their
138
+ key/origin must both be present; the environment key and API origin are not read
139
+ or used in that branch. Missing/malformed fixture values fail;
140
+ they never fall back to environment settings. Normal `cnb_` keys remain refused
141
+ by this override. Use it only for synthetic fixtures; use the server environment
142
+ settings above for a real local backend.
143
+
144
+ Missing configuration, unauthorized key, not-found article, rate limit, invalid
145
+ query, incompatible schema, pagination limit and upstream failure are distinct
146
+ errors. Error messages do not include upstream bodies, credentials or fetch
147
+ causes. Pages show a server-rendered, noindex temporary-error view on known feed failures, with an error boundary for unexpected errors; only a detail 404
148
+ becomes not-found; an invalid list/tag cursor also returns not-found instead of
149
+ claiming a temporary upstream failure. Empty successful feeds show an honest empty state. Sitemap outages return 503. Streaming Next HTML errors can carry HTTP 200
150
+ with error UI, as Next may already have sent headers; do not use HTTP 200 alone
151
+ to verify publication.
152
+
153
+ ## Routes, SEO and images
154
+
155
+ The starter provides `/blog`, `/blog/[slug]`, `/blog/tag/[tag]`,
156
+ `/blog/sitemap.xml`. Static names are
157
+ reserved by public feed validation. Route params are already decoded by Next;
158
+ do not decode them a second time. Lists and tags have cursor navigation; the
159
+ sitemap enumerates all article and tag pages, deduplicates URLs and fails rather
160
+ than truncating at the single-file sitemap limits (50,000 URLs/50 MiB).
161
+
162
+ Add `https://your-site.example/blog/sitemap.xml` to your existing sitemap index
163
+ or the `sitemap` list in your root robots implementation. Keep other sitemap
164
+ entries. Init does not edit either file. There is no blog-specific robots route.
165
+
166
+ Article title, description, canonical, Open Graph and BlogPosting JSON-LD use
167
+ the published snapshot. The article canonical is the API's validated primary
168
+ destination, which can differ from a secondary renderer's actual URL. List/tag
169
+ canonicals use the resolved site origin and base path. Sitemap entries use the
170
+ renderer’s resolved origin and routes, keeping every URL on one host; metadata
171
+ still points a secondary copy to the configured primary destination. Request headers supply the fallback origin when NEXT_PUBLIC_SITE_URL is absent. Configure the same primary destination on the publication
172
+ service; do not independently invent a different canonical in the customer app.
173
+
174
+ The renderer accepts public DTOs only. It revalidates them and reconstructs HTML
175
+ from an explicit HTML5 element/attribute allowlist using
176
+ [parse5](https://parse5.js.org/functions/parse5.parseFragment.html). No scripts,
177
+ styles, event handlers, foreign SVG/MathML, forms, iframes, arbitrary classes/IDs,
178
+ MDX or JSX are executed. JSON-LD escapes `<`, `>`, `&` and line separators.
179
+ Images use native HTTPS `<img>` with validated URLs and no-referrer policy;
180
+ **no wildcard image proxy permission is needed**. To adopt `next/image`, add
181
+ only precise, approved media hosts to your existing config yourself.
182
+ CSS selectors are scoped to `.connie-blog`; no Tailwind or global reset is needed.
183
+
184
+ ## Public exports
185
+
186
+ All entries are ESM, with declarations; React and Next remain peers.
187
+
188
+ | Import | Exports |
189
+ | --- | --- |
190
+ | `@connie-ai/next-js-blog` | Types `BlogTag`, `BlogSummary`, `BlogArticle`, `ArticlePage`, `ArticleDetail`, `TagPage`, `FeedError`; `BlogSchemaError`, `parseArticle`, `parseSummary`, `parseArticlePage`, `parseArticleDetail`, `parseTagPage`, `validateSlug`, `validateHttpsUrl` |
191
+ | `@connie-ai/next-js-blog/server` | `createBlogClient`, `BlogClientError`; types `BlogClient`, `BlogClientOptions`, `BlogClientErrorCode`; guarded by `import 'server-only'` |
192
+ | `@connie-ai/next-js-blog/render` | `BlogList`, `BlogArticleView`, `BlogTagView`, `BlogUnavailable`, `sanitizeBodyHtml` |
193
+ | `@connie-ai/next-js-blog/seo` | `normalizeBasePath`, `blogPath`, `tagPath`, `siteOrigin`, `resolveSiteOrigin`, `articleMetadata`, `collectionMetadata`, `articleJsonLd`, `serializeJsonLd`, `blogSitemap`, `sitemapXml`; type `BlogSitemapEntry` |
194
+ | `@connie-ai/next-js-blog/styles.css` | Scoped stylesheet |
195
+
196
+ `createBlogClient()` offers `listArticles({limit?,cursor?,tag?})`,
197
+ `getArticle(slug)`, `listTags({limit?,cursor?})`, `allArticles(tag?)`, `allTags()`.
198
+ It reads its environment at creation time, so create it inside a request handler.
199
+ Only the `/server` export accesses credentials; `/render` and `/seo` accept supplied
200
+ public data and have no private app, database or Next runtime dependency.
201
+
202
+ ## Check my site
203
+
204
+ In Connie Publishing Settings, save the public HTTPS blog address, deploy your
205
+ site and select **Check my site**. Connie reads the latest published snapshot for
206
+ the current workspace and fetches its actual article URL without forwarding keys
207
+ or cookies. The check compares article identity/revision, visible server-rendered
208
+ content, title, description, canonical, Open Graph and BlogPosting metadata.
209
+ A missing article, stale revision, content/metadata mismatch or unavailable site
210
+ cannot pass merely because a shell returned HTTP 200. Publish an article first
211
+ when the feed is empty. The check neither publishes an article nor verifies DNS
212
+ ownership or search indexing. Local previews remain developer-only: the server
213
+ checker only fetches public HTTPS addresses with DNS pinning.
214
+
215
+ ## Building and packaging
216
+
217
+ From this package directory, run `npm run build` to compile the client and copy
218
+ its stylesheet. `npm pack --dry-run --ignore-scripts` lists the distribution
219
+ files; `npm pack --ignore-scripts` creates the tarball from the built outputs.
220
+ The prepublish hook builds the package and does not run tests.
221
+
222
+ The archive is limited to compiled JavaScript, type declarations, CSS, the CLI,
223
+ starter pages, this README, the MIT license and package metadata. It does not
224
+ include Connie's private application or backend source, credentials, source maps,
225
+ tests, fixtures or local reports. Inspect the final tarball before publishing it.
226
+
227
+ The `latest` tag is the default publication tag. Publishing the npm library does
228
+ not deploy the Connie backend; the configured API must be available separately.
229
+ Changes to package metadata or output require a new archive and checksum.
230
+
231
+ ## License
232
+
233
+ MIT. Copyright (c) 2026 Connie contributors. See [LICENSE.md](./LICENSE.md).
234
+ This license applies to this package; it does not change the license of the
235
+ Connie service or other packages in its repository.
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, mkdtemp, readFile, readdir, lstat, realpath, writeFile, link, unlink, rmdir, rm } from 'node:fs/promises';
3
+ import { resolve, dirname, join, relative } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { createHash } from 'node:crypto';
6
+ import { createRequire } from 'node:module';
7
+
8
+ const starter = fileURLToPath(new URL('../starter/app/blog/', import.meta.url));
9
+ const markerName = '.connie-blog-init.json';
10
+ const { version: templateVersion, peerDependencies } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
11
+ class InitError extends Error {}
12
+ async function exists(path) { try { return await lstat(path); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } }
13
+ async function noSymlinks(path) {
14
+ for (let part = resolve(path); ; part = dirname(part)) {
15
+ const stat = await exists(part);
16
+ if (stat?.isSymbolicLink()) throw new InitError('Refusing a symlink destination. Use a real project directory.');
17
+ if (part === dirname(part)) break;
18
+ }
19
+ }
20
+ async function filesIn(directory, prefix = '') {
21
+ const files = new Map();
22
+ for (const item of await readdir(directory, { withFileTypes: true })) {
23
+ const path = join(directory, item.name), name = prefix + item.name;
24
+ if (item.isSymbolicLink()) throw new InitError('Refusing a symlink in the blog directory.');
25
+ if (item.isDirectory()) for (const [k, v] of await filesIn(path, name + '/')) files.set(k, v);
26
+ else if (item.isFile()) files.set(name, await readFile(path));
27
+ else throw new InitError('Refusing a special file in the blog directory.');
28
+ }
29
+ return files;
30
+ }
31
+ async function checkCollisions(app, grouped = false) {
32
+ for (const entry of await readdir(app, { withFileTypes: true })) {
33
+ if (grouped && entry.name === 'blog') throw new InitError('An existing grouped blog route conflicts with /blog. No files were written.');
34
+ if (/^\[/.test(entry.name)) throw new InitError('A dynamic root route needs manual review before adding /blog. No files were written.');
35
+ if (/^\(.*\)$/.test(entry.name) || entry.name.startsWith('@')) {
36
+ if (!entry.isDirectory() || entry.isSymbolicLink()) throw new InitError('Ambiguous route group. No files were written.');
37
+ await checkCollisions(join(app, entry.name), true);
38
+ }
39
+ }
40
+ }
41
+ export async function init(projectDirectory) {
42
+ const root = resolve(projectDirectory);
43
+ await noSymlinks(root);
44
+ if (await realpath(root) !== root) throw new InitError('Use the real project path.');
45
+ await noSymlinks(join(root, 'package.json'));
46
+ const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
47
+ if (!pkg.dependencies?.next && !pkg.devDependencies?.next) throw new InitError('No Next.js dependency found in this project.');
48
+ try {
49
+ const requireFromProject = createRequire(join(root, 'package.json'));
50
+ const next = JSON.parse(await readFile(requireFromProject.resolve('next/package.json'), 'utf8'));
51
+ const react = JSON.parse(await readFile(requireFromProject.resolve('react/package.json'), 'utf8'));
52
+ if (next.version !== peerDependencies.next || react.version !== peerDependencies.react) throw new InitError(`This package supports Next.js ${peerDependencies.next} and React ${peerDependencies.react}. No files were written.`);
53
+ } catch (error) {
54
+ if (error instanceof InitError) throw error;
55
+ throw new InitError('Install the supported Next.js and React peers before init. No files were written.');
56
+ }
57
+ const tsconfig = join(root, 'tsconfig.json');
58
+ await noSymlinks(tsconfig);
59
+ if (!(await exists(tsconfig))?.isFile()) throw new InitError('This init supports TypeScript App Router projects only. No files were written. Use the manual starter for JavaScript conversion.');
60
+ const roots = [];
61
+ for (const candidate of [join(root, 'app'), join(root, 'src/app')]) {
62
+ await noSymlinks(candidate);
63
+ const stat = await exists(candidate);
64
+ if (stat && !stat.isDirectory()) throw new InitError('The App Router root must be a directory.');
65
+ if (stat) roots.push(candidate);
66
+ }
67
+ if (roots.length !== 1) throw new InitError('Expected exactly one app or src/app root. No files were written.');
68
+ const app = roots[0];
69
+ await noSymlinks(join(app, 'layout.tsx'));
70
+ if (!(await exists(join(app, 'layout.tsx')))?.isFile()) throw new InitError('Expected a TypeScript root layout.tsx. Grouped-only root layouts require manual integration.');
71
+ for (const name of ['next.config.js', 'next.config.mjs', 'next.config.ts', 'next.config.cjs']) {
72
+ const path = join(root, name);
73
+ await noSymlinks(path);
74
+ if (await exists(path)) {
75
+ const text = await readFile(path, 'utf8');
76
+ if (/\bcacheComponents\b|\bbasePath\s*:|\boutput\s*:\s*['"]export['"]/.test(text)) throw new InitError('Cache Components, Next basePath and static export configurations require manual review. No files were written.');
77
+ }
78
+ }
79
+ await checkCollisions(app);
80
+ for (const pages of [join(root, 'pages'), join(root, 'src/pages')]) {
81
+ await noSymlinks(pages);
82
+ if (!(await exists(pages))) continue;
83
+ for (const entry of await readdir(pages)) {
84
+ if (entry === 'blog' || /^blog\./.test(entry)) throw new InitError('An existing Pages Router blog conflicts with /blog. No files were written.');
85
+ }
86
+ }
87
+ const destination = join(app, 'blog');
88
+ await noSymlinks(destination);
89
+ if (relative(root, destination).startsWith('..')) throw new InitError('Destination escapes the project.');
90
+ const files = await filesIn(starter);
91
+ const hashes = Object.fromEntries([...files].sort(([a], [b]) => a.localeCompare(b)).map(([name, bytes]) => [name, createHash('sha256').update(bytes).digest('hex')]));
92
+ files.set(markerName, Buffer.from(JSON.stringify({ schemaVersion: 1, template: templateVersion, files: hashes }, null, 2) + '\n'));
93
+ if (await exists(destination)) {
94
+ const existing = await filesIn(destination);
95
+ if (existing.size === files.size && [...files].every(([name, bytes]) => existing.get(name)?.equals(bytes))) return { status: 'unchanged', destination };
96
+ throw new InitError('Existing /blog files differ from this starter. Nothing was changed. Merge the manual starter yourself.');
97
+ }
98
+ // Exclusive mkdir/write prevent races from overwriting another process's files.
99
+ const createdFiles = [], createdDirectories = [];
100
+ // Finish writes privately on this filesystem before exposing any customer file.
101
+ // A failed writeFile can leave a partially written file even with flag wx.
102
+ const stage = await mkdtemp(join(app, '.connie-blog-stage-'));
103
+ try {
104
+ const staged = new Map();
105
+ for (const [name, bytes] of files) {
106
+ const path = join(stage, String(staged.size));
107
+ await writeFile(path, bytes, { flag: 'wx' });
108
+ staged.set(name, path);
109
+ }
110
+ await mkdir(destination); createdDirectories.push(destination);
111
+ for (const [name, bytes] of files) {
112
+ const path = join(destination, name), parents = [];
113
+ for (let p = dirname(path); p !== destination; p = dirname(p)) parents.unshift(p);
114
+ for (const parent of parents) {
115
+ await noSymlinks(parent);
116
+ if (!(await exists(parent))) { await mkdir(parent); createdDirectories.push(parent); }
117
+ }
118
+ await noSymlinks(path);
119
+ // link is exclusive and atomic: the destination is either absent or complete.
120
+ await link(staged.get(name), path); createdFiles.push([path, bytes]);
121
+ }
122
+ } catch (error) {
123
+ // Remove only unchanged files created by this invocation; leave concurrent edits.
124
+ for (const [path, bytes] of createdFiles.reverse()) {
125
+ try { await noSymlinks(path); if ((await readFile(path)).equals(bytes)) await unlink(path); } catch { /* preserve anything we cannot establish is ours */ }
126
+ }
127
+ for (const path of createdDirectories.reverse()) { try { await rmdir(path); } catch { /* preserve nonempty directories */ } }
128
+ throw error;
129
+ } finally { await rm(stage, { recursive: true, force: true }); }
130
+ return { status: 'created', destination };
131
+ }
132
+ async function main() {
133
+ const [command, ...args] = process.argv.slice(2);
134
+ if (command === '--help' || command === '-h') { console.log(`connie-blog init [--cwd <project>]\nNode.js 22+, Next.js ${peerDependencies.next} App Router and TypeScript; no installs, environment edits or overwrites.`); return; }
135
+ if (command !== 'init' || (args.length && !(args.length === 2 && args[0] === '--cwd'))) throw new InitError('Usage: connie-blog init [--cwd <project>]');
136
+ const result = await init(args[1] ?? process.cwd());
137
+ console.log(`Connie blog ${result.status}: ${result.destination}\nSet CONNIE_BLOG_API_KEY in your server environment and hosting settings (never NEXT_PUBLIC_).\nCONNIE_BLOG_API_ORIGIN optionally selects the server API (default https://connie.ai).\nFor a local backend only, set it to http://localhost:3000, using a key created in that local backend.\nOptionally set NEXT_PUBLIC_SITE_URL to your preferred public site origin; otherwise request headers determine the site origin.\nRestart the consumer server after changing environment settings; article data refreshes hourly without rebuilding.\nAdd /blog/sitemap.xml to your existing sitemap/robots configuration manually.\nNo credentials were collected; no environment or Next configuration was changed.`);
138
+ }
139
+ const entrypoint = process.argv[1] ? await realpath(resolve(process.argv[1])).catch(() => undefined) : undefined;
140
+ if (entrypoint === fileURLToPath(import.meta.url)) main().catch(error => { console.error(error instanceof InitError ? error.message : 'Connie blog init failed. Check project permissions and layout; existing files were preserved.'); process.exitCode = 1; });
@@ -0,0 +1,33 @@
1
+ import type { ArticlePage, BlogArticle, BlogSummary, TagPage } from './types.js';
2
+ export type BlogClientErrorCode = 'MISSING_CONFIGURATION' | 'INVALID_CONFIGURATION' | 'UNAUTHORIZED' | 'NOT_FOUND' | 'RATE_LIMITED' | 'UPSTREAM_UNAVAILABLE' | 'INVALID_QUERY' | 'PAGINATION_LIMIT';
3
+ export declare class BlogClientError extends Error {
4
+ readonly code: BlogClientErrorCode;
5
+ readonly status?: number | undefined;
6
+ readonly retryAfter?: string | undefined;
7
+ constructor(code: BlogClientErrorCode, status?: number | undefined, retryAfter?: string | undefined);
8
+ }
9
+ export type BlogClientOptions = {
10
+ timeoutMs?: number;
11
+ /** Next.js server Data Cache lifetime. Defaults to one hour; 0 opts out. */
12
+ revalidateSeconds?: number;
13
+ /** Local fixture only. The environment key is never sent to this override. */
14
+ development?: {
15
+ origin: string;
16
+ apiKey: string;
17
+ };
18
+ };
19
+ export type BlogClient = ReturnType<typeof createBlogClient>;
20
+ export declare function createBlogClient(options?: BlogClientOptions): {
21
+ listArticles: (input?: {
22
+ limit?: number;
23
+ cursor?: string;
24
+ tag?: string;
25
+ }) => Promise<ArticlePage>;
26
+ getArticle: (slug: string) => Promise<BlogArticle>;
27
+ listTags: (input?: {
28
+ limit?: number;
29
+ cursor?: string;
30
+ }) => Promise<TagPage>;
31
+ allArticles: (tag?: string) => Promise<BlogSummary[]>;
32
+ allTags: () => Promise<TagPage["items"]>;
33
+ };
package/dist/client.js ADDED
@@ -0,0 +1,183 @@
1
+ import { BlogSchemaError, parseArticleDetail, parseArticlePage, parseTagPage, validateSlug } from './validation.js';
2
+ export class BlogClientError extends Error {
3
+ code;
4
+ status;
5
+ retryAfter;
6
+ constructor(code, status, retryAfter) {
7
+ super(({ MISSING_CONFIGURATION: 'Set CONNIE_BLOG_API_KEY in the server environment.', INVALID_CONFIGURATION: 'Invalid blog client configuration.', UNAUTHORIZED: 'The blog key was refused. Check the server environment.', NOT_FOUND: 'This article is not published.', RATE_LIMITED: 'The blog feed is temporarily rate limited.', UPSTREAM_UNAVAILABLE: 'The blog feed is temporarily unavailable.', INVALID_QUERY: 'Invalid blog query.', PAGINATION_LIMIT: 'The blog feed could not be completely enumerated within its limits.' })[code]);
8
+ this.code = code;
9
+ this.status = status;
10
+ this.retryAfter = retryAfter;
11
+ this.name = 'BlogClientError';
12
+ }
13
+ }
14
+ function query(input) {
15
+ const params = new URLSearchParams();
16
+ if (input.limit !== undefined) {
17
+ if (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 100)
18
+ throw new BlogClientError('INVALID_QUERY');
19
+ params.set('limit', String(input.limit));
20
+ }
21
+ if (input.cursor !== undefined) {
22
+ if (typeof input.cursor !== 'string' || !input.cursor.length || input.cursor.length > 8192)
23
+ throw new BlogClientError('INVALID_QUERY');
24
+ params.set('cursor', input.cursor);
25
+ }
26
+ if (input.tag !== undefined)
27
+ params.set('tag', validateSlug(input.tag));
28
+ return params.toString();
29
+ }
30
+ function apiOrigin(value, fixtureOnly = false) {
31
+ // Validate the literal authority/path before WHATWG normalization can turn
32
+ // 127.1, hexadecimal/octal hosts, dot segments or backslashes into valid URLs.
33
+ if (typeof value !== 'string' || value.length > 2048 || /[\u0000-\u0020\u007f\\]/.test(value) || value.trim() !== value)
34
+ throw new BlogClientError('INVALID_CONFIGURATION');
35
+ const origin = /^([a-z][a-z0-9+.-]*):\/\/([^/?#]+)\/?$/i.exec(value);
36
+ if (!origin || origin[2].includes('@'))
37
+ throw new BlogClientError('INVALID_CONFIGURATION');
38
+ let url;
39
+ try {
40
+ url = new URL(value);
41
+ }
42
+ catch {
43
+ throw new BlogClientError('INVALID_CONFIGURATION');
44
+ }
45
+ if (url.username || url.password || url.pathname !== '/' || url.search || url.hash)
46
+ throw new BlogClientError('INVALID_CONFIGURATION');
47
+ if (url.protocol === 'https:' && !fixtureOnly)
48
+ return url.origin;
49
+ if (url.protocol === 'http:' && /^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/.test(origin[2]))
50
+ return url.origin;
51
+ throw new BlogClientError('INVALID_CONFIGURATION');
52
+ }
53
+ export function createBlogClient(options = {}) {
54
+ const fixture = options.development;
55
+ const fixtureConfigured = fixture !== undefined;
56
+ if (fixtureConfigured && (!fixture || typeof fixture !== 'object'))
57
+ throw new BlogClientError('INVALID_CONFIGURATION');
58
+ // The explicit fixture is self-contained: do not read environment credentials,
59
+ // origins or local-mode flags in this branch, even when its options are invalid.
60
+ const apiKey = fixtureConfigured ? fixture.apiKey : process.env.CONNIE_BLOG_API_KEY;
61
+ if (!apiKey)
62
+ throw new BlogClientError(fixtureConfigured ? 'INVALID_CONFIGURATION' : 'MISSING_CONFIGURATION');
63
+ if (typeof apiKey !== 'string' || !/^[A-Za-z0-9_\-.]{8,512}$/.test(apiKey))
64
+ throw new BlogClientError('INVALID_CONFIGURATION');
65
+ if (fixtureConfigured && !apiKey.startsWith('connie_blog_test_'))
66
+ throw new BlogClientError('INVALID_CONFIGURATION');
67
+ const origin = fixtureConfigured ? apiOrigin(fixture.origin, true)
68
+ : apiOrigin(process.env.CONNIE_BLOG_API_ORIGIN ?? 'https://connie.ai');
69
+ const timeoutMs = options.timeoutMs ?? 8000;
70
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000)
71
+ throw new BlogClientError('INVALID_CONFIGURATION');
72
+ const revalidateSeconds = options.revalidateSeconds ?? 3600;
73
+ if (!Number.isSafeInteger(revalidateSeconds) || revalidateSeconds < 0)
74
+ throw new BlogClientError('INVALID_CONFIGURATION');
75
+ // Next's server fetch cache includes the full URL and Authorization header in
76
+ // its cache key. Never share article data across API origins or credentials.
77
+ const cacheOptions = revalidateSeconds === 0
78
+ ? { cache: 'no-store' }
79
+ : { cache: 'force-cache', next: { revalidate: revalidateSeconds } };
80
+ async function read(path, parse, deadline = Infinity) {
81
+ const remaining = deadline - performance.now();
82
+ if (remaining <= 0)
83
+ throw new BlogClientError('PAGINATION_LIMIT');
84
+ const controller = new AbortController();
85
+ const timer = setTimeout(() => controller.abort(), Math.min(timeoutMs, remaining));
86
+ try {
87
+ const response = await fetch(`${origin}/api/blog/v1/${path}`, {
88
+ ...cacheOptions,
89
+ method: 'GET', headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
90
+ redirect: 'error', signal: controller.signal,
91
+ });
92
+ if (!response.ok) {
93
+ // Never include upstream response text, URL, headers or thrown fetch causes.
94
+ await response.body?.cancel();
95
+ const retry = response.headers.get('retry-after');
96
+ // Date.parse accepts arbitrary comments; only expose an actual HTTP date.
97
+ const retryAfter = retry && (/^\d{1,6}$/.test(retry) || (retry.length === 29 && Number.isFinite(Date.parse(retry)) && new Date(retry).toUTCString() === retry)) ? retry : undefined;
98
+ const code = response.status === 401 || response.status === 403 ? 'UNAUTHORIZED' : response.status === 404 ? 'NOT_FOUND' : response.status === 429 ? 'RATE_LIMITED' : response.status === 400 ? 'INVALID_QUERY' : 'UPSTREAM_UNAVAILABLE';
99
+ throw new BlogClientError(code, response.status, retryAfter);
100
+ }
101
+ if (!/^application\/json(?:;|$)/i.test(response.headers.get('content-type') ?? '')) {
102
+ await response.body?.cancel();
103
+ throw new BlogSchemaError();
104
+ }
105
+ const reader = response.body?.getReader();
106
+ if (!reader)
107
+ throw new BlogSchemaError();
108
+ const chunks = [];
109
+ let size = 0;
110
+ try {
111
+ while (true) {
112
+ const chunk = await reader.read();
113
+ if (chunk.done)
114
+ break;
115
+ size += chunk.value.byteLength;
116
+ if (size > 32 * 1024 * 1024) {
117
+ await reader.cancel();
118
+ throw new BlogSchemaError();
119
+ }
120
+ chunks.push(chunk.value);
121
+ }
122
+ }
123
+ finally {
124
+ reader.releaseLock();
125
+ }
126
+ let json;
127
+ try {
128
+ json = JSON.parse(Buffer.concat(chunks).toString('utf8'));
129
+ }
130
+ catch {
131
+ throw new BlogSchemaError();
132
+ }
133
+ const result = parse(json);
134
+ if (performance.now() >= deadline)
135
+ throw new BlogClientError('PAGINATION_LIMIT');
136
+ return result;
137
+ }
138
+ catch (error) {
139
+ if (error instanceof BlogClientError || error instanceof BlogSchemaError)
140
+ throw error;
141
+ if (performance.now() >= deadline)
142
+ throw new BlogClientError('PAGINATION_LIMIT');
143
+ throw new BlogClientError('UPSTREAM_UNAVAILABLE');
144
+ }
145
+ finally {
146
+ clearTimeout(timer);
147
+ }
148
+ }
149
+ async function listArticles(input = {}) {
150
+ return read(`articles?${query(input)}`, parseArticlePage);
151
+ }
152
+ async function getArticle(slug) {
153
+ const article = (await read(`articles/${validateSlug(slug, true)}`, parseArticleDetail)).article;
154
+ if (article.slug !== slug)
155
+ throw new BlogSchemaError();
156
+ return article;
157
+ }
158
+ async function listTags(input = {}) { return read(`tags?${query(input)}`, parseTagPage); }
159
+ async function collect(page) {
160
+ const values = [], seen = new Set(), deadline = performance.now() + 30000;
161
+ let cursor;
162
+ for (let i = 0; i < 500; i++) {
163
+ if (performance.now() >= deadline)
164
+ break;
165
+ const result = await page(cursor, deadline);
166
+ if (performance.now() >= deadline)
167
+ break;
168
+ values.push(...result.items);
169
+ if (result.nextCursor === null)
170
+ return values;
171
+ if (seen.has(result.nextCursor))
172
+ break;
173
+ seen.add(result.nextCursor);
174
+ cursor = result.nextCursor;
175
+ }
176
+ throw new BlogClientError('PAGINATION_LIMIT');
177
+ }
178
+ return {
179
+ listArticles, getArticle, listTags,
180
+ allArticles: (tag) => collect((cursor, deadline) => read(`articles?${query({ cursor, tag, limit: 100 })}`, parseArticlePage, deadline)),
181
+ allTags: () => collect((cursor, deadline) => read(`tags?${query({ cursor, limit: 100 })}`, parseTagPage, deadline)),
182
+ };
183
+ }
@@ -0,0 +1,2 @@
1
+ export type * from './types.js';
2
+ export { BlogSchemaError, parseArticle, parseSummary, parseArticlePage, parseArticleDetail, parseTagPage, validateSlug, validateHttpsUrl } from './validation.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { BlogSchemaError, parseArticle, parseSummary, parseArticlePage, parseArticleDetail, parseTagPage, validateSlug, validateHttpsUrl } from './validation.js';
@@ -0,0 +1,20 @@
1
+ import * as React from 'react';
2
+ import type { BlogArticle, BlogSummary, BlogTag } from './types.js';
3
+ export { sanitizeBodyHtml } from './sanitize.js';
4
+ export declare function BlogUnavailable(): React.JSX.Element;
5
+ export declare function BlogList({ articles, basePath, title, nextHref }: {
6
+ articles: BlogSummary[];
7
+ basePath?: string;
8
+ title?: string;
9
+ nextHref?: string;
10
+ }): React.JSX.Element;
11
+ export declare function BlogTagView({ tag, articles, basePath, nextHref }: {
12
+ tag: BlogTag;
13
+ articles: BlogSummary[];
14
+ basePath?: string;
15
+ nextHref?: string;
16
+ }): React.JSX.Element;
17
+ export declare function BlogArticleView({ article: value, basePath }: {
18
+ article: BlogArticle;
19
+ basePath?: string;
20
+ }): React.JSX.Element;