@velocity-astro/cms-astro 0.0.0-stage → 0.1.0-beta.11

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 (154) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/bin/velocity-cms.mjs +6 -0
  4. package/dist/admin-files.d.ts +21 -0
  5. package/dist/admin-files.d.ts.map +1 -0
  6. package/dist/admin-files.js +83 -0
  7. package/dist/admin-files.js.map +1 -0
  8. package/dist/challenge.d.ts +35 -0
  9. package/dist/challenge.d.ts.map +1 -0
  10. package/dist/challenge.js +84 -0
  11. package/dist/challenge.js.map +1 -0
  12. package/dist/cli.d.ts +9 -0
  13. package/dist/cli.d.ts.map +1 -0
  14. package/dist/cli.js +76 -0
  15. package/dist/cli.js.map +1 -0
  16. package/dist/connection.d.ts +26 -0
  17. package/dist/connection.d.ts.map +1 -0
  18. package/dist/connection.js +87 -0
  19. package/dist/connection.js.map +1 -0
  20. package/dist/editor.d.ts +67 -0
  21. package/dist/editor.d.ts.map +1 -0
  22. package/dist/editor.js +194 -0
  23. package/dist/editor.js.map +1 -0
  24. package/dist/entry-page.d.ts +37 -0
  25. package/dist/entry-page.d.ts.map +1 -0
  26. package/dist/entry-page.js +56 -0
  27. package/dist/entry-page.js.map +1 -0
  28. package/dist/form-post.d.ts +114 -0
  29. package/dist/form-post.d.ts.map +1 -0
  30. package/dist/form-post.js +298 -0
  31. package/dist/form-post.js.map +1 -0
  32. package/dist/hosted.d.ts +76 -0
  33. package/dist/hosted.d.ts.map +1 -0
  34. package/dist/hosted.js +104 -0
  35. package/dist/hosted.js.map +1 -0
  36. package/dist/image-optimizer.d.ts +35 -0
  37. package/dist/image-optimizer.d.ts.map +1 -0
  38. package/dist/image-optimizer.js +76 -0
  39. package/dist/image-optimizer.js.map +1 -0
  40. package/dist/index.d.ts +34 -0
  41. package/dist/index.d.ts.map +1 -0
  42. package/dist/index.js +34 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/init.d.ts +35 -0
  45. package/dist/init.d.ts.map +1 -0
  46. package/dist/init.js +140 -0
  47. package/dist/init.js.map +1 -0
  48. package/dist/integration.d.ts +72 -0
  49. package/dist/integration.d.ts.map +1 -0
  50. package/dist/integration.js +143 -0
  51. package/dist/integration.js.map +1 -0
  52. package/dist/link.d.ts +32 -0
  53. package/dist/link.d.ts.map +1 -0
  54. package/dist/link.js +80 -0
  55. package/dist/link.js.map +1 -0
  56. package/dist/live-loader.d.ts +44 -0
  57. package/dist/live-loader.d.ts.map +1 -0
  58. package/dist/live-loader.js +98 -0
  59. package/dist/live-loader.js.map +1 -0
  60. package/dist/live-pages.d.ts +69 -0
  61. package/dist/live-pages.d.ts.map +1 -0
  62. package/dist/live-pages.js +94 -0
  63. package/dist/live-pages.js.map +1 -0
  64. package/dist/loader.d.ts +22 -0
  65. package/dist/loader.d.ts.map +1 -0
  66. package/dist/loader.js +62 -0
  67. package/dist/loader.js.map +1 -0
  68. package/dist/media-store.d.ts +61 -0
  69. package/dist/media-store.d.ts.map +1 -0
  70. package/dist/media-store.js +178 -0
  71. package/dist/media-store.js.map +1 -0
  72. package/dist/menu.d.ts +51 -0
  73. package/dist/menu.d.ts.map +1 -0
  74. package/dist/menu.js +81 -0
  75. package/dist/menu.js.map +1 -0
  76. package/dist/page-head.d.ts +23 -0
  77. package/dist/page-head.d.ts.map +1 -0
  78. package/dist/page-head.js +66 -0
  79. package/dist/page-head.js.map +1 -0
  80. package/dist/page-marks.d.ts +50 -0
  81. package/dist/page-marks.d.ts.map +1 -0
  82. package/dist/page-marks.js +90 -0
  83. package/dist/page-marks.js.map +1 -0
  84. package/dist/preview.d.ts +92 -0
  85. package/dist/preview.d.ts.map +1 -0
  86. package/dist/preview.js +192 -0
  87. package/dist/preview.js.map +1 -0
  88. package/dist/resend-mailer.d.ts +63 -0
  89. package/dist/resend-mailer.d.ts.map +1 -0
  90. package/dist/resend-mailer.js +116 -0
  91. package/dist/resend-mailer.js.map +1 -0
  92. package/dist/secret.d.ts +8 -0
  93. package/dist/secret.d.ts.map +1 -0
  94. package/dist/secret.js +17 -0
  95. package/dist/secret.js.map +1 -0
  96. package/dist/single.d.ts +18 -0
  97. package/dist/single.d.ts.map +1 -0
  98. package/dist/single.js +37 -0
  99. package/dist/single.js.map +1 -0
  100. package/dist/site-editor.d.ts +41 -0
  101. package/dist/site-editor.d.ts.map +1 -0
  102. package/dist/site-editor.js +140 -0
  103. package/dist/site-editor.js.map +1 -0
  104. package/dist/site-forms.d.ts +54 -0
  105. package/dist/site-forms.d.ts.map +1 -0
  106. package/dist/site-forms.js +100 -0
  107. package/dist/site-forms.js.map +1 -0
  108. package/dist/site-images.d.ts +17 -0
  109. package/dist/site-images.d.ts.map +1 -0
  110. package/dist/site-images.js +22 -0
  111. package/dist/site-images.js.map +1 -0
  112. package/dist/site-mail.d.ts +45 -0
  113. package/dist/site-mail.d.ts.map +1 -0
  114. package/dist/site-mail.js +84 -0
  115. package/dist/site-mail.js.map +1 -0
  116. package/dist/site-media.d.ts +22 -0
  117. package/dist/site-media.d.ts.map +1 -0
  118. package/dist/site-media.js +52 -0
  119. package/dist/site-media.js.map +1 -0
  120. package/dist/site-name.d.ts +9 -0
  121. package/dist/site-name.d.ts.map +1 -0
  122. package/dist/site-name.js +21 -0
  123. package/dist/site-name.js.map +1 -0
  124. package/dist/site-plugins.d.ts +10 -0
  125. package/dist/site-plugins.d.ts.map +1 -0
  126. package/dist/site-plugins.js +23 -0
  127. package/dist/site-plugins.js.map +1 -0
  128. package/dist/site-search.d.ts +12 -0
  129. package/dist/site-search.d.ts.map +1 -0
  130. package/dist/site-search.js +79 -0
  131. package/dist/site-search.js.map +1 -0
  132. package/dist/site-storage.d.ts +34 -0
  133. package/dist/site-storage.d.ts.map +1 -0
  134. package/dist/site-storage.js +118 -0
  135. package/dist/site-storage.js.map +1 -0
  136. package/package.json +56 -3
  137. package/routes/admin.ts +10 -0
  138. package/routes/api.ts +15 -0
  139. package/routes/auth.ts +10 -0
  140. package/routes/due.ts +12 -0
  141. package/routes/editor.ts +49 -0
  142. package/routes/form-client.js.ts +173 -0
  143. package/routes/media.ts +10 -0
  144. package/routes/pages.ts +13 -0
  145. package/routes/plugins.ts +10 -0
  146. package/routes/preview-client.js.ts +18 -0
  147. package/routes/published.ts +29 -0
  148. package/routes/schedule.ts +20 -0
  149. package/routes/search-client.js.ts +33 -0
  150. package/routes/search.json.ts +10 -0
  151. package/routes/share-image.png.ts +33 -0
  152. package/routes/sitemap-live.xml.ts +16 -0
  153. package/routes/sites.ts +11 -0
  154. package/routes/submit.ts +22 -0
@@ -0,0 +1,92 @@
1
+ import type { MiddlewareHandler } from 'astro';
2
+ import { type EntryData } from '@velocity-astro/cms-core';
3
+ /**
4
+ * What someone has typed into one entry and not saved yet. The editor sends it with a preview,
5
+ * so the page beside the form shows the form as it is now. It is drawn once, for the person who
6
+ * sent it, and kept nowhere.
7
+ */
8
+ export interface PreviewDraft {
9
+ /** The entry it is for. */
10
+ readonly id: string;
11
+ /** The entry's values as the form holds them, by field id. */
12
+ readonly data: EntryData;
13
+ /**
14
+ * Other entries tried along with it and not saved either: the site's settings, when their
15
+ * colours are being chosen beside the page. Each is shown in place of the saved entry, as the
16
+ * draft itself is.
17
+ */
18
+ readonly with?: readonly {
19
+ readonly id: string;
20
+ readonly data: EntryData;
21
+ }[];
22
+ }
23
+ /** True while the page being rendered is a preview: the loaders then read the versions being worked on. */
24
+ export declare const isPreview: () => boolean;
25
+ /** True while the page being rendered is the one beside the editor's form, which marks its sections so a click can find them. */
26
+ export declare const isEditorPreview: () => boolean;
27
+ /**
28
+ * The entry as the preview should show it: with what was typed and not saved, when the preview
29
+ * came with that for this entry. Any other entry, and any entry outside a preview, is given back
30
+ * as it is.
31
+ */
32
+ export declare function withPreviewDraft<T extends {
33
+ readonly id: string;
34
+ readonly data: EntryData;
35
+ }>(entry: T): T;
36
+ /**
37
+ * Notes where a link to an entry leads on the page beside the editor's form, so that page can
38
+ * find the button that goes there and offer to change it. Nothing is noted for a visitor's page.
39
+ */
40
+ export declare function noteLinkLeads(type: string, entry: string, href: string): void;
41
+ /** What `noteLinkLeads` was told for the page being drawn: the address by `<type>:<entry>`. */
42
+ export declare const linkLeads: () => Readonly<Record<string, string>>;
43
+ /** Runs `work` as a preview, for tests and for anything that draws a page outside a request. */
44
+ export declare const asPreview: <T>(work: () => T, draft?: PreviewDraft) => T;
45
+ /** The form field the editor sends a draft in. */
46
+ export declare const DRAFT_FIELD = "draft";
47
+ /**
48
+ * Reads the draft the editor posted with a preview. Nothing is read from a request that did not
49
+ * come from the site's own pages, is too large, or is not shaped like a draft: the page is then
50
+ * refused, never drawn from something half understood.
51
+ */
52
+ export declare function readPreviewDraft(request: Request, site: URL): Promise<PreviewDraft | null>;
53
+ /** The address of the script the page beside the editor's form runs. */
54
+ export declare const EDITOR_PREVIEW_SCRIPT = "/cms-preview.js";
55
+ /**
56
+ * Which script this version of the CMS sends, as a mark in its address. A page is drawn again
57
+ * with every change in the form, and a browser that kept the script runs it before the page is
58
+ * seen, so the page comes back where it was with no jump. The mark changes with the script, so
59
+ * a copy from before an upgrade is never run.
60
+ */
61
+ export declare const EDITOR_PREVIEW_VERSION: string;
62
+ /**
63
+ * Adds the script that lets a click on the page find its section in the form. It comes from the
64
+ * site itself, so the page's own rules allow it. Where the page's links to entries lead goes
65
+ * with it as data, which no browser runs.
66
+ *
67
+ * The page is drawn again with every change in the form, and must be seen only once it is back
68
+ * where it was. So the script is the last thing in the page and runs as soon as it is read, and
69
+ * the head asks the browser to show nothing before that (`rel="expect"`, which a browser that
70
+ * does not know it passes over).
71
+ */
72
+ export declare function addEditorScript(html: string, leads?: Readonly<Record<string, string>>): string;
73
+ /**
74
+ * Adds the token to every link that stays on the site, so the person can click around and stay
75
+ * in the preview. A token is digits, a dot and hex, so it needs no escaping.
76
+ */
77
+ export declare function keepPreviewInLinks(html: string, token: string): string;
78
+ /** Whether a request is for a page rendered now, which may show uploaded images. */
79
+ export declare const showsContent: (request: Request, pathname: string, isPrerendered: boolean) => boolean;
80
+ /**
81
+ * Turns a request with a valid preview token (`?preview=<token>`) into a preview. Without
82
+ * `VELOCITY_CMS_SECRET` there are no previews at all.
83
+ *
84
+ * The token stays in the address rather than in a cookie, on purpose. A cache, in this server or
85
+ * at a CDN, answers by address before any code runs: with a cookie it would hand the person the
86
+ * public page. An address with a token is one no cache has seen, and it is never stored.
87
+ *
88
+ * A preview is never cached and never indexed, and a request without a valid token is handled
89
+ * exactly as if this middleware were not there.
90
+ */
91
+ export declare const onRequest: MiddlewareHandler;
92
+ //# sourceMappingURL=preview.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preview.d.ts","sourceRoot":"","sources":["../src/preview.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,OAAO,CAAC;AAE/C,OAAO,EAAmC,KAAK,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAM3F;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,2BAA2B;IAC3B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,8DAA8D;IAC9D,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB;;;;OAIG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS;QAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAA;KAAE,EAAE,CAAC;CAC9E;AAUD,2GAA2G;AAC3G,eAAO,MAAM,SAAS,QAAO,OAA8C,CAAC;AAE5E,iIAAiI;AACjI,eAAO,MAAM,eAAe,QAAO,OAAqD,CAAC;AAEzF;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAA;CAAE,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAMzG;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAE7E;AAED,+FAA+F;AAC/F,eAAO,MAAM,SAAS,QAAO,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAA2D,CAAC;AAIxH,gGAAgG;AAChG,eAAO,MAAM,SAAS,GAAI,CAAC,EAAE,MAAM,MAAM,CAAC,EAAE,QAAQ,YAAY,KAAG,CAAyC,CAAC;AAM7G,kDAAkD;AAClD,eAAO,MAAM,WAAW,UAAU,CAAC;AAInC;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAyBhG;AAED,wEAAwE;AACxE,eAAO,MAAM,qBAAqB,oBAAoB,CAAC;AASvD;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,QAA8B,CAAC;AAElE;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAM,GAAG,MAAM,CASlG;AAcD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAMtE;AAID,oFAAoF;AACpF,eAAO,MAAM,YAAY,GAAI,SAAS,OAAO,EAAE,UAAU,MAAM,EAAE,eAAe,OAAO,KAAG,OACjB,CAAC;AAE1E;;;;;;;;;;GAUG;AACH,eAAO,MAAM,SAAS,EAAE,iBAkCvB,CAAC"}
@@ -0,0 +1,192 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { PREVIEW_BRIDGE_SCRIPT } from '@velocity-astro/cms-admin/page-bridge';
3
+ import { PREVIEW_PARAMETER, PreviewLinks } from '@velocity-astro/cms-core';
4
+ import { siteSecret } from './secret.js';
5
+ import { refreshUploadedImages } from './site-media.js';
6
+ const PARAMETER = PREVIEW_PARAMETER;
7
+ const previewing = new AsyncLocalStorage();
8
+ /** True while the page being rendered is a preview: the loaders then read the versions being worked on. */
9
+ export const isPreview = () => previewing.getStore() !== undefined;
10
+ /** True while the page being rendered is the one beside the editor's form, which marks its sections so a click can find them. */
11
+ export const isEditorPreview = () => previewing.getStore()?.draft !== undefined;
12
+ /**
13
+ * The entry as the preview should show it: with what was typed and not saved, when the preview
14
+ * came with that for this entry. Any other entry, and any entry outside a preview, is given back
15
+ * as it is.
16
+ */
17
+ export function withPreviewDraft(entry) {
18
+ const draft = previewing.getStore()?.draft;
19
+ if (!draft)
20
+ return entry;
21
+ if (draft.id === entry.id)
22
+ return { ...entry, data: draft.data };
23
+ const beside = draft.with?.find((other) => other.id === entry.id);
24
+ return beside ? { ...entry, data: beside.data } : entry;
25
+ }
26
+ /**
27
+ * Notes where a link to an entry leads on the page beside the editor's form, so that page can
28
+ * find the button that goes there and offer to change it. Nothing is noted for a visitor's page.
29
+ */
30
+ export function noteLinkLeads(type, entry, href) {
31
+ previewing.getStore()?.leads?.set(`${type}:${entry}`, href);
32
+ }
33
+ /** What `noteLinkLeads` was told for the page being drawn: the address by `<type>:<entry>`. */
34
+ export const linkLeads = () => Object.fromEntries(previewing.getStore()?.leads ?? []);
35
+ const started = (draft) => (draft ? { draft, leads: new Map() } : {});
36
+ /** Runs `work` as a preview, for tests and for anything that draws a page outside a request. */
37
+ export const asPreview = (work, draft) => previewing.run(started(draft), work);
38
+ /** The most a draft sent with a preview may weigh. A page's sections are text; a megabyte is a very long page. */
39
+ const DRAFT_LIMIT = 1_000_000;
40
+ /** The most other entries a draft may bring with it. */
41
+ const WITH_LIMIT = 4;
42
+ /** The form field the editor sends a draft in. */
43
+ export const DRAFT_FIELD = 'draft';
44
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
45
+ /**
46
+ * Reads the draft the editor posted with a preview. Nothing is read from a request that did not
47
+ * come from the site's own pages, is too large, or is not shaped like a draft: the page is then
48
+ * refused, never drawn from something half understood.
49
+ */
50
+ export async function readPreviewDraft(request, site) {
51
+ // The browser says where a request came from, and a page cannot change what it says. A proxy
52
+ // in front of the site may change the scheme the site sees, so the host is what is compared.
53
+ const origin = request.headers.get('Origin');
54
+ const isOwn = request.headers.get('Sec-Fetch-Site') === 'same-origin' || (origin !== null && URL.canParse(origin) && new URL(origin).host === site.host);
55
+ if (!isOwn)
56
+ return null;
57
+ if (!(request.headers.get('Content-Type') ?? '').startsWith('application/x-www-form-urlencoded'))
58
+ return null;
59
+ if (Number(request.headers.get('Content-Length') ?? 0) > DRAFT_LIMIT)
60
+ return null;
61
+ const body = await request.text();
62
+ if (body.length > DRAFT_LIMIT)
63
+ return null;
64
+ try {
65
+ const sent = JSON.parse(new URLSearchParams(body).get(DRAFT_FIELD) ?? '');
66
+ if (!isRecord(sent) || typeof sent['id'] !== 'string' || sent['id'] === '' || !isRecord(sent['data']))
67
+ return null;
68
+ const beside = sent['with'];
69
+ if (beside === undefined)
70
+ return { id: sent['id'], data: sent['data'] };
71
+ if (!Array.isArray(beside) || beside.length > WITH_LIMIT)
72
+ return null;
73
+ const others = [];
74
+ for (const other of beside) {
75
+ if (!isRecord(other) || typeof other['id'] !== 'string' || other['id'] === '' || !isRecord(other['data']))
76
+ return null;
77
+ others.push({ id: other['id'], data: other['data'] });
78
+ }
79
+ return { id: sent['id'], data: sent['data'], with: others };
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ /** The address of the script the page beside the editor's form runs. */
86
+ export const EDITOR_PREVIEW_SCRIPT = '/cms-preview.js';
87
+ /** A few letters that change whenever the script does. */
88
+ function mark(text) {
89
+ let sum = 5381;
90
+ for (let at = 0; at < text.length; at++)
91
+ sum = (Math.imul(sum, 33) ^ text.charCodeAt(at)) >>> 0;
92
+ return sum.toString(36);
93
+ }
94
+ /**
95
+ * Which script this version of the CMS sends, as a mark in its address. A page is drawn again
96
+ * with every change in the form, and a browser that kept the script runs it before the page is
97
+ * seen, so the page comes back where it was with no jump. The mark changes with the script, so
98
+ * a copy from before an upgrade is never run.
99
+ */
100
+ export const EDITOR_PREVIEW_VERSION = mark(PREVIEW_BRIDGE_SCRIPT);
101
+ /**
102
+ * Adds the script that lets a click on the page find its section in the form. It comes from the
103
+ * site itself, so the page's own rules allow it. Where the page's links to entries lead goes
104
+ * with it as data, which no browser runs.
105
+ *
106
+ * The page is drawn again with every change in the form, and must be seen only once it is back
107
+ * where it was. So the script is the last thing in the page and runs as soon as it is read, and
108
+ * the head asks the browser to show nothing before that (`rel="expect"`, which a browser that
109
+ * does not know it passes over).
110
+ */
111
+ export function addEditorScript(html, leads = {}) {
112
+ const said = Object.keys(leads).length > 0 ? `<script type="application/json" data-cms-links>${JSON.stringify(leads).replace(/</g, '\\u003c')}</script>` : '';
113
+ const tag = `${said}<script id="${EDITOR_SCRIPT_ID}" src="${EDITOR_PREVIEW_SCRIPT}?v=${EDITOR_PREVIEW_VERSION}"></script>`;
114
+ const end = html.lastIndexOf('</body>');
115
+ const whole = end === -1 ? html + tag : html.slice(0, end) + tag + html.slice(end);
116
+ const head = /<head(\s[^>]*)?>/i.exec(whole);
117
+ if (!head)
118
+ return whole;
119
+ const at = head.index + head[0].length;
120
+ return `${whole.slice(0, at)}<link rel="expect" href="#${EDITOR_SCRIPT_ID}" blocking="render">${whole.slice(at)}`;
121
+ }
122
+ const EDITOR_SCRIPT_ID = 'cms-preview-script';
123
+ /** A signer per secret, so a preview link made for one site is no link at all on another. */
124
+ const links = new Map();
125
+ function previewLinks() {
126
+ const secret = siteSecret();
127
+ if (!secret)
128
+ return null;
129
+ let signer = links.get(secret);
130
+ if (!signer)
131
+ links.set(secret, (signer = new PreviewLinks(secret)));
132
+ return signer;
133
+ }
134
+ /**
135
+ * Adds the token to every link that stays on the site, so the person can click around and stay
136
+ * in the preview. A token is digits, a dot and hex, so it needs no escaping.
137
+ */
138
+ export function keepPreviewInLinks(html, token) {
139
+ return html.replace(/(<a\b[^>]*?\shref=")(\/(?!\/)[^"#?]*)(\?[^"#]*)?(#[^"]*)?"/g, (_, start, path, query, hash) => `${start}${path}${query ? `${query}&amp;` : '?'}${PARAMETER}=${token}${hash ?? ''}"`);
140
+ }
141
+ const NOT_PAGES = /^\/(?:api|media|admin|og|_image|_astro|_server-islands|_actions)(?:\/|$)|\.[a-z0-9]+$/;
142
+ /** Whether a request is for a page rendered now, which may show uploaded images. */
143
+ export const showsContent = (request, pathname, isPrerendered) => !isPrerendered && request.method === 'GET' && !NOT_PAGES.test(pathname);
144
+ /**
145
+ * Turns a request with a valid preview token (`?preview=<token>`) into a preview. Without
146
+ * `VELOCITY_CMS_SECRET` there are no previews at all.
147
+ *
148
+ * The token stays in the address rather than in a cookie, on purpose. A cache, in this server or
149
+ * at a CDN, answers by address before any code runs: with a cookie it would hand the person the
150
+ * public page. An address with a token is one no cache has seen, and it is never stored.
151
+ *
152
+ * A preview is never cached and never indexed, and a request without a valid token is handled
153
+ * exactly as if this middleware were not there.
154
+ */
155
+ export const onRequest = async (context, next) => {
156
+ // A page built ahead of time is the same for everyone, so it is never a preview. On a server
157
+ // that runs many sites it is also built for no site, and has no secret to check a token with.
158
+ if (context.isPrerendered)
159
+ return next();
160
+ if (showsContent(context.request, context.url.pathname, context.isPrerendered)) {
161
+ // A page without its newest images is still a page, so a failure here is only logged.
162
+ await refreshUploadedImages().catch((error) => console.error('[velocity-cms] Uploaded images were not read.', error));
163
+ }
164
+ const signer = previewLinks();
165
+ const token = context.url.searchParams.get(PARAMETER);
166
+ if (!signer || token === null || !(await signer.verify(token)))
167
+ return next();
168
+ context.cache.set(false);
169
+ // The editor posts what is in its form, to see the page before saving. Only a preview takes a
170
+ // post, and only one it can read.
171
+ let draft;
172
+ if (context.request.method === 'POST' && !NOT_PAGES.test(context.url.pathname)) {
173
+ const sent = await readPreviewDraft(context.request.clone(), context.url);
174
+ if (!sent)
175
+ return new Response('This preview could not be read. Open it again from the editor.', { status: 400, headers: { 'Cache-Control': 'no-store' } });
176
+ draft = sent;
177
+ }
178
+ // The page is read to the end inside the preview, because Astro renders as the response is read.
179
+ return previewing.run(started(draft), async () => {
180
+ const response = await next();
181
+ const headers = new Headers(response.headers);
182
+ headers.set('Cache-Control', 'private, no-store');
183
+ headers.set('X-Robots-Tag', 'noindex');
184
+ headers.set('Referrer-Policy', 'same-origin');
185
+ headers.delete('Content-Length');
186
+ const isHtml = headers.get('Content-Type')?.includes('text/html') === true;
187
+ const page = isHtml ? keepPreviewInLinks(await response.text(), token) : null;
188
+ const body = page === null ? await response.arrayBuffer() : draft ? addEditorScript(page, linkLeads()) : page;
189
+ return new Response(body, { status: response.status, statusText: response.statusText, headers });
190
+ });
191
+ };
192
+ //# sourceMappingURL=preview.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preview.js","sourceRoot":"","sources":["../src/preview.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAkB,MAAM,0BAA0B,CAAC;AAC3F,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAExD,MAAM,SAAS,GAAG,iBAAiB,CAAC;AA0BpC,MAAM,UAAU,GAAG,IAAI,iBAAiB,EAAW,CAAC;AAEpD,2GAA2G;AAC3G,MAAM,CAAC,MAAM,SAAS,GAAG,GAAY,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,KAAK,SAAS,CAAC;AAE5E,iIAAiI;AACjI,MAAM,CAAC,MAAM,eAAe,GAAG,GAAY,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,EAAE,KAAK,KAAK,SAAS,CAAC;AAEzF;;;;GAIG;AACH,MAA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e,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC9G,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;IACnG,CAAC,CAAC,CAAC;AACL,CAAC,CAAC"}
@@ -0,0 +1,63 @@
1
+ import type { InvitationMail, Mailer, SignInMail } from '@velocity-astro/cms-auth';
2
+ import type { NoticeMailer, SubmissionNotice } from './form-post.js';
3
+ /** The words of the emails. Give your own to send them in another language. */
4
+ export interface MailWords {
5
+ readonly signInSubject: (siteName: string) => string;
6
+ readonly signInGreeting: (name: string) => string;
7
+ readonly signInBody: (siteName: string, minutes: number) => string;
8
+ readonly signInButton: string;
9
+ readonly signInIgnore: string;
10
+ readonly invitationSubject: (siteName: string) => string;
11
+ readonly invitationGreeting: (name: string) => string;
12
+ readonly invitationBody: (siteName: string, email: string) => string;
13
+ readonly invitationButton: string;
14
+ /** The notice that a form was filled in. Left out, these are in English. */
15
+ readonly noticeSubject?: (formName: string, siteName: string) => string;
16
+ readonly noticeIntro?: (formName: string, siteName: string) => string;
17
+ readonly noticeSentFrom?: string;
18
+ readonly noticeReply?: string;
19
+ /** The email an owner asks for to see that the settings work. Left out, these are in English. */
20
+ readonly testSubject?: (siteName: string) => string;
21
+ readonly testGreeting?: (name: string) => string;
22
+ readonly testBody?: (siteName: string) => string;
23
+ }
24
+ export declare const englishMailWords: MailWords;
25
+ export interface ResendMailerOptions {
26
+ /** A Resend API key that may send email. */
27
+ readonly apiKey: string;
28
+ /** Who the emails come from, on a domain verified with Resend: `Lakeshore Realty <cms@lakeshore.example>`. */
29
+ readonly from: string;
30
+ readonly words?: MailWords;
31
+ /** Defaults to the platform's own `fetch`. */
32
+ readonly fetch?: typeof globalThis.fetch;
33
+ }
34
+ /** A test email to send: to the person who asked for it. */
35
+ export interface TestMail {
36
+ readonly email: string;
37
+ readonly name: string;
38
+ readonly siteName: string;
39
+ }
40
+ /** The provider answered and refused. `status` is its answer; the message holds its own words, for the server's log. */
41
+ export declare class MailRefusedError extends Error {
42
+ readonly status: number;
43
+ constructor(status: number, detail: string);
44
+ }
45
+ /**
46
+ * Sends the CMS's emails through Resend, over plain HTTP: no SDK, so it runs wherever the site
47
+ * does. A site that uses another provider writes its own `Mailer` the same way.
48
+ */
49
+ export declare class ResendMailer implements Mailer, NoticeMailer {
50
+ #private;
51
+ constructor(options: ResendMailerOptions);
52
+ sendSignInLink(mail: SignInMail): Promise<void>;
53
+ sendInvitation(mail: InvitationMail): Promise<void>;
54
+ /** One email that says the settings work. It carries no link and no secret. */
55
+ sendTest(mail: TestMail): Promise<void>;
56
+ sendSubmissionNotice(mail: SubmissionNotice): Promise<void>;
57
+ }
58
+ /**
59
+ * The mailer a site gets from its settings alone: Resend when `VELOCITY_CMS_RESEND_API_KEY` and
60
+ * `VELOCITY_CMS_EMAIL_FROM` are both set, otherwise none.
61
+ */
62
+ export declare function mailerFromEnv(env?: Readonly<Record<string, string | undefined>>, fetch?: typeof globalThis.fetch): ResendMailer | undefined;
63
+ //# sourceMappingURL=resend-mailer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resend-mailer.d.ts","sourceRoot":"","sources":["../src/resend-mailer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAErE,+EAA+E;AAC/E,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,aAAa,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,MAAM,CAAC;IACrD,QAAQ,CAAC,cAAc,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;IAClD,QAAQ,CAAC,UAAU,EAAE,CAA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tB,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,CAAC;IAC3B,8CAA8C;IAC9C,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CAC1C;AAED,4DAA4D;AAC5D,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,wHAAwH;AACxH,qBAAa,gBAAiB,SAAQ,KAAK;IAEvC,QAAQ,CAAC,MAAM,EAAE,MAAM;gBAAd,MAAM,EAAE,MAAM,EACvB,MAAM,EAAE,MAAM;CAIjB;AA0BD;;;GAGG;AACH,qBAAa,YAAa,YAAW,MAAM,EAAE,YAAY;;gBAI3C,OAAO,EAAE,mBAAmB;IAKxC,cAAc,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAS/C,cAAc,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IASnD,+EAA+E;IAC/E,QAAQ,CAAC,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvC,oBAAoB,CAAC,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;CAmC5D;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,EAAE,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,GAAG,YAAY,GAAG,SAAS,CAIxJ"}
@@ -0,0 +1,116 @@
1
+ export const englishMailWords = {
2
+ signInSubject: (siteName) => `Your sign-in link for ${siteName}`,
3
+ signInGreeting: (name) => `Hi ${name},`,
4
+ signInBody: (siteName, minutes) => `Use the button below to sign in to ${siteName}. The link works once and expires in ${minutes} minutes.`,
5
+ signInButton: 'Sign in',
6
+ signInIgnore: 'If you did not ask for this, you can ignore this email. Nobody can sign in without the link.',
7
+ invitationSubject: (siteName) => `You can now edit ${siteName}`,
8
+ invitationGreeting: (name) => `Hi ${name},`,
9
+ invitationBody: (siteName, email) => `You have been invited to edit ${siteName}. Open the editor and enter ${email}: a sign-in link will be emailed to you. There is no password to set.`,
10
+ invitationButton: 'Open the editor',
11
+ noticeSubject: (formName, siteName) => `New message: ${formName} on ${siteName}`,
12
+ noticeIntro: (formName, siteName) => `Someone filled in "${formName}" on ${siteName}.`,
13
+ noticeSentFrom: 'Sent from',
14
+ noticeReply: 'Reply to this email to answer them. The message is also kept in the CMS.',
15
+ testSubject: (siteName) => `Email works for ${siteName}`,
16
+ testGreeting: (name) => `Hi ${name},`,
17
+ testBody: (siteName) => `This is a test from ${siteName}. If you are reading it, sign-in links, invitations and notices from forms will arrive too.`,
18
+ };
19
+ /** The provider answered and refused. `status` is its answer; the message holds its own words, for the server's log. */
20
+ export class MailRefusedError extends Error {
21
+ status;
22
+ constructor(status, detail) {
23
+ super(`Resend refused an email (${status}). ${detail}`);
24
+ this.status = status;
25
+ }
26
+ }
27
+ const escaped = (text) => text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
28
+ /** Paragraphs and nothing else. */
29
+ function plain(...paragraphs) {
30
+ const html = `<div style="max-width:480px;margin:0 auto;padding:32px 16px">${paragraphs.map((words) => `<p style="margin:0 0 16px;font:16px/1.5 system-ui,sans-serif;color:#1a1a1a">${escaped(words)}</p>`).join('')}</div>`;
31
+ return { html, text: paragraphs.join('\n\n') };
32
+ }
33
+ /** One paragraph of greeting, one of explanation, one button, and the address in full under it. */
34
+ function layout(greeting, body, button, url, note) {
35
+ const paragraph = (words) => `<p style="margin:0 0 16px;font:16px/1.5 system-ui,sans-serif;color:#1a1a1a">${escaped(words)}</p>`;
36
+ const html = [
37
+ '<div style="max-width:480px;margin:0 auto;padding:32px 16px">',
38
+ paragraph(greeting),
39
+ paragraph(body),
40
+ `<p style="margin:0 0 24px"><a href="${escaped(url)}" style="display:inline-block;padding:10px 18px;border-radius:8px;background:#111;color:#fff;font:600 16px system-ui,sans-serif;text-decoration:none">${escaped(button)}</a></p>`,
41
+ `<p style="margin:0 0 16px;font:13px/1.5 system-ui,sans-serif;color:#666;word-break:break-all">${escaped(url)}</p>`,
42
+ note === undefined ? '' : `<p style="margin:0;font:13px/1.5 system-ui,sans-serif;color:#666">${escaped(note)}</p>`,
43
+ '</div>',
44
+ ].join('');
45
+ const text = [greeting, body, url, ...(note === undefined ? [] : [note])].join('\n\n');
46
+ return { html, text };
47
+ }
48
+ /**
49
+ * Sends the CMS's emails through Resend, over plain HTTP: no SDK, so it runs wherever the site
50
+ * does. A site that uses another provider writes its own `Mailer` the same way.
51
+ */
52
+ export class ResendMailer {
53
+ #options;
54
+ #words;
55
+ constructor(options) {
56
+ this.#options = options;
57
+ this.#words = options.words ?? englishMailWords;
58
+ }
59
+ sendSignInLink(mail) {
60
+ const words = this.#words;
61
+ return this.#send(mail.email, words.signInSubject(mail.siteName), layout(words.signInGreeting(mail.name), words.signInBody(mail.siteName, mail.expiresInMinutes), words.signInButton, mail.url, words.signInIgnore));
62
+ }
63
+ sendInvitation(mail) {
64
+ const words = this.#words;
65
+ return this.#send(mail.email, words.invitationSubject(mail.siteName), layout(words.invitationGreeting(mail.name), words.invitationBody(mail.siteName, mail.email), words.invitationButton, mail.url));
66
+ }
67
+ /** One email that says the settings work. It carries no link and no secret. */
68
+ sendTest(mail) {
69
+ const words = { ...englishMailWords, ...this.#words };
70
+ return this.#send(mail.email, words.testSubject?.(mail.siteName) ?? mail.siteName, plain(words.testGreeting?.(mail.name) ?? '', words.testBody?.(mail.siteName) ?? ''));
71
+ }
72
+ sendSubmissionNotice(mail) {
73
+ const words = { ...englishMailWords, ...this.#words };
74
+ const intro = words.noticeIntro?.(mail.formName, mail.siteName) ?? '';
75
+ const from = mail.page === undefined ? undefined : `${words.noticeSentFrom ?? ''} ${mail.page}`;
76
+ const note = mail.replyTo === undefined ? undefined : words.noticeReply;
77
+ const line = (style, text) => `<p style="margin:0 0 ${style}">${escaped(text).replace(/\n/g, '<br>')}</p>`;
78
+ // Everything a visitor wrote is escaped, and shown as text: a notice never carries their markup or links.
79
+ const html = [
80
+ '<div style="max-width:480px;margin:0 auto;padding:32px 16px">',
81
+ line('24px;font:16px/1.5 system-ui,sans-serif;color:#1a1a1a', intro),
82
+ ...mail.answers.flatMap((answer) => [
83
+ line('2px;font:600 13px/1.5 system-ui,sans-serif;color:#666', answer.label),
84
+ line('16px;font:16px/1.5 system-ui,sans-serif;color:#1a1a1a', answer.value),
85
+ ]),
86
+ ...[from, note].flatMap((text) => (text === undefined ? [] : [line('8px;font:13px/1.5 system-ui,sans-serif;color:#666;word-break:break-all', text)])),
87
+ '</div>',
88
+ ].join('');
89
+ const text = [intro, ...mail.answers.map((answer) => `${answer.label}:\n${answer.value}`), ...(from === undefined ? [] : [from]), ...(note === undefined ? [] : [note])].join('\n\n');
90
+ return this.#send(mail.to, words.noticeSubject?.(mail.formName, mail.siteName) ?? mail.formName, { html, text }, mail.replyTo);
91
+ }
92
+ async #send(to, subject, body, replyTo) {
93
+ const send = this.#options.fetch ?? ((input, init) => globalThis.fetch(input, init));
94
+ const response = await send('https://api.resend.com/emails', {
95
+ method: 'POST',
96
+ headers: { authorization: `Bearer ${this.#options.apiKey}`, 'content-type': 'application/json' },
97
+ body: JSON.stringify({ from: this.#options.from, to: [to], subject, ...body, ...(replyTo !== undefined && { reply_to: replyTo }) }),
98
+ });
99
+ if (!response.ok) {
100
+ // The provider's own words go to the server's log through whoever catches this. The address
101
+ // is left out: a log is not the place for who works on a site.
102
+ const detail = (await response.text().catch(() => '')).slice(0, 300);
103
+ throw new MailRefusedError(response.status, detail);
104
+ }
105
+ }
106
+ }
107
+ /**
108
+ * The mailer a site gets from its settings alone: Resend when `VELOCITY_CMS_RESEND_API_KEY` and
109
+ * `VELOCITY_CMS_EMAIL_FROM` are both set, otherwise none.
110
+ */
111
+ export function mailerFromEnv(env = process.env, fetch) {
112
+ const apiKey = env['VELOCITY_CMS_RESEND_API_KEY'];
113
+ const from = env['VELOCITY_CMS_EMAIL_FROM'];
114
+ return apiKey && from ? new ResendMailer({ apiKey, from, ...(fetch && { fetch }) }) : undefined;
115
+ }
116
+ //# sourceMappingURL=resend-mailer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resend-mailer.js","sourceRoot":"","sources":["../src/resend-mailer.ts"],"names":[],"mappings":"AAyBA,MAAM,CAAC,MAAM,gBAAgB,GAAc;IACzC,aAAa,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,yBAAyB,QAAQ,EAAE;IAChE,cAAc,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,IAAI,GAAG;IACvC,UAAU,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,CAAC,sCAAsC,QAAQ,wCAAwC,OAAO,WAAW;IAC3I,YAAY,EAAE,SAAS;IACvB,YAAY,EAAE,8FAA8F;IAC5G,iBAAiB,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,oBAAoB,QAAQ,EAAE;IAC/D,kBAAkB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,IAAI,GAAG;IAC3C,cAAc,EAAE,CAAC,QAAQ,EAAE,KAAK,EAAE,EAAE,CAClC,iCAAiC,QAAQ,+BAA+B,KAAK,uEAAuE;IACtJ,gBAAgB,EAAE,iBAAiB;IACnC,aAAa,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,EAAE,CAAC,gBAAgB,QAAQ,OAAO,QAAQ,EAAE;IAChF,WAAW,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,EAAE,CAAC,sBAAsB,QAAQ,QAAQ,QAAQ,GAAG;IACtF,cAAc,EAAE,WAAW;IAC3B,WAAW,EAAE,0EAA0E;IACvF,WAAW,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,mBAAmB,QAA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Q,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACtD,CAAC;IACH,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,MAAoD,OAAO,CAAC,GAAG,EAAE,KAA+B;IAC5H,MAAM,MAAM,GAAG,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAClD,MAAM,IAAI,GAAG,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAC5C,OAAO,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,KAAK,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAClG,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The site's one secret: from `VELOCITY_CMS_SECRET`, or the site's own on a server that runs many. It signs preview links and, until the editor
3
+ * exists, proves that a publish notice comes from the site's owner. Without it both are off.
4
+ */
5
+ export declare const siteSecret: () => string | undefined;
6
+ /** Whether the request carries the secret as a bearer token. */
7
+ export declare function hasSiteSecret(request: Request): boolean;
8
+ //# sourceMappingURL=secret.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret.d.ts","sourceRoot":"","sources":["../src/secret.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,eAAO,MAAM,UAAU,QAAO,MAAM,GAAG,SAAgG,CAAC;AAExI,gEAAgE;AAChE,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAMvD"}
package/dist/secret.js ADDED
@@ -0,0 +1,17 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ import { currentSite, isHosted } from './hosted.js';
3
+ /**
4
+ * The site's one secret: from `VELOCITY_CMS_SECRET`, or the site's own on a server that runs many. It signs preview links and, until the editor
5
+ * exists, proves that a publish notice comes from the site's owner. Without it both are off.
6
+ */
7
+ export const siteSecret = () => (isHosted() ? currentSite()?.secret : process.env.VELOCITY_CMS_SECRET || undefined);
8
+ /** Whether the request carries the secret as a bearer token. */
9
+ export function hasSiteSecret(request) {
10
+ const secret = siteSecret();
11
+ const given = request.headers.get('authorization')?.match(/^Bearer (.+)$/)?.[1];
12
+ if (!secret || !given)
13
+ return false;
14
+ const [a, b] = [Buffer.from(secret), Buffer.from(given)];
15
+ return a.length === b.length && timingSafeEqual(a, b);
16
+ }
17
+ //# sourceMappingURL=secret.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret.js","sourceRoot":"","sources":["../src/secret.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEpD;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAuB,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,SAAS,CAAC,CAAC;AAExI,gEAAgE;AAChE,MAAM,UAAU,aAAa,CAAC,OAAgB;IAC5C,MAAM,MAAM,GAAG,UAAU,EAAE,CAAC;IAC5B,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,KAAK,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAChF,IAAI,CAAC,MAAM,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IACpC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACzD,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,IAAI,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACxD,CAAC"}
@@ -0,0 +1,18 @@
1
+ import type { Cms } from '@velocity-astro/cms-core';
2
+ import type { DrawnPage } from './page-head.js';
3
+ /** `single` for a CMS already at hand. `preview` reads the version being worked on. */
4
+ export declare function singleFrom(cms: Cms, locale: string, type: string, preview?: boolean): Promise<Readonly<Record<string, unknown>> | undefined>;
5
+ /**
6
+ * What a single page of the CMS holds, by field key, for the page being drawn: the site's
7
+ * settings, say, which every page reads.
8
+ *
9
+ * ```astro
10
+ * const settings = await single(Astro, 'settings');
11
+ * ```
12
+ *
13
+ * The entry in the page's language is read, and the first language's when that language has
14
+ * none. It answers with nothing when there is no such type, when nothing is published yet, and
15
+ * when anything goes wrong: a page is never lost over it, and the template uses its own values.
16
+ */
17
+ export declare function single(page: DrawnPage, type: string): Promise<Readonly<Record<string, unknown>> | undefined>;
18
+ //# sourceMappingURL=single.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"single.d.ts","sourceRoot":"","sources":["../src/single.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,0BAA0B,CAAC;AAGpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAGhD,uFAAuF;AACvF,wBAAsB,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,UAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAQhJ;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,MAAM,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAQlH"}
package/dist/single.js ADDED
@@ -0,0 +1,37 @@
1
+ import { sharedConnection } from './connection.js';
2
+ import { DEFAULT_LOCALE, entriesOf } from './link.js';
3
+ import { isPreview, withPreviewDraft } from './preview.js';
4
+ /** `single` for a CMS already at hand. `preview` reads the version being worked on. */
5
+ export async function singleFrom(cms, locale, type, preview = false) {
6
+ const holder = (await cms.schema.list()).find((candidate) => candidate.key === type);
7
+ if (!holder || holder.kind !== 'single')
8
+ return undefined;
9
+ const shown = (await entriesOf(cms, holder)).filter((entry) => preview || entry.published !== undefined);
10
+ // What a site says about itself (its name, its phone number) holds in every language, so a
11
+ // language with no entry of its own reads the first language's instead of going without.
12
+ const entry = shown.find((candidate) => candidate.locale === locale) ?? shown.find((candidate) => candidate.locale === DEFAULT_LOCALE) ?? shown[0];
13
+ return entry && cms.content.toPublic(holder, withPreviewDraft(entry), preview ? 'working' : 'published').data;
14
+ }
15
+ /**
16
+ * What a single page of the CMS holds, by field key, for the page being drawn: the site's
17
+ * settings, say, which every page reads.
18
+ *
19
+ * ```astro
20
+ * const settings = await single(Astro, 'settings');
21
+ * ```
22
+ *
23
+ * The entry in the page's language is read, and the first language's when that language has
24
+ * none. It answers with nothing when there is no such type, when nothing is published yet, and
25
+ * when anything goes wrong: a page is never lost over it, and the template uses its own values.
26
+ */
27
+ export async function single(page, type) {
28
+ try {
29
+ const { cms } = await sharedConnection({});
30
+ return await singleFrom(cms, page.currentLocale ?? DEFAULT_LOCALE, type, isPreview());
31
+ }
32
+ catch (error) {
33
+ console.error(`[velocity-cms] "${type}" could not be read, so the template's own values are used.`, error instanceof Error ? error.message : error);
34
+ return undefined;
35
+ }
36
+ }
37
+ //# sourceMappingURL=single.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"single.js","sourceRoot":"","sources":["../src/single.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtD,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAE3D,uFAAuF;AACvF,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