@kiriti/comments-server 0.1.0 → 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/README.md +26 -0
- package/dist/index.cjs +72 -0
- package/dist/index.d.cts +29 -1
- package/dist/index.d.ts +29 -1
- package/dist/index.js +71 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -45,6 +45,32 @@ If the widget runs on a site not in `allowedOrigins`, it shows a notice instead
|
|
|
45
45
|
|
|
46
46
|
Add CORS for the sites that show the widget if the API is on another origin.
|
|
47
47
|
|
|
48
|
+
### Serverless / no Express app: `createCommentsHandler`
|
|
49
|
+
|
|
50
|
+
A drop-in Node handler (Vercel functions, Next.js API routes, `http.createServer`). It starts on the first request,
|
|
51
|
+
reuses the MongoDB connection while warm, and copes with platforms that pre-parse the body.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
// api/comments/[...path].ts (Vercel) — or pages/api/comments/[...path].ts (Next.js)
|
|
55
|
+
import { createCommentsHandler } from "@kiriti/comments-server";
|
|
56
|
+
export default createCommentsHandler({ rateLimit: { store: "mongo" } }); // settings from COMMENTS_* env vars
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Out of function slots? Point a rewrite at an existing function and let it delegate:
|
|
60
|
+
|
|
61
|
+
```jsonc
|
|
62
|
+
// vercel.json
|
|
63
|
+
{ "source": "/api/comments/:path*", "destination": "/api/existing?action=comments&path=:path*" }
|
|
64
|
+
```
|
|
65
|
+
```ts
|
|
66
|
+
// inside api/existing.ts
|
|
67
|
+
const comments = createCommentsHandler({ stripParams: ["action"] });
|
|
68
|
+
if (req.query.action === "comments") return comments(req, res);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Options: everything `createCommentsRouter` takes, plus `basePath` (default `/api/comments`), `pathParam`
|
|
72
|
+
(default `path`) and `stripParams`.
|
|
73
|
+
|
|
48
74
|
## Options
|
|
49
75
|
|
|
50
76
|
| Option | Default | |
|
package/dist/index.cjs
CHANGED
|
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var index_exports = {};
|
|
32
32
|
__export(index_exports, {
|
|
33
33
|
CommentsError: () => CommentsError,
|
|
34
|
+
createCommentsHandler: () => createCommentsHandler,
|
|
34
35
|
createCommentsRouter: () => createCommentsRouter,
|
|
35
36
|
createCommentsService: () => createCommentsService,
|
|
36
37
|
createMemoryRateLimitStore: () => createMemoryRateLimitStore,
|
|
@@ -681,9 +682,80 @@ var createCommentsRouter = async (options) => {
|
|
|
681
682
|
router.close = store.close;
|
|
682
683
|
return router;
|
|
683
684
|
};
|
|
685
|
+
|
|
686
|
+
// src/handler.ts
|
|
687
|
+
var import_express2 = __toESM(require("express"), 1);
|
|
688
|
+
var SUB_PATH = /^[a-z0-9/_-]{0,200}$/i;
|
|
689
|
+
var sendJson = (res, status, body) => {
|
|
690
|
+
if (res.writableEnded) return;
|
|
691
|
+
res.statusCode = status;
|
|
692
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
693
|
+
res.end(JSON.stringify(body));
|
|
694
|
+
};
|
|
695
|
+
var subPath = (rawUrl, basePath, pathParam, strip) => {
|
|
696
|
+
const url = new URL(rawUrl, "http://localhost");
|
|
697
|
+
let path = null;
|
|
698
|
+
if (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`)) path = url.pathname.slice(basePath.length);
|
|
699
|
+
else if (url.searchParams.has(pathParam)) path = url.searchParams.get(pathParam) ?? "";
|
|
700
|
+
if (path === null) return null;
|
|
701
|
+
for (const key of [pathParam, ...strip]) url.searchParams.delete(key);
|
|
702
|
+
const query = url.searchParams.toString();
|
|
703
|
+
return `${path.replace(/^\/+/, "")}${query ? `?${query}` : ""}`;
|
|
704
|
+
};
|
|
705
|
+
var createCommentsHandler = (options = {}) => {
|
|
706
|
+
const { basePath = "/api/comments", pathParam = "path", stripParams = [], ...routerOptions } = options;
|
|
707
|
+
const base = basePath.replace(/\/+$/, "");
|
|
708
|
+
let starting = null;
|
|
709
|
+
const start = () => {
|
|
710
|
+
starting ??= createCommentsRouter(routerOptions).then((router) => {
|
|
711
|
+
const app = (0, import_express2.default)();
|
|
712
|
+
app.disable("x-powered-by");
|
|
713
|
+
app.set("trust proxy", true);
|
|
714
|
+
app.use(base, router);
|
|
715
|
+
return { app, router };
|
|
716
|
+
}).catch((error) => {
|
|
717
|
+
starting = null;
|
|
718
|
+
throw error;
|
|
719
|
+
});
|
|
720
|
+
return starting;
|
|
721
|
+
};
|
|
722
|
+
const handler = async (req, res) => {
|
|
723
|
+
const path = subPath(req.url ?? "/", base, pathParam, stripParams);
|
|
724
|
+
if (path === null || !SUB_PATH.test(path.split("?")[0] ?? "")) return sendJson(res, 404, { error: "Not found.", code: "not_found" });
|
|
725
|
+
let app;
|
|
726
|
+
try {
|
|
727
|
+
({ app } = await start());
|
|
728
|
+
} catch (error) {
|
|
729
|
+
console.error("[comments-server] failed to start:", error instanceof Error ? error.message : error);
|
|
730
|
+
return sendJson(res, 503, { error: "Comments are temporarily unavailable.", code: "unavailable" });
|
|
731
|
+
}
|
|
732
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
733
|
+
try {
|
|
734
|
+
void req.body;
|
|
735
|
+
} catch {
|
|
736
|
+
return sendJson(res, 400, { error: "Invalid JSON body.", code: "invalid_json" });
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
req.url = `${base}/${path}`;
|
|
740
|
+
await new Promise((resolve) => {
|
|
741
|
+
res.once("finish", resolve);
|
|
742
|
+
res.once("close", resolve);
|
|
743
|
+
app(req, res);
|
|
744
|
+
});
|
|
745
|
+
};
|
|
746
|
+
return Object.assign(handler, {
|
|
747
|
+
close: async () => {
|
|
748
|
+
if (!starting) return;
|
|
749
|
+
const { router } = await starting.catch(() => ({ router: null }));
|
|
750
|
+
await router?.close();
|
|
751
|
+
starting = null;
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
};
|
|
684
755
|
// Annotate the CommonJS export names for ESM import in node:
|
|
685
756
|
0 && (module.exports = {
|
|
686
757
|
CommentsError,
|
|
758
|
+
createCommentsHandler,
|
|
687
759
|
createCommentsRouter,
|
|
688
760
|
createCommentsService,
|
|
689
761
|
createMemoryRateLimitStore,
|
package/dist/index.d.cts
CHANGED
|
@@ -2,6 +2,7 @@ import { Router } from 'express';
|
|
|
2
2
|
import { Db, MongoClient, ObjectId, Collection } from 'mongodb';
|
|
3
3
|
import { ThreadingConfig, CommentSort, ThreadsPage, SessionUser, CommentDTO, ModerationStatus, ModerationPage, ModerationAction } from '@kiriti/comments-core';
|
|
4
4
|
export * from '@kiriti/comments-core';
|
|
5
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
6
|
|
|
6
7
|
interface RateLimitRule {
|
|
7
8
|
/** Allowed requests per window. */
|
|
@@ -129,6 +130,33 @@ interface CommentsRouter extends Router {
|
|
|
129
130
|
*/
|
|
130
131
|
declare const createCommentsRouter: (options: CommentsServerOptions) => Promise<CommentsRouter>;
|
|
131
132
|
|
|
133
|
+
interface CommentsHandlerOptions extends CommentsServerOptions {
|
|
134
|
+
/** Public URL prefix of the API, e.g. "/api/comments" (the widget's `apiBaseUrl`). Default "/api/comments". */
|
|
135
|
+
basePath?: string;
|
|
136
|
+
/**
|
|
137
|
+
* Query parameter holding the API sub-path when a rewrite sends every request to one function, e.g.
|
|
138
|
+
* `/api/comments/:path*` → `/api/some-function?path=:path*`. Default "path".
|
|
139
|
+
*/
|
|
140
|
+
pathParam?: string;
|
|
141
|
+
/** Other query parameters added by your rewrite that the API should not see (e.g. ["action"]). */
|
|
142
|
+
stripParams?: string[];
|
|
143
|
+
}
|
|
144
|
+
type NodeHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
145
|
+
/**
|
|
146
|
+
* A ready-to-mount Node request handler for the whole comments API — Vercel functions, Next.js API routes
|
|
147
|
+
* (`export const config = { api: { bodyParser: false } }` optional), or plain `http.createServer`.
|
|
148
|
+
*
|
|
149
|
+
* // api/comments/[...path].ts on Vercel, or behind a rewrite to one shared function:
|
|
150
|
+
* const handler = createCommentsHandler({}); // settings from COMMENTS_* env vars
|
|
151
|
+
* export default handler;
|
|
152
|
+
*
|
|
153
|
+
* The router (and MongoDB connection) starts on the first request and is reused while the instance stays warm;
|
|
154
|
+
* if startup fails (e.g. missing settings) requests get a 503 and the next one retries.
|
|
155
|
+
*/
|
|
156
|
+
declare const createCommentsHandler: (options?: CommentsHandlerOptions) => NodeHandler & {
|
|
157
|
+
close: () => Promise<void>;
|
|
158
|
+
};
|
|
159
|
+
|
|
132
160
|
interface CommentDoc {
|
|
133
161
|
_id: ObjectId;
|
|
134
162
|
slug: string;
|
|
@@ -215,4 +243,4 @@ declare class CommentsError extends Error {
|
|
|
215
243
|
retryAfter?: number | undefined);
|
|
216
244
|
}
|
|
217
245
|
|
|
218
|
-
export { type CommentDoc, CommentsError, type CommentsRouter, type CommentsServerOptions, type CommentsService, type GoogleIdentity, type RateLimitOptions, type RateLimitRule, type RateLimitStore, type Store, type UserDoc, createCommentsRouter, createCommentsService, createMemoryRateLimitStore, createMongoRateLimitStore, openStore, resolveOptions };
|
|
246
|
+
export { type CommentDoc, CommentsError, type CommentsHandlerOptions, type CommentsRouter, type CommentsServerOptions, type CommentsService, type GoogleIdentity, type RateLimitOptions, type RateLimitRule, type RateLimitStore, type Store, type UserDoc, createCommentsHandler, createCommentsRouter, createCommentsService, createMemoryRateLimitStore, createMongoRateLimitStore, openStore, resolveOptions };
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { Router } from 'express';
|
|
|
2
2
|
import { Db, MongoClient, ObjectId, Collection } from 'mongodb';
|
|
3
3
|
import { ThreadingConfig, CommentSort, ThreadsPage, SessionUser, CommentDTO, ModerationStatus, ModerationPage, ModerationAction } from '@kiriti/comments-core';
|
|
4
4
|
export * from '@kiriti/comments-core';
|
|
5
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
6
|
|
|
6
7
|
interface RateLimitRule {
|
|
7
8
|
/** Allowed requests per window. */
|
|
@@ -129,6 +130,33 @@ interface CommentsRouter extends Router {
|
|
|
129
130
|
*/
|
|
130
131
|
declare const createCommentsRouter: (options: CommentsServerOptions) => Promise<CommentsRouter>;
|
|
131
132
|
|
|
133
|
+
interface CommentsHandlerOptions extends CommentsServerOptions {
|
|
134
|
+
/** Public URL prefix of the API, e.g. "/api/comments" (the widget's `apiBaseUrl`). Default "/api/comments". */
|
|
135
|
+
basePath?: string;
|
|
136
|
+
/**
|
|
137
|
+
* Query parameter holding the API sub-path when a rewrite sends every request to one function, e.g.
|
|
138
|
+
* `/api/comments/:path*` → `/api/some-function?path=:path*`. Default "path".
|
|
139
|
+
*/
|
|
140
|
+
pathParam?: string;
|
|
141
|
+
/** Other query parameters added by your rewrite that the API should not see (e.g. ["action"]). */
|
|
142
|
+
stripParams?: string[];
|
|
143
|
+
}
|
|
144
|
+
type NodeHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
145
|
+
/**
|
|
146
|
+
* A ready-to-mount Node request handler for the whole comments API — Vercel functions, Next.js API routes
|
|
147
|
+
* (`export const config = { api: { bodyParser: false } }` optional), or plain `http.createServer`.
|
|
148
|
+
*
|
|
149
|
+
* // api/comments/[...path].ts on Vercel, or behind a rewrite to one shared function:
|
|
150
|
+
* const handler = createCommentsHandler({}); // settings from COMMENTS_* env vars
|
|
151
|
+
* export default handler;
|
|
152
|
+
*
|
|
153
|
+
* The router (and MongoDB connection) starts on the first request and is reused while the instance stays warm;
|
|
154
|
+
* if startup fails (e.g. missing settings) requests get a 503 and the next one retries.
|
|
155
|
+
*/
|
|
156
|
+
declare const createCommentsHandler: (options?: CommentsHandlerOptions) => NodeHandler & {
|
|
157
|
+
close: () => Promise<void>;
|
|
158
|
+
};
|
|
159
|
+
|
|
132
160
|
interface CommentDoc {
|
|
133
161
|
_id: ObjectId;
|
|
134
162
|
slug: string;
|
|
@@ -215,4 +243,4 @@ declare class CommentsError extends Error {
|
|
|
215
243
|
retryAfter?: number | undefined);
|
|
216
244
|
}
|
|
217
245
|
|
|
218
|
-
export { type CommentDoc, CommentsError, type CommentsRouter, type CommentsServerOptions, type CommentsService, type GoogleIdentity, type RateLimitOptions, type RateLimitRule, type RateLimitStore, type Store, type UserDoc, createCommentsRouter, createCommentsService, createMemoryRateLimitStore, createMongoRateLimitStore, openStore, resolveOptions };
|
|
246
|
+
export { type CommentDoc, CommentsError, type CommentsHandlerOptions, type CommentsRouter, type CommentsServerOptions, type CommentsService, type GoogleIdentity, type RateLimitOptions, type RateLimitRule, type RateLimitStore, type Store, type UserDoc, createCommentsHandler, createCommentsRouter, createCommentsService, createMemoryRateLimitStore, createMongoRateLimitStore, openStore, resolveOptions };
|
package/dist/index.js
CHANGED
|
@@ -575,8 +575,79 @@ var createCommentsRouter = async (options) => {
|
|
|
575
575
|
router.close = store.close;
|
|
576
576
|
return router;
|
|
577
577
|
};
|
|
578
|
+
|
|
579
|
+
// src/handler.ts
|
|
580
|
+
import express2 from "express";
|
|
581
|
+
var SUB_PATH = /^[a-z0-9/_-]{0,200}$/i;
|
|
582
|
+
var sendJson = (res, status, body) => {
|
|
583
|
+
if (res.writableEnded) return;
|
|
584
|
+
res.statusCode = status;
|
|
585
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
586
|
+
res.end(JSON.stringify(body));
|
|
587
|
+
};
|
|
588
|
+
var subPath = (rawUrl, basePath, pathParam, strip) => {
|
|
589
|
+
const url = new URL(rawUrl, "http://localhost");
|
|
590
|
+
let path = null;
|
|
591
|
+
if (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`)) path = url.pathname.slice(basePath.length);
|
|
592
|
+
else if (url.searchParams.has(pathParam)) path = url.searchParams.get(pathParam) ?? "";
|
|
593
|
+
if (path === null) return null;
|
|
594
|
+
for (const key of [pathParam, ...strip]) url.searchParams.delete(key);
|
|
595
|
+
const query = url.searchParams.toString();
|
|
596
|
+
return `${path.replace(/^\/+/, "")}${query ? `?${query}` : ""}`;
|
|
597
|
+
};
|
|
598
|
+
var createCommentsHandler = (options = {}) => {
|
|
599
|
+
const { basePath = "/api/comments", pathParam = "path", stripParams = [], ...routerOptions } = options;
|
|
600
|
+
const base = basePath.replace(/\/+$/, "");
|
|
601
|
+
let starting = null;
|
|
602
|
+
const start = () => {
|
|
603
|
+
starting ??= createCommentsRouter(routerOptions).then((router) => {
|
|
604
|
+
const app = express2();
|
|
605
|
+
app.disable("x-powered-by");
|
|
606
|
+
app.set("trust proxy", true);
|
|
607
|
+
app.use(base, router);
|
|
608
|
+
return { app, router };
|
|
609
|
+
}).catch((error) => {
|
|
610
|
+
starting = null;
|
|
611
|
+
throw error;
|
|
612
|
+
});
|
|
613
|
+
return starting;
|
|
614
|
+
};
|
|
615
|
+
const handler = async (req, res) => {
|
|
616
|
+
const path = subPath(req.url ?? "/", base, pathParam, stripParams);
|
|
617
|
+
if (path === null || !SUB_PATH.test(path.split("?")[0] ?? "")) return sendJson(res, 404, { error: "Not found.", code: "not_found" });
|
|
618
|
+
let app;
|
|
619
|
+
try {
|
|
620
|
+
({ app } = await start());
|
|
621
|
+
} catch (error) {
|
|
622
|
+
console.error("[comments-server] failed to start:", error instanceof Error ? error.message : error);
|
|
623
|
+
return sendJson(res, 503, { error: "Comments are temporarily unavailable.", code: "unavailable" });
|
|
624
|
+
}
|
|
625
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
626
|
+
try {
|
|
627
|
+
void req.body;
|
|
628
|
+
} catch {
|
|
629
|
+
return sendJson(res, 400, { error: "Invalid JSON body.", code: "invalid_json" });
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
req.url = `${base}/${path}`;
|
|
633
|
+
await new Promise((resolve) => {
|
|
634
|
+
res.once("finish", resolve);
|
|
635
|
+
res.once("close", resolve);
|
|
636
|
+
app(req, res);
|
|
637
|
+
});
|
|
638
|
+
};
|
|
639
|
+
return Object.assign(handler, {
|
|
640
|
+
close: async () => {
|
|
641
|
+
if (!starting) return;
|
|
642
|
+
const { router } = await starting.catch(() => ({ router: null }));
|
|
643
|
+
await router?.close();
|
|
644
|
+
starting = null;
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
};
|
|
578
648
|
export {
|
|
579
649
|
CommentsError,
|
|
650
|
+
createCommentsHandler,
|
|
580
651
|
createCommentsRouter,
|
|
581
652
|
createCommentsService,
|
|
582
653
|
createMemoryRateLimitStore,
|
package/package.json
CHANGED