@docs-sdk-dev/next 0.0.0-stage → 0.4.0-next.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.
@@ -0,0 +1,35 @@
1
+ /** The environment variable that tells the Next dev server where `devNext` publishes build events. */
2
+ export declare const devEventsVariable = "DOCS_SDK_DEV_EVENTS";
3
+ /** The same messages `docs dev` sends its pages: a build made `revision` current, or a build failed. */
4
+ export type DevMessage = {
5
+ type: "built";
6
+ revision: string;
7
+ documents: number;
8
+ } | {
9
+ type: "failed";
10
+ code: string;
11
+ message: string;
12
+ source?: string;
13
+ line?: number;
14
+ };
15
+ /** Describe a failed build for open pages without its stack trace. */
16
+ export declare function devFailure(error: unknown): Extract<DevMessage, {
17
+ type: "failed";
18
+ }>;
19
+ /**
20
+ * The hint `devNext` prints when open pages would not refresh after a rebuild: the App Router's root layout exists
21
+ * but never names `DocsDevRefresh`. Undefined when the layout renders it or no root layout is found.
22
+ */
23
+ export declare function devRefreshHint(root: string): Promise<string | undefined>;
24
+ /**
25
+ * Serve build events to open pages over Server-Sent Events on a loopback port. Pages live on the Next dev origin,
26
+ * so the stream allows cross-origin reads from loopback origins only.
27
+ */
28
+ export declare function serveDevEvents(): Promise<{
29
+ url: string;
30
+ /** How many open pages are listening for builds. */
31
+ listeners: () => number;
32
+ built(revision: string, documents: number): void;
33
+ failed(error: unknown): void;
34
+ close(): Promise<void>;
35
+ }>;
@@ -0,0 +1,117 @@
1
+ import { createServer } from "node:http";
2
+ import { once } from "node:events";
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { isDocsError } from "@docs-sdk-dev/core";
6
+
7
+ // src/dev-events.ts
8
+ /** The environment variable that tells the Next dev server where `devNext` publishes build events. */
9
+ const devEventsVariable = "DOCS_SDK_DEV_EVENTS";
10
+ /** Describe a failed build for open pages without its stack trace. */
11
+ function devFailure(error) {
12
+ const location = isDocsError(error) ? error.location : {};
13
+ return {
14
+ type: "failed",
15
+ code: isDocsError(error) ? error.code : "DOCS_BUILD_FAILED",
16
+ message: error instanceof Error ? error.message : String(error),
17
+ ...location.source ? { source: location.source } : {},
18
+ ...location.line ? { line: location.line } : {}
19
+ };
20
+ }
21
+ const layouts = ["app", "src/app"].flatMap((folder) => [
22
+ "tsx",
23
+ "jsx",
24
+ "ts",
25
+ "js"
26
+ ].map((extension) => join(folder, "layout." + extension)));
27
+ /**
28
+ * The hint `devNext` prints when open pages would not refresh after a rebuild: the App Router's root layout exists
29
+ * but never names `DocsDevRefresh`. Undefined when the layout renders it or no root layout is found.
30
+ */
31
+ async function devRefreshHint(root) {
32
+ for (const layout of layouts) {
33
+ const source = await readFile(join(root, layout), "utf8").catch(() => void 0);
34
+ if (source === void 0) continue;
35
+ if (source.includes("DocsDevRefresh")) return;
36
+ return `Open pages won't refresh after rebuilds: ${layout} doesn't render DocsDevRefresh. Add \`import { DocsDevRefresh } from "@docs-sdk-dev/next/server"\` and render \`<DocsDevRefresh docs={docs} />\` in its <body>.`;
37
+ }
38
+ }
39
+ const loopback = /* @__PURE__ */ new Set([
40
+ "localhost",
41
+ "127.0.0.1",
42
+ "[::1]"
43
+ ]);
44
+ function loopbackOrigin(origin) {
45
+ if (!origin) return;
46
+ try {
47
+ const url = new URL(origin);
48
+ return /^https?:$/.test(url.protocol) && loopback.has(url.hostname) ? url.origin : void 0;
49
+ } catch {
50
+ return;
51
+ }
52
+ }
53
+ /**
54
+ * Serve build events to open pages over Server-Sent Events on a loopback port. Pages live on the Next dev origin,
55
+ * so the stream allows cross-origin reads from loopback origins only.
56
+ */
57
+ async function serveDevEvents() {
58
+ const clients = /* @__PURE__ */ new Set();
59
+ let built;
60
+ let failed;
61
+ let host = "";
62
+ const write = (response, message) => response.write(`data: ${JSON.stringify(message)}\n\n`);
63
+ const server = createServer((request, response) => {
64
+ if (request.headers.host !== host) return response.writeHead(421).end();
65
+ if (new URL(request.url ?? "/", "http://localhost").pathname !== "/__docs/events") return response.writeHead(404).end();
66
+ const origin = loopbackOrigin(request.headers.origin);
67
+ response.writeHead(200, {
68
+ "content-type": "text/event-stream",
69
+ "cache-control": "no-store",
70
+ connection: "keep-alive",
71
+ ...origin && {
72
+ "access-control-allow-origin": origin,
73
+ vary: "origin"
74
+ }
75
+ });
76
+ response.write(": connected\n\n");
77
+ if (built) write(response, built);
78
+ if (failed) write(response, failed);
79
+ clients.add(response);
80
+ request.on("close", () => clients.delete(response));
81
+ });
82
+ server.listen(0, "127.0.0.1");
83
+ await once(server, "listening");
84
+ const address = server.address();
85
+ if (!address || typeof address === "string") throw new Error("Expected a loopback port.");
86
+ host = `127.0.0.1:${address.port}`;
87
+ const send = (message) => {
88
+ for (const response of clients) write(response, message);
89
+ };
90
+ return {
91
+ url: `http://${host}/__docs/events`,
92
+ /** How many open pages are listening for builds. */
93
+ listeners: () => clients.size,
94
+ built(revision, documents) {
95
+ built = {
96
+ type: "built",
97
+ revision,
98
+ documents
99
+ };
100
+ failed = void 0;
101
+ send(built);
102
+ },
103
+ failed(error) {
104
+ failed = devFailure(error);
105
+ send(failed);
106
+ },
107
+ async close() {
108
+ for (const response of clients) response.end();
109
+ clients.clear();
110
+ server.closeAllConnections();
111
+ await new Promise((done) => server.close(() => done()));
112
+ }
113
+ };
114
+ }
115
+
116
+ export { devEventsVariable, devFailure, devRefreshHint, serveDevEvents };
117
+ //# sourceMappingURL=dev-events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-events.js","names":[],"sources":["../src/dev-events.ts"],"sourcesContent":["import { createServer, type ServerResponse } from \"node:http\"\nimport { once } from \"node:events\"\nimport { readFile } from \"node:fs/promises\"\nimport { join } from \"node:path\"\nimport { isDocsError } from \"@docs-sdk-dev/core\"\n\n/** The environment variable that tells the Next dev server where `devNext` publishes build events. */\nexport const devEventsVariable = \"DOCS_SDK_DEV_EVENTS\"\n\n/** The same messages `docs dev` sends its pages: a build made `revision` current, or a build failed. */\nexport type DevMessage =\n | { type: \"built\"; revision: string; documents: number }\n | { type: \"failed\"; code: string; message: string; source?: string; line?: number }\n\n/** Describe a failed build for open pages without its stack trace. */\nexport function devFailure(error: unknown): Extract<DevMessage, { type: \"failed\" }> {\n const location = isDocsError(error) ? error.location : {}\n return {\n type: \"failed\",\n code: isDocsError(error) ? error.code : \"DOCS_BUILD_FAILED\",\n message: error instanceof Error ? error.message : String(error),\n ...(location.source ? { source: location.source } : {}),\n ...(location.line ? { line: location.line } : {}),\n }\n}\n\nconst layouts = [\"app\", \"src/app\"].flatMap((folder) =>\n [\"tsx\", \"jsx\", \"ts\", \"js\"].map((extension) => join(folder, \"layout.\" + extension)),\n)\n\n/**\n * The hint `devNext` prints when open pages would not refresh after a rebuild: the App Router's root layout exists\n * but never names `DocsDevRefresh`. Undefined when the layout renders it or no root layout is found.\n */\nexport async function devRefreshHint(root: string) {\n for (const layout of layouts) {\n const source = await readFile(join(root, layout), \"utf8\").catch(() => undefined)\n if (source === undefined) continue\n if (source.includes(\"DocsDevRefresh\")) return\n return (\n `Open pages won't refresh after rebuilds: ${layout} doesn't render DocsDevRefresh. Add ` +\n `\\`import { DocsDevRefresh } from \"@docs-sdk-dev/next/server\"\\` and render ` +\n `\\`<DocsDevRefresh docs={docs} />\\` in its <body>.`\n )\n }\n}\n\nconst loopback = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"])\n\nfunction loopbackOrigin(origin: string | undefined) {\n if (!origin) return\n try {\n const url = new URL(origin)\n return /^https?:$/.test(url.protocol) && loopback.has(url.hostname) ? url.origin : undefined\n } catch {\n return\n }\n}\n\n/**\n * Serve build events to open pages over Server-Sent Events on a loopback port. Pages live on the Next dev origin,\n * so the stream allows cross-origin reads from loopback origins only.\n */\nexport async function serveDevEvents() {\n const clients = new Set<ServerResponse>()\n let built: Extract<DevMessage, { type: \"built\" }> | undefined\n let failed: Extract<DevMessage, { type: \"failed\" }> | undefined\n let host = \"\"\n const write = (response: ServerResponse, message: DevMessage) =>\n response.write(`data: ${JSON.stringify(message)}\\n\\n`)\n const server = createServer((request, response) => {\n // A page on another host name that resolves to this address cannot read the stream.\n if (request.headers.host !== host) return response.writeHead(421).end()\n if (new URL(request.url ?? \"/\", \"http://localhost\").pathname !== \"/__docs/events\")\n return response.writeHead(404).end()\n const origin = loopbackOrigin(request.headers.origin)\n response.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-store\",\n connection: \"keep-alive\",\n ...(origin && { \"access-control-allow-origin\": origin, vary: \"origin\" }),\n })\n response.write(\": connected\\n\\n\")\n // A page compares the current build with the one it rendered, so a build that finished while it loaded is not\n // missed. A page opened while the last build had failed sees the error at once.\n if (built) write(response, built)\n if (failed) write(response, failed)\n clients.add(response)\n request.on(\"close\", () => clients.delete(response))\n })\n server.listen(0, \"127.0.0.1\")\n await once(server, \"listening\")\n const address = server.address()\n if (!address || typeof address === \"string\") throw new Error(\"Expected a loopback port.\")\n host = `127.0.0.1:${address.port}`\n const send = (message: DevMessage) => {\n for (const response of clients) write(response, message)\n }\n return {\n url: `http://${host}/__docs/events`,\n /** How many open pages are listening for builds. */\n listeners: () => clients.size,\n built(revision: string, documents: number) {\n built = { type: \"built\", revision, documents }\n failed = undefined\n send(built)\n },\n failed(error: unknown) {\n failed = devFailure(error)\n send(failed)\n },\n async close() {\n for (const response of clients) response.end()\n clients.clear()\n server.closeAllConnections()\n await new Promise<void>((done) => server.close(() => done()))\n },\n }\n}\n"],"mappings":";;;;;;;;AAOA,MAAa,oBAAoB;;AAQjC,SAAgB,WAAW,OAAyD;CAClF,MAAM,WAAW,YAAY,KAAK,IAAI,MAAM,WAAW,CAAC;CACxD,OAAO;EACL,MAAM;EACN,MAAM,YAAY,KAAK,IAAI,MAAM,OAAO;EACxC,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,GAAI,SAAS,SAAS,EAAE,QAAQ,SAAS,OAAO,IAAI,CAAC;EACrD,GAAI,SAAS,OAAO,EAAE,MAAM,SAAS,KAAK,IAAI,CAAC;CACjD;AAC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A+B;IAAQ,MAAM;GAAS;EACxE,CAAC;EACD,SAAS,MAAM,iBAAiB;EAGhC,IAAI,OAAO,MAAM,UAAU,KAAK;EAChC,IAAI,QAAQ,MAAM,UAAU,MAAM;EAClC,QAAQ,IAAI,QAAQ;EACpB,QAAQ,GAAG,eAAe,QAAQ,OAAO,QAAQ,CAAC;CACpD,CAAC;CACD,OAAO,OAAO,GAAG,WAAW;CAC5B,MAAM,KAAK,QAAQ,WAAW;CAC9B,MAAM,UAAU,OAAO,QAAQ;CAC/B,IAAI,CAAC,WAAW,OAAO,YAAY,UAAU,MAAM,IAAI,MAAM,2BAA2B;CACxF,OAAO,aAAa,QAAQ;CAC5B,MAAM,QAAQ,YAAwB;EACpC,KAAK,MAAM,YAAY,SAAS,MAAM,UAAU,OAAO;CACzD;CACA,OAAO;EACL,KAAK,UAAU,KAAK;;EAEpB,iBAAiB,QAAQ;EACzB,MAAM,UAAkB,WAAmB;GACzC,QAAQ;IAAE,MAAM;IAAS;IAAU;GAAU;GAC7C,SAAS;GACT,KAAK,KAAK;EACZ;EACA,OAAO,OAAgB;GACrB,SAAS,WAAW,KAAK;GACzB,KAAK,MAAM;EACb;EACA,MAAM,QAAQ;GACZ,KAAK,MAAM,YAAY,SAAS,SAAS,IAAI;GAC7C,QAAQ,MAAM;GACd,OAAO,oBAAoB;GAC3B,MAAM,IAAI,SAAe,SAAS,OAAO,YAAY,KAAK,CAAC,CAAC;EAC9D;CACF;AACF"}
@@ -0,0 +1,9 @@
1
+ import { type ReactNode } from "react";
2
+ /**
3
+ * Follow `devNext` builds from an open page. A build that changes the publication refreshes the route in place,
4
+ * which keeps client state and scroll. A failed build shows its error until the next one succeeds.
5
+ */
6
+ export declare function DevRefresh({ url, revision }: {
7
+ url: string;
8
+ revision: string;
9
+ }): ReactNode;
@@ -0,0 +1,51 @@
1
+ "use client";
2
+
3
+ import { useRouter } from "next/navigation.js";
4
+ import { createElement, useEffect, useRef, useState } from "react";
5
+
6
+ // src/dev-refresh.ts
7
+ const panel = {
8
+ position: "fixed",
9
+ inset: "auto 1rem 1rem 1rem",
10
+ zIndex: 0x7fffffff,
11
+ maxHeight: "50vh",
12
+ overflow: "auto",
13
+ padding: "1rem 1.25rem",
14
+ borderRadius: 12,
15
+ background: "#2b0f12",
16
+ color: "#ffe9ea",
17
+ font: "13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace",
18
+ boxShadow: "0 12px 40px #0006"
19
+ };
20
+ /**
21
+ * Follow `devNext` builds from an open page. A build that changes the publication refreshes the route in place,
22
+ * which keeps client state and scroll. A failed build shows its error until the next one succeeds.
23
+ */
24
+ function DevRefresh({ url, revision }) {
25
+ const router = useRouter();
26
+ const served = useRef(revision);
27
+ const [failure, setFailure] = useState();
28
+ useEffect(() => {
29
+ const events = new EventSource(url);
30
+ events.addEventListener("message", (event) => {
31
+ const message = JSON.parse(event.data);
32
+ if (message.type === "failed") return setFailure(message);
33
+ if (message.type !== "built") return;
34
+ setFailure(void 0);
35
+ if (message.revision === served.current) return;
36
+ served.current = message.revision;
37
+ router.refresh();
38
+ });
39
+ return () => events.close();
40
+ }, [url, router]);
41
+ if (!failure) return null;
42
+ const where = failure.source ? failure.source + (failure.line ? ":" + failure.line : "") : "";
43
+ return createElement("section", {
44
+ id: "docs-dev-error",
45
+ role: "alert",
46
+ style: panel
47
+ }, createElement("strong", null, "Build failed: " + failure.code), createElement("p", null, failure.message), where && createElement("p", null, where), createElement("p", null, "The page shows the last good build. Save a fix to rebuild."));
48
+ }
49
+
50
+ export { DevRefresh };
51
+ //# sourceMappingURL=dev-refresh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-refresh.js","names":[],"sources":["../src/dev-refresh.ts"],"sourcesContent":["\"use client\"\n\nimport { useRouter } from \"next/navigation.js\"\nimport { createElement, useEffect, useRef, useState, type ReactNode } from \"react\"\n\ntype Failure = { code: string; message: string; source?: string; line?: number }\n\nconst panel = {\n position: \"fixed\",\n inset: \"auto 1rem 1rem 1rem\",\n zIndex: 2147483647,\n maxHeight: \"50vh\",\n overflow: \"auto\",\n padding: \"1rem 1.25rem\",\n borderRadius: 12,\n background: \"#2b0f12\",\n color: \"#ffe9ea\",\n font: \"13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace\",\n boxShadow: \"0 12px 40px #0006\",\n} as const\n\n/**\n * Follow `devNext` builds from an open page. A build that changes the publication refreshes the route in place,\n * which keeps client state and scroll. A failed build shows its error until the next one succeeds.\n */\nexport function DevRefresh({ url, revision }: { url: string; revision: string }): ReactNode {\n const router = useRouter()\n const served = useRef(revision)\n const [failure, setFailure] = useState<Failure>()\n useEffect(() => {\n const events = new EventSource(url)\n events.addEventListener(\"message\", (event) => {\n const message = JSON.parse(event.data)\n if (message.type === \"failed\") return setFailure(message)\n if (message.type !== \"built\") return\n setFailure(undefined)\n if (message.revision === served.current) return\n served.current = message.revision\n router.refresh()\n })\n return () => events.close()\n }, [url, router])\n if (!failure) return null\n const where = failure.source ? failure.source + (failure.line ? \":\" + failure.line : \"\") : \"\"\n return createElement(\n \"section\",\n { id: \"docs-dev-error\", role: \"alert\", style: panel },\n createElement(\"strong\", null, \"Build failed: \" + failure.code),\n createElement(\"p\", null, failure.message),\n where && createElement(\"p\", null, where),\n createElement(\"p\", null, \"The page shows the last good build. Save a fix to rebuild.\"),\n )\n}\n"],"mappings":";;;;;;AAOA,MAAM,QAAQ;CACZ,UAAU;CACV,OAAO;CACP,QAAQ;CACR,WAAW;CACX,UAAU;CACV,SAAS;CACT,cAAc;CACd,YAAY;CACZ,OAAO;CACP,MAAM;CACN,WAAW;AACb;;;;;AAMA,SAAgB,WAAW,EAAE,KAAK,YAA0D;CAC1F,MAAM,SAAS,UAAU;CACzB,MAAM,SAAS,OAAO,QAAQ;CAC9B,MAAM,CAAC,SAAS,cAAc,SAAkB;CAChD,gBAAgB;EACd,MAAM,SAAS,IAAI,YAAY,GAAG;EAClC,OAAO,iBAAiB,YAAY,UAAU;GAC5C,MAAM,UAAU,KAAK,MAAM,MAAM,IAAI;GACrC,IAAI,QAAQ,SAAS,UAAU,OAAO,WAAW,OAAO;GACxD,IAAI,QAAQ,SAAS,SAAS;GAC9B,WAAW,MAAS;GACpB,IAAI,QAAQ,aAAa,OAAO,SAAS;GACzC,OAAO,UAAU,QAAQ;GACzB,OAAO,QAAQ;EACjB,CAAC;EACD,aAAa,OAAO,MAAM;CAC5B,GAAG,CAAC,KAAK,MAAM,CAAC;CAChB,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,QAAQ,QAAQ,SAAS,QAAQ,UAAU,QAAQ,OAAO,MAAM,QAAQ,OAAO,MAAM;CAC3F,OAAO,cACL,WACA;EAAE,IAAI;EAAkB,MAAM;EAAS,OAAO;CAAM,GACpD,cAAc,UAAU,MAAM,mBAAmB,QAAQ,IAAI,GAC7D,cAAc,KAAK,MAAM,QAAQ,OAAO,GACxC,SAAS,cAAc,KAAK,MAAM,KAAK,GACvC,cAAc,KAAK,MAAM,4DAA4D,CACvF;AACF"}
@@ -0,0 +1 @@
1
+ export * from "./server.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ import { DocsMetadata, toNextMetadata } from "./metadata.js";
2
+ import { openAccessPublication, openPublication, publicPublication } from "./publication.js";
3
+ import { DocsDevRefresh, createDocs } from "./server.js";
4
+
5
+ export { DocsDevRefresh, DocsMetadata, createDocs, openAccessPublication, openPublication, publicPublication, toNextMetadata };
@@ -0,0 +1,15 @@
1
+ import type { Metadata } from "next";
2
+ import type { ResolvedMetadata } from "@docs-sdk-dev/core";
3
+ export declare function toNextMetadata(metadata: ResolvedMetadata): Metadata;
4
+ /** Render JSON-LD and social fields that require exact output from an App Router page. */
5
+ export declare function DocsMetadata({ metadata }: {
6
+ metadata?: ResolvedMetadata;
7
+ }): (import("react").DetailedReactHTMLElement<import("react").HTMLAttributes<HTMLElement>, HTMLElement> | import("react").DetailedReactHTMLElement<{
8
+ key: number;
9
+ dangerouslySetInnerHTML: {
10
+ __html: string;
11
+ };
12
+ }, HTMLElement> | import("react").ReactElement<{
13
+ key: number;
14
+ hrefLang: string;
15
+ }, string | import("react").JSXElementConstructor<any>>)[] | null;
@@ -0,0 +1,48 @@
1
+ import { metadataHead, metadataRobots } from "@docs-sdk-dev/web/metadata";
2
+ import { renderMetadataHead } from "@docs-sdk-dev/react/server";
3
+
4
+ // src/metadata.ts
5
+ function needsExactSocial(metadata) {
6
+ const { description, openGraph, twitter } = metadata;
7
+ return Boolean(openGraph && (!twitter || !openGraph.description && description) || twitter && !twitter.description && (openGraph?.description || description) || openGraph?.image?.url.startsWith("/") || twitter?.image?.url.startsWith("/"));
8
+ }
9
+ function toNextMetadata(metadata) {
10
+ const { title, description, canonical, alternates, openGraph, twitter } = metadata;
11
+ const exactSocial = needsExactSocial(metadata);
12
+ return {
13
+ title: { absolute: title },
14
+ description: description ?? null,
15
+ alternates: {
16
+ canonical: canonical ?? null,
17
+ languages: Object.fromEntries(alternates.map(({ language, url }) => [language, url]))
18
+ },
19
+ robots: metadataRobots(metadata.robots) || null,
20
+ openGraph: openGraph && !exactSocial ? {
21
+ type: openGraph.type,
22
+ title: { absolute: openGraph.title },
23
+ description: openGraph.description,
24
+ url: openGraph.url,
25
+ siteName: openGraph.siteName,
26
+ locale: openGraph.locale,
27
+ alternateLocale: openGraph.alternateLocales && [...openGraph.alternateLocales],
28
+ images: openGraph.image ? [openGraph.image] : []
29
+ } : null,
30
+ twitter: twitter && !exactSocial ? {
31
+ card: twitter.card,
32
+ title: { absolute: twitter.title },
33
+ description: twitter.description,
34
+ site: twitter.site,
35
+ creator: twitter.creator,
36
+ images: twitter.image ? [twitter.image] : []
37
+ } : null
38
+ };
39
+ }
40
+ /** Render JSON-LD and social fields that require exact output from an App Router page. */
41
+ function DocsMetadata({ metadata }) {
42
+ if (!metadata) return null;
43
+ const exactSocial = needsExactSocial(metadata);
44
+ return renderMetadataHead(metadataHead(metadata).filter((entry) => entry.tag === "script" || exactSocial && entry.tag === "meta" && (entry.attributes.property?.startsWith("og:") || entry.attributes.name?.startsWith("twitter:"))));
45
+ }
46
+
47
+ export { DocsMetadata, toNextMetadata };
48
+ //# sourceMappingURL=metadata.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metadata.js","names":[],"sources":["../src/metadata.ts"],"sourcesContent":["import type { Metadata } from \"next\"\nimport type { ResolvedMetadata } from \"@docs-sdk-dev/core\"\nimport { metadataHead, metadataRobots } from \"@docs-sdk-dev/web/metadata\"\nimport { renderMetadataHead } from \"@docs-sdk-dev/react/server\"\n\n// Next fills absent social fields from OG and the page. Emit the resolved tags directly when a user disabled such a field.\nfunction needsExactSocial(metadata: ResolvedMetadata) {\n const { description, openGraph, twitter } = metadata\n return Boolean(\n (openGraph && (!twitter || (!openGraph.description && description))) ||\n (twitter && !twitter.description && (openGraph?.description || description)) ||\n openGraph?.image?.url.startsWith(\"/\") ||\n twitter?.image?.url.startsWith(\"/\"),\n )\n}\n\nexport function toNextMetadata(metadata: ResolvedMetadata): Metadata {\n const { title, description, canonical, alternates, openGraph, twitter } = metadata\n const exactSocial = needsExactSocial(metadata)\n return {\n title: { absolute: title },\n description: description ?? null,\n alternates: {\n canonical: canonical ?? null,\n languages: Object.fromEntries(alternates.map(({ language, url }) => [language, url])),\n },\n robots: metadataRobots(metadata.robots) || null,\n openGraph:\n openGraph && !exactSocial\n ? {\n type: openGraph.type,\n title: { absolute: openGraph.title },\n description: openGraph.description,\n url: openGraph.url,\n siteName: openGraph.siteName,\n locale: openGraph.locale,\n alternateLocale: openGraph.alternateLocales && [...openGraph.alternateLocales],\n images: openGraph.image ? [openGraph.image] : [],\n }\n : null,\n twitter:\n twitter && !exactSocial\n ? {\n card: twitter.card,\n title: { absolute: twitter.title },\n description: twitter.description,\n site: twitter.site,\n creator: twitter.creator,\n images: twitter.image ? [twitter.image] : [],\n }\n : null,\n }\n}\n\n/** Render JSON-LD and social fields that require exact output from an App Router page. */\nexport function DocsMetadata({ metadata }: { metadata?: ResolvedMetadata }) {\n if (!metadata) return null\n const exactSocial = needsExactSocial(metadata)\n return renderMetadataHead(\n metadataHead(metadata).filter(\n (entry) =>\n entry.tag === \"script\" ||\n (exactSocial &&\n entry.tag === \"meta\" &&\n (entry.attributes.property?.startsWith(\"og:\") ||\n entry.attributes.name?.startsWith(\"twitter:\"))),\n ),\n )\n}\n"],"mappings":";;;;AAMA,SAAS,iBAAiB,UAA4B;CACpD,MAAM,EAAE,aAAa,WAAW,YAAY;CAC5C,OAAO,QACJ,cAAc,CAAC,WAAY,CAAC,UAAU,eAAe,gBACrD,WAAW,CAAC,QAAQ,gBAAgB,WAAW,eAAe,gBAC/D,WAAW,OAAO,IAAI,WAAW,GAAG,KACpC,SAAS,OAAO,IAAI,WAAW,GAAG,CACpC;AACF;AAEA,SAAgB,eAAe,UAAsC;CACnE,MAAM,EAAE,OAAO,aAAa,WAAW,YAAY,WAAW,YAAY;CAC1E,MAAM,cAAc,iBAAiB,QAAQ;CAC7C,OAAO;EACL,OAAO,EAAE,UAAU,MAAM;EACzB,aAAa,eAAe;EAC5B,YAAY;GACV,WAAW,aAAa;GACxB,WAAW,OAAO,YAAY,WAAW,KAAK,EAAE,UAAU,UAAU,CAAC,UAAU,GAAG,CAAC,CAAC;EACtF;EACA,QAAQ,eAAe,SAAS,MAAM,KAAK;EAC3C,WACE,aAAa,CAAC,cACV;GACE,MAAM,UAAU;GAChB,OAAO,EAAE,UAAU,UAAU,MAAM;GACnC,aAAa,UAAU;GACvB,KAAK,UAAU;GACf,UAAU,UAAU;GACpB,QAAQ,UAAU;GAClB,iBAAiB,UAAU,oBAAoB,CAAC,GAAG,UAAU,gBAAgB;GAC7E,QAAQ,UAAU,QAAQ,CAAC,UAAU,KAAK,IAAI,CAAC;EACjD,IACA;EACN,SACE,WAAW,CAAC,cACR;GACE,MAAM,QAAQ;GACd,OAAO,EAAE,UAAU,QAAQ,MAAM;GACjC,aAAa,QAAQ;GACrB,MAAM,QAAQ;GACd,SAAS,QAAQ;GACjB,QAAQ,QAAQ,QAAQ,CAAC,QAAQ,KAAK,IAAI,CAAC;EAC7C,IACA;CACR;AACF;;AAGA,SAAgB,aAAa,EAAE,YAA6C;CAC1E,IAAI,CAAC,UAAU,OAAO;CACtB,MAAM,cAAc,iBAAiB,QAAQ;CAC7C,OAAO,mBACL,aAAa,QAAQ,CAAC,CAAC,QACpB,UACC,MAAM,QAAQ,YACb,eACC,MAAM,QAAQ,WACb,MAAM,WAAW,UAAU,WAAW,KAAK,KAC1C,MAAM,WAAW,MAAM,WAAW,UAAU,EACpD,CACF;AACF"}
@@ -0,0 +1,9 @@
1
+ import type { WebPublication } from "@docs-sdk-dev/node/publication";
2
+ export interface NativeRoutes {
3
+ /** Module exporting `docs` and `renderDocsPage`, shared by the catch-all and native App Router entries. */
4
+ entry: string;
5
+ appDirectory?: "app" | "src/app";
6
+ revalidate?: number | false;
7
+ home?: readonly string[];
8
+ }
9
+ export declare function writeNativeRoutes(root: string, publication: WebPublication, options: NativeRoutes): Promise<void>;
@@ -0,0 +1,80 @@
1
+ import { lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { dirname, relative, resolve, sep } from "node:path";
4
+ import { DocsError, isSourceAssetPath } from "@docs-sdk-dev/core";
5
+ import { nextNativeRouteGroup } from "@docs-sdk-dev/node/internal/project-inputs";
6
+
7
+ // src/native-routes.ts
8
+ const signature = "// Generated by Docs SDK native routes.\n";
9
+ async function writeNativeRoutes(root, publication, options) {
10
+ const project = await realpath(root);
11
+ const appDirectory = options.appDirectory ?? "app";
12
+ const app = resolve(project, appDirectory);
13
+ const group = resolve(app, nextNativeRouteGroup);
14
+ const entry = resolve(project, options.entry);
15
+ const error = (source, message) => new DocsError("DOCS_NEXT_ROUTE", message, { source });
16
+ if (!["app", "src/app"].includes(appDirectory) || !isSourceAssetPath(options.entry) || await realpath(entry) !== entry || await realpath(app) !== app) throw error(options.entry, "Expected local App Router inputs for Docs SDK.");
17
+ if (options.revalidate !== void 0 && options.revalidate !== false && (!Number.isSafeInteger(options.revalidate) || options.revalidate < 0)) throw error(options.entry, "Expected a non-negative revalidation interval or false.");
18
+ const prior = /* @__PURE__ */ new Map();
19
+ async function collect(directory) {
20
+ const state = await lstat(directory).catch((failure) => {
21
+ if (failure.code !== "ENOENT") throw failure;
22
+ });
23
+ if (!state) return;
24
+ if (!state.isDirectory()) throw error(directory, "Expected a generated route directory.");
25
+ for (const child of await readdir(directory, { withFileTypes: true })) {
26
+ const path = resolve(directory, child.name);
27
+ if (child.isDirectory()) await collect(path);
28
+ else if (child.isFile() && child.name === "page.js") {
29
+ const code = await readFile(path, "utf8");
30
+ if (!code.startsWith(signature)) throw error(path, "The generated route directory contains an author-owned page.");
31
+ prior.set(path, code);
32
+ } else throw error(path, "The generated route directory contains an author-owned entry.");
33
+ }
34
+ }
35
+ await collect(group);
36
+ const files = /* @__PURE__ */ new Map();
37
+ function emit(route, slug, native) {
38
+ if (slug.some((part) => !isSourceAssetPath(part) || !/^[A-Za-z0-9][A-Za-z0-9._=-]*$/.test(part))) throw error(route, "The native route contains a reserved App Router segment.");
39
+ const parts = route.split("/").filter(Boolean).map(decodeURIComponent);
40
+ const file = resolve(group, ...parts, "page.js");
41
+ const specifier = (path) => JSON.stringify("./" + relative(dirname(file), path).split(sep).join("/"));
42
+ const layout = native?.layout === "custom";
43
+ const selected = native && `{ revision: ${JSON.stringify(publication.manifest.buildRevision)}, module: ${JSON.stringify(native.module)}, view: { default: View${layout ? ", Layout" : ""} } }`;
44
+ const code = [
45
+ signature.trimEnd(),
46
+ `import { docs, renderDocsPage } from ${specifier(entry)}`,
47
+ ...native ? [`import View${layout ? ", { Layout }" : ""} from ${specifier(resolve(project, native.module))}`] : [],
48
+ ...options.revalidate === void 0 ? [] : [`export const revalidate = ${JSON.stringify(options.revalidate)}`],
49
+ `const slug = ${JSON.stringify(slug)}`,
50
+ "export function generateMetadata() { return docs.getMetadata(slug) }",
51
+ `export default async function Page() { return renderDocsPage(await docs.getPage(slug${selected ? `, ${selected}` : ""})) }`,
52
+ ""
53
+ ].join("\n");
54
+ files.set(file, code);
55
+ }
56
+ const native = publication.documents.filter((document) => document.nativeView || document.route === "/");
57
+ for (const document of native) emit(document.route, document.route.split("/").filter(Boolean).map(decodeURIComponent), document.nativeView);
58
+ if (options.home && !native.some((document) => document.route === "/")) {
59
+ const requested = "/" + options.home.map(encodeURIComponent).join("/") + "/";
60
+ emit("/", options.home, publication.documents.find((document) => document.route === requested)?.nativeView);
61
+ }
62
+ for (const [file, code] of files) {
63
+ if (prior.get(file) === code) continue;
64
+ await mkdir(dirname(file), { recursive: true });
65
+ if (!prior.has(file)) await writeFile(file, code, { flag: "wx" });
66
+ else {
67
+ const candidate = file + "." + randomUUID();
68
+ try {
69
+ await writeFile(candidate, code, { flag: "wx" });
70
+ await rename(candidate, file);
71
+ } finally {
72
+ await rm(candidate, { force: true });
73
+ }
74
+ }
75
+ }
76
+ for (const file of prior.keys()) if (!files.has(file)) await rm(file);
77
+ }
78
+
79
+ export { writeNativeRoutes };
80
+ //# sourceMappingURL=native-routes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-routes.js","names":[],"sources":["../src/native-routes.ts"],"sourcesContent":["import { lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from \"node:fs/promises\"\nimport { randomUUID } from \"node:crypto\"\nimport { dirname, relative, resolve, sep } from \"node:path\"\nimport { DocsError, isSourceAssetPath } from \"@docs-sdk-dev/core\"\nimport type { Document } from \"@docs-sdk-dev/core\"\nimport { nextNativeRouteGroup } from \"@docs-sdk-dev/node/internal/project-inputs\"\nimport type { WebPublication } from \"@docs-sdk-dev/node/publication\"\n\nexport interface NativeRoutes {\n /** Module exporting `docs` and `renderDocsPage`, shared by the catch-all and native App Router entries. */\n entry: string\n appDirectory?: \"app\" | \"src/app\"\n revalidate?: number | false\n home?: readonly string[]\n}\n\nconst signature = \"// Generated by Docs SDK native routes.\\n\"\n\nexport async function writeNativeRoutes(\n root: string,\n publication: WebPublication,\n options: NativeRoutes,\n) {\n const project = await realpath(root)\n const appDirectory = options.appDirectory ?? \"app\"\n const app = resolve(project, appDirectory)\n const group = resolve(app, nextNativeRouteGroup)\n const entry = resolve(project, options.entry)\n const error = (source: string, message: string) =>\n new DocsError(\"DOCS_NEXT_ROUTE\", message, { source })\n if (\n ![\"app\", \"src/app\"].includes(appDirectory) ||\n !isSourceAssetPath(options.entry) ||\n (await realpath(entry)) !== entry ||\n (await realpath(app)) !== app\n )\n throw error(options.entry, \"Expected local App Router inputs for Docs SDK.\")\n if (\n options.revalidate !== undefined &&\n options.revalidate !== false &&\n (!Number.isSafeInteger(options.revalidate) || options.revalidate < 0)\n )\n throw error(options.entry, \"Expected a non-negative revalidation interval or false.\")\n\n const prior = new Map<string, string>()\n async function collect(directory: string) {\n const state = await lstat(directory).catch((failure: NodeJS.ErrnoException) => {\n if (failure.code !== \"ENOENT\") throw failure\n })\n if (!state) return\n if (!state.isDirectory()) throw error(directory, \"Expected a generated route directory.\")\n for (const child of await readdir(directory, { withFileTypes: true })) {\n const path = resolve(directory, child.name)\n if (child.isDirectory()) await collect(path)\n else if (child.isFile() && child.name === \"page.js\") {\n const code = await readFile(path, \"utf8\")\n if (!code.startsWith(signature))\n throw error(path, \"The generated route directory contains an author-owned page.\")\n prior.set(path, code)\n } else throw error(path, \"The generated route directory contains an author-owned entry.\")\n }\n }\n await collect(group)\n\n const files = new Map<string, string>()\n function emit(route: string, slug: readonly string[], native?: Document[\"nativeView\"]) {\n if (\n slug.some((part) => !isSourceAssetPath(part) || !/^[A-Za-z0-9][A-Za-z0-9._=-]*$/.test(part))\n )\n throw error(route, \"The native route contains a reserved App Router segment.\")\n const parts = route.split(\"/\").filter(Boolean).map(decodeURIComponent)\n const file = resolve(group, ...parts, \"page.js\")\n const specifier = (path: string) =>\n JSON.stringify(\"./\" + relative(dirname(file), path).split(sep).join(\"/\"))\n const layout = native?.layout === \"custom\"\n const selected =\n native &&\n `{ revision: ${JSON.stringify(publication.manifest.buildRevision)}, module: ${JSON.stringify(native.module)}, view: { default: View${layout ? \", Layout\" : \"\"} } }`\n const code = [\n signature.trimEnd(),\n `import { docs, renderDocsPage } from ${specifier(entry)}`,\n ...(native\n ? [\n `import View${layout ? \", { Layout }\" : \"\"} from ${specifier(resolve(project, native.module))}`,\n ]\n : []),\n ...(options.revalidate === undefined\n ? []\n : [`export const revalidate = ${JSON.stringify(options.revalidate)}`]),\n `const slug = ${JSON.stringify(slug)}`,\n \"export function generateMetadata() { return docs.getMetadata(slug) }\",\n `export default async function Page() { return renderDocsPage(await docs.getPage(slug${selected ? `, ${selected}` : \"\"})) }`,\n \"\",\n ].join(\"\\n\")\n files.set(file, code)\n }\n const native = publication.documents.filter(\n (document) => document.nativeView || document.route === \"/\",\n )\n for (const document of native) {\n emit(\n document.route,\n document.route.split(\"/\").filter(Boolean).map(decodeURIComponent),\n document.nativeView,\n )\n }\n if (options.home && !native.some((document) => document.route === \"/\")) {\n const requested = \"/\" + options.home.map(encodeURIComponent).join(\"/\") + \"/\"\n emit(\n \"/\",\n options.home,\n publication.documents.find((document) => document.route === requested)?.nativeView,\n )\n }\n for (const [file, code] of files) {\n if (prior.get(file) === code) continue\n await mkdir(dirname(file), { recursive: true })\n if (!prior.has(file)) await writeFile(file, code, { flag: \"wx\" })\n else {\n const candidate = file + \".\" + randomUUID()\n try {\n await writeFile(candidate, code, { flag: \"wx\" })\n await rename(candidate, file)\n } finally {\n await rm(candidate, { force: true })\n }\n }\n }\n for (const file of prior.keys()) if (!files.has(file)) await rm(file)\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,YAAY;AAElB,eAAsB,kBACpB,MACA,aACA,SACA;CACA,MAAM,UAAU,MAAM,SAAS,IAAI;CACnC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,MAAM,QAAQ,SAAS,YAAY;CACzC,MAAM,QAAQ,QAAQ,KAAK,oBAAoB;CAC/C,MAAM,QAAQ,QAAQ,SAAS,QAAQ,KAAK;C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AkB,CAAC,CAAC,KAAK,GAAG,IAAI;EACzE,KACE,KACA,QAAQ,MACR,YAAY,UAAU,MAAM,aAAa,SAAS,UAAU,SAAS,CAAC,EAAE,UAC1E;CACF;CACA,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO;EAChC,IAAI,MAAM,IAAI,IAAI,MAAM,MAAM;EAC9B,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;EAC9C,IAAI,CAAC,MAAM,IAAI,IAAI,GAAG,MAAM,UAAU,MAAM,MAAM,EAAE,MAAM,KAAK,CAAC;OAC3D;GACH,MAAM,YAAY,OAAO,MAAM,WAAW;GAC1C,IAAI;IACF,MAAM,UAAU,WAAW,MAAM,EAAE,MAAM,KAAK,CAAC;IAC/C,MAAM,OAAO,WAAW,IAAI;GAC9B,UAAU;IACR,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;GACrC;EACF;CACF;CACA,KAAK,MAAM,QAAQ,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,GAAG,MAAM,GAAG,IAAI;AACtE"}
@@ -0,0 +1,6 @@
1
+ import type { AccessDefinition } from "@docs-sdk-dev/core/access";
2
+ import type { DocsPublication, NativeViews } from "./server.js";
3
+ /** Reuse only an application-designated public release. Request-authorized loaders can open an independent publication. */
4
+ export declare function publicPublication(file: string, nativeViews?: NativeViews): () => Promise<DocsPublication>;
5
+ export declare function openPublication(file: string, nativeViews?: NativeViews): Promise<DocsPublication>;
6
+ export declare function openAccessPublication(file: string, access: AccessDefinition, nativeViews?: NativeViews): (request: Request, publicRevision: string) => Promise<DocsPublication>;
@@ -0,0 +1,56 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { openWebPublicationView } from "@docs-sdk-dev/node/publication";
3
+ import { createCompiledPublication } from "@docs-sdk-dev/web/compiled-publication";
4
+ import { createOgResourceHandler } from "@docs-sdk-dev/node/internal/web-serving";
5
+
6
+ // src/publication.ts
7
+ /** Reuse only an application-designated public release. Request-authorized loaders can open an independent publication. */
8
+ function publicPublication(file, nativeViews) {
9
+ let current;
10
+ return async () => {
11
+ const info = await stat(file, { bigint: true });
12
+ const revision = [
13
+ info.dev,
14
+ info.ino,
15
+ info.size,
16
+ info.mtimeNs,
17
+ info.ctimeNs
18
+ ].join(":");
19
+ if (current?.revision !== revision) {
20
+ const publication = openPublication(file, nativeViews);
21
+ current = {
22
+ revision,
23
+ publication
24
+ };
25
+ publication.catch(() => {
26
+ if (current?.publication === publication) current = void 0;
27
+ });
28
+ }
29
+ return current.publication;
30
+ };
31
+ }
32
+ async function openPublication(file, nativeViews) {
33
+ const publication = JSON.parse(await readFile(file, "utf8"));
34
+ return {
35
+ ...docsPublication(publication, nativeViews),
36
+ ...publication.og && { readOgResource: createOgResourceHandler(publication.og) }
37
+ };
38
+ }
39
+ function openAccessPublication(file, access, nativeViews) {
40
+ return async (request, publicRevision) => docsPublication(await openWebPublicationView(file, access, request, publicRevision), nativeViews);
41
+ }
42
+ function docsPublication(publication, nativeViews) {
43
+ return {
44
+ ...createCompiledPublication(publication),
45
+ accessRequired: publication.accessRequired === true,
46
+ metadata: publication.metadata,
47
+ ...nativeViews?.revision === publication.manifest.buildRevision && { readNativeView: (path) => Object.hasOwn(nativeViews.modules, path) ? nativeViews.modules[path]() : void 0 },
48
+ async serveMcp(request) {
49
+ const { servePublicationMcp } = await import("@docs-sdk-dev/node/internal/mcp");
50
+ return servePublicationMcp(request, publication);
51
+ }
52
+ };
53
+ }
54
+
55
+ export { openAccessPublication, openPublication, publicPublication };
56
+ //# sourceMappingURL=publication.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publication.js","names":[],"sources":["../src/publication.ts"],"sourcesContent":["import { readFile, stat } from \"node:fs/promises\"\nimport type { AccessDefinition } from \"@docs-sdk-dev/core/access\"\nimport { openWebPublicationView, type WebPublication } from \"@docs-sdk-dev/node/publication\"\nimport { createCompiledPublication } from \"@docs-sdk-dev/web/compiled-publication\"\nimport { createOgResourceHandler } from \"@docs-sdk-dev/node/internal/web-serving\"\nimport type { DocsPublication, NativeViews } from \"./server.js\"\n\n/** Reuse only an application-designated public release. Request-authorized loaders can open an independent publication. */\nexport function publicPublication(file: string, nativeViews?: NativeViews) {\n let current: { revision: string; publication: Promise<DocsPublication> } | undefined\n return async () => {\n const info = await stat(file, { bigint: true })\n const revision = [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(\":\")\n if (current?.revision !== revision) {\n const publication = openPublication(file, nativeViews)\n current = { revision, publication }\n void publication.catch(() => {\n if (current?.publication === publication) current = undefined\n })\n }\n return current.publication\n }\n}\n\nexport async function openPublication(\n file: string,\n nativeViews?: NativeViews,\n): Promise<DocsPublication> {\n const publication: WebPublication = JSON.parse(await readFile(file, \"utf8\"))\n return {\n ...docsPublication(publication, nativeViews),\n ...(publication.og && { readOgResource: createOgResourceHandler(publication.og) }),\n }\n}\n\nexport function openAccessPublication(\n file: string,\n access: AccessDefinition,\n nativeViews?: NativeViews,\n) {\n return async (request: Request, publicRevision: string): Promise<DocsPublication> =>\n docsPublication(\n await openWebPublicationView(file, access, request, publicRevision),\n nativeViews,\n )\n}\n\nfunction docsPublication(publication: WebPublication, nativeViews?: NativeViews) {\n return {\n ...createCompiledPublication(publication),\n accessRequired: publication.accessRequired === true,\n metadata: publication.metadata,\n ...(nativeViews?.revision === publication.manifest.buildRevision && {\n readNativeView: (path: string) =>\n Object.hasOwn(nativeViews.modules, path) ? nativeViews.modules[path]!() : undefined,\n }),\n async serveMcp(request: Request) {\n const { servePublicationMcp } = await import(\"@docs-sdk-dev/node/internal/mcp\")\n return servePublicationMcp(request, publication)\n },\n }\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,kBAAkB,MAAc,aAA2B;CACzE,IAAI;CACJ,OAAO,YAAY;EACjB,MAAM,OAAO,MAAM,KAAK,MAAM,EAAE,QAAQ,KAAK,CAAC;EAC9C,MAAM,WAAW;GAAC,KAAK;GAAK,KAAK;GAAK,KAAK;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