@taggor/server 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +167 -2
- package/dist/index.d.ts +86 -0
- package/dist/index.js +230 -0
- package/package.json +43 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Taggor
|
|
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,168 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @taggor/server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The helper a site with a server uses to put a Taggor component in its first HTML response. One function,
|
|
4
|
+
no dependency, no framework: the result is a string.
|
|
5
|
+
|
|
6
|
+
> Where server-side rendering is not switched on for your site (or the site has no server key yet), `render`
|
|
7
|
+
> returns the bare tag, which is what the page has without it, so installing this package changes nothing on
|
|
8
|
+
> your site. The docs page for server-side rendering is at <https://taggor.dev/docs/ssr/>.
|
|
9
|
+
|
|
10
|
+
## What it does
|
|
11
|
+
|
|
12
|
+
`render(tag, attributes, options)` asks the Taggor edge for the component's server-rendered fragment
|
|
13
|
+
(`GET <origin>/r/<siteKey>/<tag>?<attributes>`, with the site's server key as `Authorization: Bearer <key>`)
|
|
14
|
+
and returns HTML to write where the tag would go: the element
|
|
15
|
+
with its shadow root already filled, which a browser shows before any script. The site's snippet stays as it is;
|
|
16
|
+
the Taggor runtime takes over the elements already on the screen. Whatever goes wrong (Taggor slow or down, the
|
|
17
|
+
route off, a component that cannot render on a server) it returns the bare tag, and the component renders in
|
|
18
|
+
the browser as it always did.
|
|
19
|
+
|
|
20
|
+
## Use
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { createTaggorServer } from "@taggor/server";
|
|
24
|
+
|
|
25
|
+
export const taggor = createTaggorServer({
|
|
26
|
+
origin: "https://<the origin your snippet is loaded from>", // host of /s/<siteKey>.js, no path
|
|
27
|
+
siteKey: "<the site key>",
|
|
28
|
+
serverKey: process.env.TAGGOR_SERVER_KEY, // the server key, from the server's environment
|
|
29
|
+
ssr: process.env.TAGGOR_SSR !== "off", // the switch: false returns the bare tag, with no request
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const html = await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" });
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
| Option | Default | Meaning |
|
|
36
|
+
| -------------- | -------- | ------------------------------------------------------------------------------------------- |
|
|
37
|
+
| `origin` | required | `https:` origin without a path (`http:` only on a loopback host). |
|
|
38
|
+
| `siteKey` | required | The site key of the snippet. |
|
|
39
|
+
| `serverKey` | required | The site's server key (`tgs_live_…`) from the server's environment; see below. |
|
|
40
|
+
| `ssr` | `true` | `false` turns it off: every `render` returns the bare tag, no request. |
|
|
41
|
+
| `timeoutMs` | `300` | Time one request may take before the bare tag is used. |
|
|
42
|
+
| `cacheSeconds` | `60` | Time a response is reused in this process (`0` for never); a failure is remembered for 5 s. |
|
|
43
|
+
|
|
44
|
+
`render` options: `lang` (the page's language), `nonce` (added to the fragment's `<style>` elements, for a CSP
|
|
45
|
+
with a nonce), `ssr: false` (skip this element). `element(tag, attributes)` returns the bare tag with no
|
|
46
|
+
request. Attributes: text as is, a number as text, `true` as the empty attribute, a list or object as JSON,
|
|
47
|
+
`false`, `null` and `undefined` left out. Errors: `createTaggorServer` throws a `TypeError` for a bad origin,
|
|
48
|
+
site key, or a missing or malformed server key (the message never quotes the key); `render` throws a `TypeError` only for a tag, attribute name or nonce that HTML cannot hold, never for
|
|
49
|
+
anything the network or Taggor does.
|
|
50
|
+
|
|
51
|
+
## The server key
|
|
52
|
+
|
|
53
|
+
The site key is public; the server key is a secret, so only the customer's servers spend the site's server
|
|
54
|
+
renders. Create it on the site's Install > SSR tab in the portal (or `POST /v1/sites/{site_id}/server-keys`);
|
|
55
|
+
it is shown once. Put it in the server's environment as `TAGGOR_SERVER_KEY` and never in browser code, the
|
|
56
|
+
page, a public environment variable or the repository. A site without a key gets no server rendering, and a
|
|
57
|
+
request without a valid key gets the bare tag. A site holds two keys at once, so a rotation is: create, deploy,
|
|
58
|
+
revoke the old one (it stops working within a few minutes at most). The helper sends the key on every request as an
|
|
59
|
+
`Authorization` header, never in the URL.
|
|
60
|
+
|
|
61
|
+
## Where the HTML goes
|
|
62
|
+
|
|
63
|
+
The result is HTML text and each framework has its own raw HTML output. Below, `taggor` is the helper above
|
|
64
|
+
in a module that runs only on the server, with `serverKey: process.env.TAGGOR_SERVER_KEY`. More examples (React Router,
|
|
65
|
+
SvelteKit, Flask) come with the docs page when server-side rendering is switched on.
|
|
66
|
+
|
|
67
|
+
**Next.js (App Router, a Server Component).** `suppressHydrationWarning` is needed: the browser consumes the
|
|
68
|
+
`<template>` when it creates the shadow root, so React would log a hydration error in development. Render the
|
|
69
|
+
page on each request (`export const dynamic = "force-dynamic"`), or the fragment is frozen at build time. Never
|
|
70
|
+
name the key `NEXT_PUBLIC_…`.
|
|
71
|
+
|
|
72
|
+
```tsx
|
|
73
|
+
import { taggor } from "@/lib/taggor";
|
|
74
|
+
|
|
75
|
+
export async function Faq() {
|
|
76
|
+
const html = await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" });
|
|
77
|
+
return <div suppressHydrationWarning dangerouslySetInnerHTML={{ __html: html }} />;
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
**Astro** (`output: "server"` or an on-demand page; a static build freezes the fragment).
|
|
82
|
+
|
|
83
|
+
```astro
|
|
84
|
+
---
|
|
85
|
+
import { taggor } from "../lib/taggor";
|
|
86
|
+
const faq = await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" });
|
|
87
|
+
---
|
|
88
|
+
<Fragment set:html={faq} />
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**Nuxt (Nitro hook).** Never `v-html`: Vue sets `innerHTML` again on hydration and the shadow root is lost.
|
|
92
|
+
Write the fragment into the HTML after Vue rendered it, into a placeholder
|
|
93
|
+
(`<div data-taggor="faq-accordion" />` in `app/app.vue`); `taggor` is auto-imported from `server/utils/taggor.ts`.
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
// server/plugins/taggor.ts
|
|
97
|
+
export default defineNitroPlugin((nitro) => {
|
|
98
|
+
nitro.hooks.hook("render:html", async (html) => {
|
|
99
|
+
const slot = '<div data-taggor="faq-accordion"></div>';
|
|
100
|
+
if (!html.body.some((part) => part.includes(slot))) return;
|
|
101
|
+
const faq = await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" });
|
|
102
|
+
html.body = html.body.map((part) =>
|
|
103
|
+
part.replace(slot, () => `<div data-taggor="faq-accordion">${faq}</div>`),
|
|
104
|
+
);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
**Plain Node (Express, or `node:http`).** Start the server with the key in its environment.
|
|
110
|
+
|
|
111
|
+
```js
|
|
112
|
+
app.get("/", async (_request, response) => {
|
|
113
|
+
const faq = await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" });
|
|
114
|
+
response.send(`<!doctype html><html lang="en"><body>${faq}
|
|
115
|
+
<script async src="https://<your snippet's origin>/s/<site key>.js"></script></body></html>`);
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
**Plain PHP, over HTTP (no WordPress plugin).** Any language can do what the helper does: one request with the
|
|
120
|
+
server key in an `Authorization: Bearer` header (never in the URL) and a short timeout; if the answer is `200`,
|
|
121
|
+
`text/html`, starts with `<tag` and ends with `</tag>`, write the body, otherwise the bare tag. **Not run**
|
|
122
|
+
(there is no PHP on the machine that wrote this); it is a sketch of that rule.
|
|
123
|
+
|
|
124
|
+
```php
|
|
125
|
+
function taggor_render(string $tag, array $attrs = [], string $lang = ''): string {
|
|
126
|
+
if ($lang !== '') { $attrs['lang'] = $lang; }
|
|
127
|
+
$text = [];
|
|
128
|
+
foreach ($attrs as $name => $value) {
|
|
129
|
+
if ($value === false || $value === null) { continue; }
|
|
130
|
+
$text[$name] = $value === true ? '' : (is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : (string) $value);
|
|
131
|
+
}
|
|
132
|
+
$bare = "<$tag";
|
|
133
|
+
foreach ($text as $name => $value) { $bare .= ' ' . $name . '="' . htmlspecialchars($value, ENT_COMPAT) . '"'; }
|
|
134
|
+
$bare .= "></$tag>";
|
|
135
|
+
$url = 'https://<the origin your snippet is loaded from>/r/<the site key>/' . $tag . '?' . http_build_query($text);
|
|
136
|
+
$key = getenv('TAGGOR_SERVER_KEY'); // from the server's environment
|
|
137
|
+
$context = stream_context_create(['http' => ['timeout' => 0.3,
|
|
138
|
+
'header' => "Accept: text/html\r\nAuthorization: Bearer $key\r\n"]]);
|
|
139
|
+
$body = @file_get_contents($url, false, $context);
|
|
140
|
+
$ok = $body !== false && str_contains($http_response_header[0] ?? '', ' 200')
|
|
141
|
+
&& str_starts_with($body, "<$tag") && str_ends_with($body, "</$tag>");
|
|
142
|
+
return $ok ? $body : $bare;
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Caching and revocation
|
|
147
|
+
|
|
148
|
+
The helper keeps each fragment in memory, **per instance** (per process: two servers, or two serverless
|
|
149
|
+
instances, each hold their own copy), for `cacheSeconds` (default 60 s, like the edge's own cache of a key);
|
|
150
|
+
a failure is kept for 5 s. So an instance may serve a cached fragment **up to 60 s after you revoke the server
|
|
151
|
+
key**, on top of the up to about two minutes the edge itself takes to stop accepting a revoked key. An instance
|
|
152
|
+
that has nothing cached asks the edge, gets the bare tag, and caches that. Set `cacheSeconds: 0` if that
|
|
153
|
+
matters more to you than the extra requests (a cached answer does not spend your allowance, a request does).
|
|
154
|
+
Concurrent calls for the same fragment share one request.
|
|
155
|
+
|
|
156
|
+
## Limits
|
|
157
|
+
|
|
158
|
+
No personal data in attributes (they travel in the request URL); no fallback content inside a server-rendered
|
|
159
|
+
tag; a component prop named `ssr` is not rendered on the server; a client-side navigation gets no server
|
|
160
|
+
render. Server renders count against a monthly allowance of your plan, and only requests with the server key
|
|
161
|
+
spend it; a leaked key spends it until it is revoked.
|
|
162
|
+
|
|
163
|
+
## Runtimes
|
|
164
|
+
|
|
165
|
+
The package is one file with no dependency and imports nothing, not even a Node built-in. It was checked as a
|
|
166
|
+
consumer under Node 26 and Deno 2. Bun is **not tested**.
|
|
167
|
+
|
|
168
|
+
License: MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@taggor/server` (SSR spike, ADR 0066): the helper a site with a server uses to put a Taggor
|
|
3
|
+
* component in its first HTML response.
|
|
4
|
+
*
|
|
5
|
+
* `render(tag, attributes)` asks the Taggor edge for the component's server-rendered fragment
|
|
6
|
+
* (`GET <origin>/r/<siteKey>/<tag>?<attributes>`) and returns HTML to write where the tag would
|
|
7
|
+
* go: the element with its shadow root already filled, which the browser shows before any script
|
|
8
|
+
* and the Taggor runtime then takes over. Whatever goes wrong (Taggor slow or down, the route
|
|
9
|
+
* off, a component that cannot render on a server), it returns the bare tag instead, exactly what
|
|
10
|
+
* the page has without this helper, and the component renders in the browser as it always did.
|
|
11
|
+
* The site's snippet (`/s/<siteKey>.js`) stays as it is; this adds nothing to the browser.
|
|
12
|
+
*
|
|
13
|
+
* Server key (spike, ADR 0066, no ticket): every request carries the site's server key
|
|
14
|
+
* (`tgs_live_…`, created in the portal's Install > SSR tab or through `POST /v1/sites/{id}/server-keys`)
|
|
15
|
+
* as `Authorization: Bearer <key>`; without a valid one the edge refuses and this helper writes the
|
|
16
|
+
* bare tag. The key is a server secret: read it from the server's environment
|
|
17
|
+
* (`process.env.TAGGOR_SERVER_KEY`), never put it in browser code or in the repository. It is
|
|
18
|
+
* checked for shape when the helper is created and never appears in an error message or a URL.
|
|
19
|
+
*
|
|
20
|
+
* No dependency and no framework: the result is a string. Where it goes is the framework's raw
|
|
21
|
+
* HTML output (the public page /docs/ssr/, apps/site/docs-src/sources/ssr.md, has tested examples for
|
|
22
|
+
* Next.js, Astro, Express, React Router, SvelteKit, Nuxt and Flask; README.md is this package's guide).
|
|
23
|
+
*/
|
|
24
|
+
/** How the helper is set up, once per site. */
|
|
25
|
+
export interface TaggorServerOptions {
|
|
26
|
+
/** The origin the site's snippet is loaded from (`https://…`, the host of `/s/<siteKey>.js`). */
|
|
27
|
+
readonly origin: string;
|
|
28
|
+
/** The site key of the snippet. */
|
|
29
|
+
readonly siteKey: string;
|
|
30
|
+
/**
|
|
31
|
+
* The site's server key (`tgs_live_…`; `tgs_test_…` outside production), from the server's
|
|
32
|
+
* environment: `serverKey: process.env.TAGGOR_SERVER_KEY`. Required: the type takes `undefined` so
|
|
33
|
+
* an environment read type-checks, and a missing key throws a `TypeError` at creation (without it
|
|
34
|
+
* the edge gives no fragment). A server secret: never send it to a browser.
|
|
35
|
+
*/
|
|
36
|
+
readonly serverKey: string | undefined;
|
|
37
|
+
/** `false` turns server rendering off: every `render` returns the bare tag, with no request. */
|
|
38
|
+
readonly ssr?: boolean;
|
|
39
|
+
/** How long one request may take before the bare tag is used; default 300 ms. */
|
|
40
|
+
readonly timeoutMs?: number;
|
|
41
|
+
/** How long a fragment is reused in this process; default 60 s, `0` for never. */
|
|
42
|
+
readonly cacheSeconds?: number;
|
|
43
|
+
/** The `fetch` to use (default: the global one). */
|
|
44
|
+
readonly fetch?: typeof fetch;
|
|
45
|
+
/** The clock, in milliseconds (default `Date.now`); for tests. */
|
|
46
|
+
readonly now?: () => number;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* An attribute value as a server has it: a string as is, a number as text, `true` as the empty
|
|
50
|
+
* attribute, an array or object as JSON (how a page writes an `array` or `object` prop);
|
|
51
|
+
* `false`, `null` and `undefined` leave the attribute out.
|
|
52
|
+
*/
|
|
53
|
+
export type AttributeValue = string | number | boolean | null | undefined | object;
|
|
54
|
+
/** Per-element choices. */
|
|
55
|
+
export interface RenderOptions {
|
|
56
|
+
/** The page's language (`<html lang>`), written as the element's `lang`. */
|
|
57
|
+
readonly lang?: string;
|
|
58
|
+
/** The page's CSP nonce, added to the fragment's `<style>` elements. */
|
|
59
|
+
readonly nonce?: string;
|
|
60
|
+
/** `false` skips server rendering for this element. */
|
|
61
|
+
readonly ssr?: boolean;
|
|
62
|
+
}
|
|
63
|
+
/** The helper of one site. */
|
|
64
|
+
export interface TaggorServer {
|
|
65
|
+
/**
|
|
66
|
+
* HTML for one component: the server-rendered fragment, or the bare tag. Errors: throws a
|
|
67
|
+
* `TypeError` only for a tag, attribute name or nonce that cannot be written in HTML (a mistake
|
|
68
|
+
* in the calling code); never for anything the network or Taggor does. Side effects: at most
|
|
69
|
+
* one request, none within `cacheSeconds` of an identical one.
|
|
70
|
+
*/
|
|
71
|
+
render(tag: string, attributes?: Readonly<Record<string, AttributeValue>>, options?: RenderOptions): Promise<string>;
|
|
72
|
+
/** The bare tag alone, with no request: what `render` falls back to. */
|
|
73
|
+
element(tag: string, attributes?: Readonly<Record<string, AttributeValue>>, options?: Pick<RenderOptions, "lang">): string;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Creates the helper of one site.
|
|
77
|
+
*
|
|
78
|
+
* Inputs: `TaggorServerOptions`. Output: a `TaggorServer`. Errors: throws a `TypeError` when the
|
|
79
|
+
* origin is not an `https:` URL (or `http:` on a loopback host) without a path, the site key is
|
|
80
|
+
* malformed, or the server key is absent or not shaped like one (the message never quotes it), so a
|
|
81
|
+
* misconfiguration shows at startup and not as a silently missing fragment. Side effects: none
|
|
82
|
+
* until `render`; then requests to the origin, each with `Authorization: Bearer <server key>`, and
|
|
83
|
+
* an in-memory cache of at most 500 entries.
|
|
84
|
+
*/
|
|
85
|
+
export declare function createTaggorServer(options: TaggorServerOptions): TaggorServer;
|
|
86
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@taggor/server` (SSR spike, ADR 0066): the helper a site with a server uses to put a Taggor
|
|
3
|
+
* component in its first HTML response.
|
|
4
|
+
*
|
|
5
|
+
* `render(tag, attributes)` asks the Taggor edge for the component's server-rendered fragment
|
|
6
|
+
* (`GET <origin>/r/<siteKey>/<tag>?<attributes>`) and returns HTML to write where the tag would
|
|
7
|
+
* go: the element with its shadow root already filled, which the browser shows before any script
|
|
8
|
+
* and the Taggor runtime then takes over. Whatever goes wrong (Taggor slow or down, the route
|
|
9
|
+
* off, a component that cannot render on a server), it returns the bare tag instead, exactly what
|
|
10
|
+
* the page has without this helper, and the component renders in the browser as it always did.
|
|
11
|
+
* The site's snippet (`/s/<siteKey>.js`) stays as it is; this adds nothing to the browser.
|
|
12
|
+
*
|
|
13
|
+
* Server key (spike, ADR 0066, no ticket): every request carries the site's server key
|
|
14
|
+
* (`tgs_live_…`, created in the portal's Install > SSR tab or through `POST /v1/sites/{id}/server-keys`)
|
|
15
|
+
* as `Authorization: Bearer <key>`; without a valid one the edge refuses and this helper writes the
|
|
16
|
+
* bare tag. The key is a server secret: read it from the server's environment
|
|
17
|
+
* (`process.env.TAGGOR_SERVER_KEY`), never put it in browser code or in the repository. It is
|
|
18
|
+
* checked for shape when the helper is created and never appears in an error message or a URL.
|
|
19
|
+
*
|
|
20
|
+
* No dependency and no framework: the result is a string. Where it goes is the framework's raw
|
|
21
|
+
* HTML output (the public page /docs/ssr/, apps/site/docs-src/sources/ssr.md, has tested examples for
|
|
22
|
+
* Next.js, Astro, Express, React Router, SvelteKit, Nuxt and Flask; README.md is this package's guide).
|
|
23
|
+
*/
|
|
24
|
+
const TAG_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/;
|
|
25
|
+
const ATTRIBUTE_NAME = /^[a-z][a-z0-9-]{0,63}$/;
|
|
26
|
+
const SITE_KEY = /^[A-Za-z0-9_-]{1,64}$/;
|
|
27
|
+
/**
|
|
28
|
+
* The shape of a server key: prefix, 32 random base62 characters and a 6-character checksum. This
|
|
29
|
+
* package has no dependency, so the checksum itself is left to the edge (`@taggor/contract`'s
|
|
30
|
+
* `parseServerKey` holds the full rule); the shape is enough to catch a missing or pasted-wrong key.
|
|
31
|
+
*/
|
|
32
|
+
const SERVER_KEY = /^tgs_(?:live|test)_[0-9A-Za-z]{38}$/;
|
|
33
|
+
const NONCE = /^[A-Za-z0-9+/_=-]{1,256}$/;
|
|
34
|
+
const TEMPLATE_OPEN = /^<template shadowrootmode="open"(?: shadowrootdelegatesfocus)?>/;
|
|
35
|
+
/** A fragment larger than this is not used (the edge's own ceiling is lower). */
|
|
36
|
+
const MAX_FRAGMENT_CHARS = 1024 * 1024;
|
|
37
|
+
const MAX_CACHE_ENTRIES = 500;
|
|
38
|
+
/** A failure is remembered this long, so an outage costs one slow request, not one per page. */
|
|
39
|
+
const FAILURE_CACHE_MS = 5000;
|
|
40
|
+
/** The longest query the route accepts (apps/edge domain/fragment.ts); longer is never asked. */
|
|
41
|
+
const MAX_QUERY_CHARS = 8192;
|
|
42
|
+
const escapeAttribute = (value) => value
|
|
43
|
+
.replaceAll("&", "&")
|
|
44
|
+
.replaceAll('"', """)
|
|
45
|
+
.replaceAll("<", "<")
|
|
46
|
+
.replaceAll(">", ">");
|
|
47
|
+
/** The attributes as text, sorted by name; throws for a name HTML cannot hold. */
|
|
48
|
+
function textAttributes(attributes, lang) {
|
|
49
|
+
const given = Object.entries(attributes);
|
|
50
|
+
// The page language wins over a `lang` written among the attributes.
|
|
51
|
+
const all = lang
|
|
52
|
+
? [...given.filter(([name]) => name !== "lang"), ["lang", lang]]
|
|
53
|
+
: given;
|
|
54
|
+
const entries = [];
|
|
55
|
+
for (const [name, value] of all) {
|
|
56
|
+
if (!ATTRIBUTE_NAME.test(name)) {
|
|
57
|
+
throw new TypeError(`@taggor/server: "${name}" is not a lowercase attribute name`);
|
|
58
|
+
}
|
|
59
|
+
if (value === false || value === null || value === undefined)
|
|
60
|
+
continue;
|
|
61
|
+
const text = value === true
|
|
62
|
+
? ""
|
|
63
|
+
: typeof value === "object"
|
|
64
|
+
? JSON.stringify(value)
|
|
65
|
+
: typeof value === "number"
|
|
66
|
+
? String(value)
|
|
67
|
+
: value;
|
|
68
|
+
entries.push([name, text]);
|
|
69
|
+
}
|
|
70
|
+
return entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
71
|
+
}
|
|
72
|
+
function bareTag(tag, attributes) {
|
|
73
|
+
const text = attributes
|
|
74
|
+
.map(([name, value]) => (value === "" ? ` ${name}` : ` ${name}="${escapeAttribute(value)}"`))
|
|
75
|
+
.join("");
|
|
76
|
+
return `<${tag}${text}></${tag}>`;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Adds the page's nonce to the `<style>` elements the fragment starts with. Only those: the scan
|
|
80
|
+
* walks from the template's opening tag over consecutive `<style>…</style>` pairs (the edge
|
|
81
|
+
* escapes `</style` inside CSS) and stops at the first thing that is not one, so a `<style>` a
|
|
82
|
+
* component renders in its own markup is never touched.
|
|
83
|
+
*/
|
|
84
|
+
function withNonce(fragment, nonce) {
|
|
85
|
+
const start = fragment.indexOf("<template ");
|
|
86
|
+
const open = start < 0 ? null : TEMPLATE_OPEN.exec(fragment.slice(start));
|
|
87
|
+
if (start < 0 || open === null)
|
|
88
|
+
return fragment;
|
|
89
|
+
let position = start + open[0].length;
|
|
90
|
+
let output = fragment.slice(0, position);
|
|
91
|
+
while (fragment.startsWith("<style>", position)) {
|
|
92
|
+
const end = fragment.indexOf("</style>", position);
|
|
93
|
+
if (end < 0)
|
|
94
|
+
break;
|
|
95
|
+
output += `<style nonce="${nonce}">${fragment.slice(position + 7, end + 8)}`;
|
|
96
|
+
position = end + 8;
|
|
97
|
+
}
|
|
98
|
+
return output + fragment.slice(position);
|
|
99
|
+
}
|
|
100
|
+
/** Whether a body is a fragment of `tag`: the element, with a declarative shadow root, whole. */
|
|
101
|
+
function isFragmentOf(tag, html) {
|
|
102
|
+
if (html.length > MAX_FRAGMENT_CHARS || !html.endsWith(`</${tag}>`))
|
|
103
|
+
return false;
|
|
104
|
+
if (!html.startsWith(`<${tag} `) && !html.startsWith(`<${tag}>`))
|
|
105
|
+
return false;
|
|
106
|
+
const close = html.indexOf(">");
|
|
107
|
+
return TEMPLATE_OPEN.test(html.slice(close + 1));
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Creates the helper of one site.
|
|
111
|
+
*
|
|
112
|
+
* Inputs: `TaggorServerOptions`. Output: a `TaggorServer`. Errors: throws a `TypeError` when the
|
|
113
|
+
* origin is not an `https:` URL (or `http:` on a loopback host) without a path, the site key is
|
|
114
|
+
* malformed, or the server key is absent or not shaped like one (the message never quotes it), so a
|
|
115
|
+
* misconfiguration shows at startup and not as a silently missing fragment. Side effects: none
|
|
116
|
+
* until `render`; then requests to the origin, each with `Authorization: Bearer <server key>`, and
|
|
117
|
+
* an in-memory cache of at most 500 entries.
|
|
118
|
+
*/
|
|
119
|
+
export function createTaggorServer(options) {
|
|
120
|
+
let origin;
|
|
121
|
+
try {
|
|
122
|
+
origin = new URL(options.origin);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
throw new TypeError("@taggor/server: `origin` is not a URL");
|
|
126
|
+
}
|
|
127
|
+
const loopback = ["127.0.0.1", "localhost", "[::1]"].includes(origin.hostname);
|
|
128
|
+
if (!(origin.protocol === "https:" || (origin.protocol === "http:" && loopback)) ||
|
|
129
|
+
origin.pathname !== "/" ||
|
|
130
|
+
origin.search !== "" ||
|
|
131
|
+
origin.username !== "") {
|
|
132
|
+
throw new TypeError("@taggor/server: `origin` must be an https origin, without a path");
|
|
133
|
+
}
|
|
134
|
+
if (!SITE_KEY.test(options.siteKey))
|
|
135
|
+
throw new TypeError("@taggor/server: malformed `siteKey`");
|
|
136
|
+
// Read as unknown: a JavaScript caller may pass anything.
|
|
137
|
+
const serverKey = options.serverKey;
|
|
138
|
+
if (serverKey === undefined || serverKey === null || serverKey === "") {
|
|
139
|
+
throw new TypeError("@taggor/server: `serverKey` is missing; set it from the server's environment (TAGGOR_SERVER_KEY)");
|
|
140
|
+
}
|
|
141
|
+
if (typeof serverKey !== "string" || !SERVER_KEY.test(serverKey)) {
|
|
142
|
+
throw new TypeError("@taggor/server: `serverKey` is not a Taggor server key (tgs_live_…)");
|
|
143
|
+
}
|
|
144
|
+
const authorization = `Bearer ${serverKey}`;
|
|
145
|
+
const now = options.now ?? Date.now;
|
|
146
|
+
const timeoutMs = options.timeoutMs ?? 300;
|
|
147
|
+
const cacheMs = (options.cacheSeconds ?? 60) * 1000;
|
|
148
|
+
/** `html: null` remembers a failure. Insertion order is age: the first key is the oldest. */
|
|
149
|
+
const cache = new Map();
|
|
150
|
+
const pending = new Map();
|
|
151
|
+
const remember = (url, html) => {
|
|
152
|
+
const ttl = html === null ? Math.min(FAILURE_CACHE_MS, cacheMs) : cacheMs;
|
|
153
|
+
if (ttl <= 0)
|
|
154
|
+
return;
|
|
155
|
+
cache.delete(url);
|
|
156
|
+
if (cache.size >= MAX_CACHE_ENTRIES) {
|
|
157
|
+
const oldest = cache.keys().next();
|
|
158
|
+
if (!oldest.done)
|
|
159
|
+
cache.delete(oldest.value);
|
|
160
|
+
}
|
|
161
|
+
cache.set(url, { html, expires: now() + ttl });
|
|
162
|
+
};
|
|
163
|
+
/** One request: the fragment, or `null` for anything else. Never rejects. */
|
|
164
|
+
const request = async (tag, url) => {
|
|
165
|
+
try {
|
|
166
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
167
|
+
headers: { accept: "text/html", authorization },
|
|
168
|
+
// The route never redirects; one that did would hand the server key to another place.
|
|
169
|
+
// "manual", not "error": workerd (Next.js on Workers) does not implement "error"; a 3xx is
|
|
170
|
+
// then just a status that is not 200, which is the bare tag.
|
|
171
|
+
redirect: "manual",
|
|
172
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
173
|
+
});
|
|
174
|
+
if (response.status !== 200)
|
|
175
|
+
return null;
|
|
176
|
+
if (!(response.headers.get("content-type") ?? "").startsWith("text/html"))
|
|
177
|
+
return null;
|
|
178
|
+
const html = await response.text();
|
|
179
|
+
return isFragmentOf(tag, html) ? html : null;
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
const fragmentOf = (tag, url) => {
|
|
186
|
+
const known = cache.get(url);
|
|
187
|
+
if (known !== undefined && known.expires > now())
|
|
188
|
+
return Promise.resolve(known.html);
|
|
189
|
+
let flight = pending.get(url);
|
|
190
|
+
if (flight === undefined) {
|
|
191
|
+
flight = request(tag, url).then((html) => {
|
|
192
|
+
pending.delete(url);
|
|
193
|
+
remember(url, html);
|
|
194
|
+
return html;
|
|
195
|
+
});
|
|
196
|
+
pending.set(url, flight);
|
|
197
|
+
}
|
|
198
|
+
return flight;
|
|
199
|
+
};
|
|
200
|
+
const checked = (tag) => {
|
|
201
|
+
if (!TAG_NAME.test(tag) || tag.length > 64) {
|
|
202
|
+
throw new TypeError(`@taggor/server: "${tag}" is not a custom element name`);
|
|
203
|
+
}
|
|
204
|
+
return tag;
|
|
205
|
+
};
|
|
206
|
+
return {
|
|
207
|
+
element: (tag, attributes = {}, renderOptions = {}) => bareTag(checked(tag), textAttributes(attributes, renderOptions.lang)),
|
|
208
|
+
async render(tag, attributes = {}, renderOptions = {}) {
|
|
209
|
+
const text = textAttributes(attributes, renderOptions.lang);
|
|
210
|
+
const bare = bareTag(checked(tag), text);
|
|
211
|
+
const { nonce } = renderOptions;
|
|
212
|
+
if (nonce !== undefined && !NONCE.test(nonce)) {
|
|
213
|
+
throw new TypeError("@taggor/server: `nonce` is not a base64 value");
|
|
214
|
+
}
|
|
215
|
+
if (options.ssr === false || renderOptions.ssr === false)
|
|
216
|
+
return bare;
|
|
217
|
+
const url = new URL(`/r/${options.siteKey}/${tag}`, origin);
|
|
218
|
+
for (const [name, value] of text)
|
|
219
|
+
url.searchParams.set(name, value);
|
|
220
|
+
// The route would answer 404 for a longer query, every 5 s: the bare tag, with no request.
|
|
221
|
+
if (url.search.length > MAX_QUERY_CHARS)
|
|
222
|
+
return bare;
|
|
223
|
+
const html = await fragmentOf(tag, url.href);
|
|
224
|
+
if (html === null)
|
|
225
|
+
return bare;
|
|
226
|
+
return nonce === undefined ? html : withNonce(html, nonce);
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@taggor/server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Server helper for sites that render HTML on a server: asks the Taggor edge for a component's server-rendered fragment and falls back to the bare tag.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"taggor",
|
|
7
|
+
"ssr",
|
|
8
|
+
"server-side-rendering",
|
|
9
|
+
"declarative-shadow-dom",
|
|
10
|
+
"web-components"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"homepage": "https://taggor.dev/docs/",
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"type": "module",
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"main": "./dist/index.js",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"!dist/**/*.map",
|
|
33
|
+
"!dist/.tsbuildinfo"
|
|
34
|
+
],
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@taggor/config": "0.0.0",
|
|
37
|
+
"@types/node": "26.6.5"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsc -b tsconfig.build.json",
|
|
41
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
42
|
+
"lint": "eslint . --max-warnings 0",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"test:coverage": "vitest run --coverage"
|
|
45
|
+
}
|
|
6
46
|
}
|