@softr/sdk 0.0.101-seo.0 → 0.0.102

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.
Files changed (40) hide show
  1. package/dist/auth/context.d.ts +0 -5
  2. package/dist/auth/isomorphic.d.ts +1 -2
  3. package/dist/auth/isomorphic.js +4 -4
  4. package/dist/auth/session.js +1 -11
  5. package/dist/cache.js +25 -0
  6. package/dist/formatting.d.ts +13 -10
  7. package/dist/formatting.js +11 -6
  8. package/dist/index.d.ts +3 -2
  9. package/dist/index.js +3 -2
  10. package/dist/mcp.d.ts +2 -2
  11. package/dist/package.js +1 -1
  12. package/dist/push.d.ts +52 -0
  13. package/dist/push.js +295 -0
  14. package/dist/pwa.js +8 -19
  15. package/dist/route/page.d.ts +3 -41
  16. package/dist/route/page.js +25 -102
  17. package/dist/server.d.ts +1 -3
  18. package/dist/server.js +1 -3
  19. package/package.json +10 -33
  20. package/skills/softr-sdk/SKILL.md +7 -8
  21. package/skills/softr-sdk/ai/SKILL.md +2 -2
  22. package/skills/softr-sdk/auth/SKILL.md +1 -1
  23. package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
  24. package/skills/softr-sdk/current-user/SKILL.md +1 -1
  25. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  26. package/skills/softr-sdk/formatting/SKILL.md +3 -3
  27. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  28. package/skills/softr-sdk/mcp/SKILL.md +1 -1
  29. package/skills/softr-sdk/push-notifications/SKILL.md +140 -0
  30. package/skills/softr-sdk/pwa/SKILL.md +1 -1
  31. package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
  32. package/skills/softr-sdk/record-queries/SKILL.md +1 -1
  33. package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
  34. package/skills/softr-sdk/routes-and-visibility/SKILL.md +4 -90
  35. package/skills/softr-sdk/workflows/SKILL.md +1 -1
  36. package/dist/auth/session.d.ts +0 -14
  37. package/dist/origin.js +0 -16
  38. package/dist/sitemap.d.ts +0 -35
  39. package/dist/sitemap.js +0 -56
  40. package/skills/softr-sdk/sitemap/SKILL.md +0 -112
@@ -0,0 +1,140 @@
1
+ ---
2
+ name: push-notifications
3
+ description: >-
4
+ Let signed-in visitors turn on push notifications: usePushNotifications for
5
+ the prompt, its states and the Studio texts, the PushNotifications and
6
+ PushPrompt types, and how to check that push is on for the app. Notifications
7
+ are sent by Softr Workflows, never by app code; the service worker is already
8
+ served, never write one.
9
+ metadata:
10
+ type: sub-skill
11
+ library: softr-sdk
12
+ library_version: 0.0.102
13
+ ---
14
+
15
+ # Push notifications
16
+
17
+ The builder turns push on in Studio, under Users → Notifications, for desktop, mobile or both, and writes the prompt's texts there. Notifications are sent by a Softr Workflow's "Send notification" action, which the builder sets up in Studio. What the app adds is one thing: a prompt that lets the signed-in visitor turn notifications on in this browser.
18
+
19
+ > **CRITICAL**: Never write a service worker, a `public/sw.js`, or any `navigator.serviceWorker`, `PushManager` or `Notification` code of your own. The app already serves its service worker, and `usePushNotifications()` registers it, subscribes and unsubscribes.
20
+ >
21
+ > **CRITICAL**: Never send a push from app code. Sending is a Softr Workflow's "Send notification" action. When the builder asks for "notify X when Y", point them to that workflow; when Y is something the app does, the app triggers the workflow (load the Softr SDK `workflows` guidance). The app itself adds only the prompt.
22
+
23
+ ## Setup
24
+
25
+ ```ts
26
+ import { usePushNotifications } from '@softr/sdk'
27
+ import type { PushNotifications, PushPrompt } from '@softr/sdk'
28
+ ```
29
+
30
+ ```ts
31
+ type PushPrompt = {
32
+ title: string | null // what the builder wrote in Studio; any of these may be missing
33
+ message: string | null
34
+ enableButtonLabel: string | null
35
+ }
36
+
37
+ type PushNotifications =
38
+ | { status: 'unavailable' } // loading, signed out, push off, this device type off, or no browser support
39
+ | { status: 'install-first'; prompt: PushPrompt } // iPhone and iPad: push works only in the installed app
40
+ | {
41
+ status: 'ask'
42
+ prompt: PushPrompt
43
+ dismissed: boolean // skipped recently, within the builder's skip days; hide the prompt
44
+ subscribe: () => Promise<void> // call from a click
45
+ dismiss: () => void
46
+ }
47
+ | { status: 'subscribed'; unsubscribe: () => Promise<void> }
48
+ | { status: 'blocked' } // blocked in the browser; only the visitor can undo it there
49
+ ```
50
+
51
+ ## Is push on for the app?
52
+
53
+ Ask the running app for `/_softr/push.json`: `200` means push is on, `404` means it is off in Studio or the plan does not include it. Do not build a prompt against a `404`: push has to be turned on first. A change in Studio can take up to two minutes to reach the app.
54
+
55
+ Push works only on the published app. Inside the Studio preview the hook always says `unavailable`, so the prompt never shows there. That is expected, not a bug to fix.
56
+
57
+ ## Core Patterns
58
+
59
+ ### The prompt
60
+
61
+ Render it once, in `RootDocument` in `src/routes/__root.tsx`, so it shows on every page and the browser stays registered for the visitor. Use the prompt component the template ships when it has one. It shows only on `ask`, and shows nothing on `install-first`: on iPhone and iPad, the app's install button does that job (load the Softr SDK `pwa` guidance).
62
+
63
+ Call `usePushNotifications()` in that one component only. Each call keeps state of its own: a second call, in a header or on a settings page, does not see a subscribe made through the first, so the prompt would stay on screen after the visitor said yes.
64
+
65
+ `subscribe()` rejects when the browser or Softr refuses. Catch it and tell the visitor, so the button never fails in silence.
66
+
67
+ ```tsx
68
+ function EnableNotifications() {
69
+ const push = usePushNotifications()
70
+ if (push.status !== 'ask' || push.dismissed) return null
71
+ return (
72
+ <div role="dialog">
73
+ <p>{push.prompt.title ?? 'Turn on notifications'}</p>
74
+ <p>{push.prompt.message ?? 'Get notified about updates.'}</p>
75
+ <button onClick={() => push.subscribe().catch(() => toast.error('Notifications could not be turned on.'))}>
76
+ {push.prompt.enableButtonLabel ?? 'Turn on'}
77
+ </button>
78
+ <button onClick={push.dismiss}>Not now</button>
79
+ </div>
80
+ )
81
+ }
82
+ ```
83
+
84
+ Fall back to your own wording only where the builder left a text empty. On `install-first`, point the visitor to installing the app (load the Softr SDK `pwa` guidance); do not ask for permission.
85
+
86
+ ### Signing out
87
+
88
+ Nothing to add. The browser keeps its subscription when the visitor signs out, so signing back in does not ask again.
89
+
90
+ ## Common Mistakes
91
+
92
+ ### CRITICAL Asking for permission on page load
93
+
94
+ Wrong:
95
+
96
+ ```tsx
97
+ useEffect(() => { push.status === 'ask' && push.subscribe() }, [push.status])
98
+ ```
99
+
100
+ Correct:
101
+
102
+ ```tsx
103
+ <button onClick={() => push.subscribe().catch(() => toast.error('Notifications could not be turned on.'))}>
104
+ {push.prompt.enableButtonLabel ?? 'Turn on'}
105
+ </button>
106
+ ```
107
+
108
+ Browsers ignore or block a permission request that no click started, and a visitor who blocks it can only undo that in the browser's settings.
109
+
110
+ Source: packages/sdk/src/push.ts
111
+
112
+ ### HIGH Showing the prompt whatever the status
113
+
114
+ Wrong:
115
+
116
+ ```tsx
117
+ const push = usePushNotifications()
118
+ return <button onClick={() => push.subscribe()}>Turn on notifications</button>
119
+ ```
120
+
121
+ Correct:
122
+
123
+ ```tsx
124
+ const push = usePushNotifications()
125
+ if (push.status !== 'ask' || push.dismissed) return null
126
+ return (
127
+ <button onClick={() => push.subscribe().catch(() => toast.error('Notifications could not be turned on.'))}>
128
+ {push.prompt.enableButtonLabel ?? 'Turn on'}
129
+ </button>
130
+ )
131
+ ```
132
+
133
+ The hook says `unavailable` when push is off in Studio, for this device type, or for a signed-out visitor. A prompt that skips the check shows in all of those, and on iPhone it asks for something the browser cannot give.
134
+
135
+ Source: packages/sdk/src/push.ts
136
+
137
+ ## References
138
+
139
+ - [SKILL.md](../SKILL.md): the entrypoints and which one each export lives on
140
+ - [pwa/SKILL.md](../pwa/SKILL.md): installing the app, which iPhone and iPad need before push
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.101-seo.0
12
+ library_version: 0.0.102
13
13
  ---
14
14
 
15
15
  # Installing the app
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.101-seo.0
12
+ library_version: 0.0.102
13
13
  ---
14
14
 
15
15
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineMutation` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 0.0.101-seo.0
13
+ library_version: 0.0.102
14
14
  ---
15
15
 
16
16
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. The same holds for any helper that calls `ds`: declare it inside the handler. A function at module level that calls `ds` keeps the server-only import in the browser bundle, and every page stops loading until it moves. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.101-seo.0
12
+ library_version: 0.0.102
13
13
  ---
14
14
 
15
15
  **Boundary.** `Audience` and `defineVisibility` come from `@softr/sdk` and work anywhere.
@@ -5,16 +5,14 @@ description: >-
5
5
  (LOGGED_IN_USERS, NON_LOGGED_IN_USERS and customGroups) and its title,
6
6
  guardRoute or assertRouteAccess in beforeLoad, pageHead in head, isAuthorized
7
7
  and checkAccess anywhere, rendering an access error, and the lint rules that
8
- require the declaration. Also a head built from the loader's data with
9
- pageHead, the canonical and social tags every page gets, excerpt for a
10
- description taken from a record, and jsonLdScript for structured data.
8
+ require the declaration.
11
9
  metadata:
12
10
  type: sub-skill
13
11
  library: softr-sdk
14
- library_version: 0.0.101-seo.0
12
+ library_version: 0.0.102
15
13
  ---
16
14
 
17
- **Boundary.** `definePage`, `pageHead`, `excerpt`, `jsonLdScript`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
15
+ **Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
18
16
 
19
17
  # Route visibility
20
18
 
@@ -52,7 +50,7 @@ These constraints hold, because Softr reads the file rather than running it:
52
50
  - The import must be a direct named import from `@softr/sdk`.
53
51
  - A route file has one `definePage`. The route names it in `beforeLoad` and in `head`. A page imported from elsewhere is rejected.
54
52
  - Every value inside the literal is written there too. A group id taken from a `const`, a spread or an import still type-checks, but Studio can no longer change that setting. Repeat the id on each route, even when two routes share it.
55
- - The literals are the page's fallbacks. A title or description that comes from the route's data goes in a `head` written after `loader`, as [Head tags from the route's data](#head-tags-from-the-routes-data) shows.
53
+ - A head setting that depends on the route's data is a function of its head context: `title: ({ loaderData }) => loaderData?.name`.
56
54
  - Never state `visibility` on `__root.tsx`. The root cannot carry an audience, so a rule there would gate nothing while looking like it does. Its `definePage` holds the app-wide head defaults only. Put the rule on a layout below the root instead.
57
55
 
58
56
  `userGroupTypes` is a set, so a rule names one audience or several:
@@ -231,93 +229,9 @@ function StaffNote() {
231
229
 
232
230
  To show or hide a part of a page, `Audience` is simpler: see [region-visibility/SKILL.md](../region-visibility/SKILL.md).
233
231
 
234
- ### Tags every page gets
235
-
236
- `pageHead` renders these from the settings, unless the page sets its own:
237
-
238
- | Tag | Value | Set your own with |
239
- | --- | --- | --- |
240
- | `<link rel="canonical">` | the page's own full URL, with no trailing slash and only the `page` query parameter kept | `canonicalUrl` |
241
- | `og:url` | the same URL as the canonical | follows `canonicalUrl` |
242
- | `og:title` | `title` | `socialTitle` |
243
- | `og:description` | `description` | `socialDescription` |
244
- | `og:image` | `socialImage` as a full URL | `socialImage` |
245
-
246
- Only the page the visitor is on renders a canonical and an `og:url`, never a layout above it. `canonicalUrl` takes a path, such as `'/pricing'`, or a full URL, rendered as written. A path in `socialImage` becomes a full URL the same way.
247
-
248
- Name a list's pagination search parameter `page`, so each page of the list keeps its own canonical: `/blog?page=2`.
249
-
250
- ### Head tags from the route's data
251
-
252
- A record page takes its title and description from the record. Write `head` after `loader` and call `pageHead` with the page's own settings spread in, then the values from `ctx.loaderData`. The literals in `definePage` stay as the fallbacks, used before the data loads and when it fails, and they are what Studio shows and edits.
253
-
254
- ```tsx
255
- import { createFileRoute, notFound } from '@tanstack/react-router'
256
- import { definePage, excerpt, guardRoute, pageHead } from '@softr/sdk'
257
- import { getArticle } from '#/server/articles.ts'
258
-
259
- const pageSettings = definePage({
260
- visibility: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] },
261
- title: 'Article | Acme',
262
- description: 'An article from the Acme blog.',
263
- })
264
-
265
- export const Route = createFileRoute('/blog/$articleId')({
266
- beforeLoad: guardRoute(pageSettings),
267
- loader: async ({ params }) => {
268
- const article = await getArticle({ data: { articleId: params.articleId } })
269
- if (article === null) throw notFound()
270
- return article
271
- },
272
- head: (ctx) =>
273
- pageHead({
274
- ...pageSettings,
275
- title: ctx.loaderData?.fields.title ? `${ctx.loaderData.fields.title} | Acme` : pageSettings.title,
276
- description: excerpt(ctx.loaderData?.fields.body) ?? pageSettings.description,
277
- })(ctx),
278
- component: Article,
279
- })
280
- ```
281
-
282
- `head` comes after `loader`, so `ctx.loaderData` carries the loader's types and a field the query does not declare fails to type check. Read the record's fields directly.
283
-
284
- `excerpt(text, maxLength = 155)` turns a long text field into a description: it drops markdown and HTML, collapses whitespace and cuts at a word boundary with an ellipsis. It takes `string | null | undefined` and returns `undefined` when nothing is left, so `?? pageSettings.description` picks the fallback.
285
-
286
- Keep `socialImage` to the page's own image or the app's. A record's attachment URL stops working within hours, long before link previews refresh.
287
-
288
- ### Structured data
289
-
290
- `jsonLdScript(data)` turns a schema.org object into a `head` script. It escapes the JSON so a record's text cannot break out of the script tag. Return it in `scripts` next to what `pageHead` gave:
291
-
292
- ```tsx
293
- head: (ctx) => {
294
- const article = ctx.loaderData
295
- const head = pageHead({
296
- ...pageSettings,
297
- title: article?.fields.title ? `${article.fields.title} | Acme` : pageSettings.title,
298
- description: excerpt(article?.fields.body) ?? pageSettings.description,
299
- })(ctx)
300
- if (article === undefined) return head
301
- return {
302
- ...head,
303
- scripts: [
304
- jsonLdScript({
305
- '@context': 'https://schema.org',
306
- '@type': 'Article',
307
- headline: article.fields.title,
308
- datePublished: article.fields.publishedAt,
309
- }),
310
- ],
311
- }
312
- },
313
- ```
314
-
315
- The landing page names the business the same way, with literals: an `Organization` with its name, logo and URL, and a `WebSite`.
316
-
317
232
  ## References
318
233
 
319
234
  - [current-user/SKILL.md](../current-user/SKILL.md): reading the visitor a guard has just admitted
320
235
  - [record-queries/SKILL.md](../record-queries/SKILL.md): a guard covers the page, not the server function behind it
321
236
  - [auth/SKILL.md](../auth/SKILL.md): `NON_LOGGED_IN_USERS` and the sign-in flow it fronts
322
237
  - [region-visibility/SKILL.md](../region-visibility/SKILL.md): showing part of a page to some of the visitors the route admits
323
- - [sitemap/SKILL.md](../sitemap/SKILL.md): listing the public pages, record pages included, in `/sitemap.xml`
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.101-seo.0
12
+ library_version: 0.0.102
13
13
  ---
14
14
 
15
15
  **Boundary.** `workflow` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineWorkflow` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -1,14 +0,0 @@
1
- import "./context.js";
2
-
3
- //#region src/auth/session.d.ts
4
-
5
- /**
6
- * Runs `fn` as a signed-out visitor, whoever sent the request, so every `ds`
7
- * read inside it returns only what a signed-out visitor may see.
8
- *
9
- * @example
10
- * const page = await asSignedOutVisitor(() => ds.list(articlesQuery).limit(100))
11
- */
12
- declare function asSignedOutVisitor<T>(fn: () => T): Promise<Awaited<T>>;
13
- //#endregion
14
- export { asSignedOutVisitor };
package/dist/origin.js DELETED
@@ -1,16 +0,0 @@
1
- import { requireDefined } from "./assertions.js";
2
-
3
- //#region src/origin.ts
4
- /** The app's primary origin when one is configured, else the origin `request` reached. */
5
- function appOrigin(request) {
6
- const primary = process.env.SOFTR_PRIMARY_ORIGIN;
7
- if (primary) return requireDefined(URL.parse(primary), `SOFTR_PRIMARY_ORIGIN is not a URL: ${primary}`).origin;
8
- const url = new URL(request.url);
9
- const proto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
10
- const protocol = proto === "https" || proto === "http" ? `${proto}:` : url.protocol;
11
- const host = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || url.host;
12
- return new URL(`${protocol}//${host}`).origin;
13
- }
14
-
15
- //#endregion
16
- export { appOrigin };
package/dist/sitemap.d.ts DELETED
@@ -1,35 +0,0 @@
1
- //#region src/sitemap.d.ts
2
- /** A page for {@link sitemapXml}: a path or full URL, or an object with the page's details. */
3
- type SitemapEntry = string | {
4
- loc: string;
5
- lastmod?: string | Date;
6
- changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
7
- priority?: number;
8
- alternateRefs?: Array<{
9
- href: string;
10
- hreflang: string;
11
- }>;
12
- images?: Array<{
13
- loc: string;
14
- caption?: string;
15
- title?: string;
16
- }>;
17
- news?: {
18
- publication: {
19
- name: string;
20
- language: string;
21
- };
22
- publicationDate: string | Date;
23
- title: string;
24
- };
25
- };
26
- /**
27
- * The sitemap response listing `entries`. A path resolves against the app's
28
- * origin, and a full URL is kept as written.
29
- *
30
- * @example
31
- * GET: ({ request }) => sitemapXml(request, ["/", "/pricing", { loc: "/blog", changefreq: "daily" }])
32
- */
33
- declare function sitemapXml(request: Request, entries: Array<SitemapEntry>): Response;
34
- //#endregion
35
- export { SitemapEntry, sitemapXml };
package/dist/sitemap.js DELETED
@@ -1,56 +0,0 @@
1
- import { assert } from "./assertions.js";
2
- import { appOrigin } from "./origin.js";
3
-
4
- //#region src/sitemap.ts
5
- const MAX_URLS = 5e4;
6
- /**
7
- * The sitemap response listing `entries`. A path resolves against the app's
8
- * origin, and a full URL is kept as written.
9
- *
10
- * @example
11
- * GET: ({ request }) => sitemapXml(request, ["/", "/pricing", { loc: "/blog", changefreq: "daily" }])
12
- */
13
- function sitemapXml(request, entries) {
14
- assert(entries.length <= MAX_URLS, `A sitemap lists at most ${MAX_URLS} URLs, got ${entries.length}.`);
15
- const origin = appOrigin(request);
16
- const url = (path) => escapeXml(new URL(path, origin).href);
17
- const date = (value) => escapeXml(value instanceof Date ? value.toISOString() : value);
18
- const pages = entries.map((entry) => typeof entry === "string" ? { loc: entry } : entry);
19
- const namespaces = [
20
- "xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"",
21
- ...pages.some((page) => page.alternateRefs?.length) ? ["xmlns:xhtml=\"http://www.w3.org/1999/xhtml\""] : [],
22
- ...pages.some((page) => page.images?.length) ? ["xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\""] : [],
23
- ...pages.some((page) => page.news !== void 0) ? ["xmlns:news=\"http://www.google.com/schemas/sitemap-news/0.9\""] : []
24
- ];
25
- const urls = pages.map((page) => [
26
- " <url>",
27
- ` <loc>${url(page.loc)}</loc>`,
28
- ...page.lastmod === void 0 ? [] : [` <lastmod>${date(page.lastmod)}</lastmod>`],
29
- ...page.changefreq === void 0 ? [] : [` <changefreq>${page.changefreq}</changefreq>`],
30
- ...page.priority === void 0 ? [] : [` <priority>${page.priority}</priority>`],
31
- ...(page.alternateRefs ?? []).map((ref) => ` <xhtml:link rel="alternate" hreflang="${escapeXml(ref.hreflang)}" href="${url(ref.href)}"/>`),
32
- ...(page.images ?? []).map((image) => {
33
- const caption = image.caption === void 0 ? "" : `<image:caption>${escapeXml(image.caption)}</image:caption>`;
34
- const title = image.title === void 0 ? "" : `<image:title>${escapeXml(image.title)}</image:title>`;
35
- return ` <image:image><image:loc>${url(image.loc)}</image:loc>${caption}${title}</image:image>`;
36
- }),
37
- ...(page.news === void 0 ? [] : [page.news]).map((news) => {
38
- return ` <news:news><news:publication>${`<news:name>${escapeXml(news.publication.name)}</news:name>`}${`<news:language>${escapeXml(news.publication.language)}</news:language>`}</news:publication>${`<news:publication_date>${date(news.publicationDate)}</news:publication_date>`}<news:title>${escapeXml(news.title)}</news:title></news:news>`;
39
- }),
40
- " </url>"
41
- ].join("\n"));
42
- const xml = [
43
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
44
- `<urlset ${namespaces.join(" ")}>`,
45
- ...urls,
46
- "</urlset>",
47
- ""
48
- ];
49
- return new Response(xml.join("\n"), { headers: { "content-type": "application/xml; charset=utf-8" } });
50
- }
51
- function escapeXml(value) {
52
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
53
- }
54
-
55
- //#endregion
56
- export { sitemapXml };
@@ -1,112 +0,0 @@
1
- ---
2
- name: sitemap
3
- description: >-
4
- Serve /sitemap.xml from a server route: sitemapXml from @softr/sdk/server
5
- turns a list of paths or entries into the response, one ds.list loop per
6
- public record route pages through nextOffset, and asSignedOutVisitor makes
7
- every read list only what a signed-out visitor may see. Covers the
8
- SitemapEntry fields and keeping the list in step with the app's public pages.
9
- metadata:
10
- type: sub-skill
11
- library: softr-sdk
12
- library_version: 0.0.101-seo.0
13
- ---
14
-
15
- **Boundary.** `sitemapXml`, `asSignedOutVisitor` and `ds` come from `@softr/sdk/server` and run only in server code: here, a route's server handler.
16
-
17
- # Sitemap
18
-
19
- The sitemap lists every page a signed-out visitor can open: the public static pages, and one URL per record on each public record page. The app builds it on each request, so a record added after publish is listed straight away.
20
-
21
- ## Setup
22
-
23
- ```ts
24
- import { asSignedOutVisitor, ds, sitemapXml } from '@softr/sdk/server'
25
- import type { SitemapEntry } from '@softr/sdk/server'
26
- ```
27
-
28
- ```ts
29
- sitemapXml(request: Request, entries: Array<SitemapEntry>): Response
30
- asSignedOutVisitor<T>(fn: () => T): Promise<Awaited<T>>
31
- ```
32
-
33
- ## Core Patterns
34
-
35
- ### The sitemap route
36
-
37
- ```ts
38
- // src/routes/sitemap[.]xml.ts
39
- import { createFileRoute } from '@tanstack/react-router'
40
- import { asSignedOutVisitor, ds, sitemapXml } from '@softr/sdk/server'
41
- import { articlesQuery } from '#/server/articles.ts'
42
- import { toolsQuery } from '#/server/tools.ts'
43
-
44
- export const Route = createFileRoute('/sitemap.xml')({
45
- server: {
46
- handlers: {
47
- GET: ({ request }) =>
48
- asSignedOutVisitor(async () => {
49
- const articlePaths: Array<string> = []
50
- let articleOffset: number | null = 0
51
- while (articleOffset !== null) {
52
- const page = await ds.list(articlesQuery).limit(100).offset(articleOffset)
53
- for (const article of page.records) articlePaths.push(`/blog/${article.fields.slug}`)
54
- articleOffset = page.nextOffset
55
- }
56
-
57
- const toolPaths: Array<string> = []
58
- let toolOffset: number | null = 0
59
- while (toolOffset !== null) {
60
- const page = await ds.list(toolsQuery).limit(100).offset(toolOffset)
61
- for (const tool of page.records) toolPaths.push(`/tools/${tool.id}`)
62
- toolOffset = page.nextOffset
63
- }
64
-
65
- return sitemapXml(request, ['/', '/pricing', '/blog', ...articlePaths, ...toolPaths])
66
- }),
67
- },
68
- },
69
- })
70
- ```
71
-
72
- - The `[.]` in the file name makes the route's path `/sitemap.xml`. The route has a server handler and no component.
73
- - List the public static pages by hand, as paths. A page behind sign-in stays out.
74
- - Add one loop per public record page. `ds.list` returns at most 100 records at a time, so each loop follows `nextOffset` until it is `null`. Build each path the way the record page's route builds it.
75
- - `asSignedOutVisitor` wraps the whole handler. Every `ds` read inside it returns what a signed-out visitor may see, whoever requested the sitemap, so the sitemap never lists a private record.
76
- - Each query a loop reads names `NON_LOGGED_IN_USERS` in its `permissions`, as the public record page's own query does.
77
- - A path becomes a full URL on the app's address. A full URL is kept as written.
78
-
79
- When the app gains or loses a public page or a public record page, change this route in the same edit.
80
-
81
- ### More than a path
82
-
83
- An entry is a path or an object. Use the object form for a page that needs more:
84
-
85
- ```ts
86
- type SitemapEntry =
87
- | string
88
- | {
89
- loc: string
90
- lastmod?: string | Date
91
- changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never'
92
- priority?: number
93
- alternateRefs?: Array<{ href: string; hreflang: string }>
94
- images?: Array<{ loc: string; caption?: string; title?: string }>
95
- news?: { publication: { name: string; language: string }; publicationDate: string | Date; title: string }
96
- }
97
- ```
98
-
99
- ```ts
100
- const articleEntries: Array<SitemapEntry> = []
101
- // inside the loop
102
- articleEntries.push({ loc: `/blog/${article.fields.slug}`, lastmod: article.fields.updatedAt ?? undefined })
103
- ```
104
-
105
- Set `lastmod` only from a date the record really holds, such as its last-updated field. Leave it out otherwise.
106
-
107
- A sitemap lists at most 50,000 URLs.
108
-
109
- ## References
110
-
111
- - [record-queries/SKILL.md](../record-queries/SKILL.md): declaring the query each loop reads, and `nextOffset`
112
- - [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md): which pages are public, and the canonical URL each page renders