@conloca/cloud-astro 0.2.2 → 0.2.4

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 (241) hide show
  1. package/README.md +378 -207
  2. package/dist/.build-inputs.json +69 -0
  3. package/dist/src/component-manifest.d.ts +5 -3
  4. package/dist/src/component-manifest.d.ts.map +1 -1
  5. package/dist/src/component-manifest.js +7 -7
  6. package/dist/src/component-manifest.js.map +1 -1
  7. package/dist/src/constants.d.ts +14 -13
  8. package/dist/src/constants.d.ts.map +1 -1
  9. package/dist/src/constants.js +14 -13
  10. package/dist/src/constants.js.map +1 -1
  11. package/dist/src/d3-build.d.ts +70 -0
  12. package/dist/src/d3-build.d.ts.map +1 -0
  13. package/dist/src/d3-build.js +272 -0
  14. package/dist/src/d3-build.js.map +1 -0
  15. package/dist/src/descriptors.d.ts +2 -2
  16. package/dist/src/descriptors.d.ts.map +1 -1
  17. package/dist/src/descriptors.js +4 -2
  18. package/dist/src/descriptors.js.map +1 -1
  19. package/dist/src/doctor/checks-address.d.ts +18 -0
  20. package/dist/src/doctor/checks-address.d.ts.map +1 -0
  21. package/dist/src/doctor/checks-address.js +163 -0
  22. package/dist/src/doctor/checks-address.js.map +1 -0
  23. package/dist/src/doctor/checks-live.d.ts +8 -5
  24. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  25. package/dist/src/doctor/checks-live.js +226 -188
  26. package/dist/src/doctor/checks-live.js.map +1 -1
  27. package/dist/src/doctor/checks-offline.d.ts +6 -25
  28. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  29. package/dist/src/doctor/checks-offline.js +30 -259
  30. package/dist/src/doctor/checks-offline.js.map +1 -1
  31. package/dist/src/doctor/checks-preview-limits.d.ts +11 -0
  32. package/dist/src/doctor/checks-preview-limits.d.ts.map +1 -0
  33. package/dist/src/doctor/checks-preview-limits.js +133 -0
  34. package/dist/src/doctor/checks-preview-limits.js.map +1 -0
  35. package/dist/src/doctor/checks-preview-live.d.ts +14 -0
  36. package/dist/src/doctor/checks-preview-live.d.ts.map +1 -0
  37. package/dist/src/doctor/checks-preview-live.js +72 -0
  38. package/dist/src/doctor/checks-preview-live.js.map +1 -0
  39. package/dist/src/doctor/checks-preview.d.ts +7 -0
  40. package/dist/src/doctor/checks-preview.d.ts.map +1 -0
  41. package/dist/src/doctor/checks-preview.js +287 -0
  42. package/dist/src/doctor/checks-preview.js.map +1 -0
  43. package/dist/src/doctor/config-scan.d.ts +12 -3
  44. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  45. package/dist/src/doctor/config-scan.js +38 -11
  46. package/dist/src/doctor/config-scan.js.map +1 -1
  47. package/dist/src/doctor/run.d.ts.map +1 -1
  48. package/dist/src/doctor/run.js +16 -10
  49. package/dist/src/doctor/run.js.map +1 -1
  50. package/dist/src/doctor/types.d.ts +17 -7
  51. package/dist/src/doctor/types.d.ts.map +1 -1
  52. package/dist/src/doctor/types.js +17 -7
  53. package/dist/src/doctor/types.js.map +1 -1
  54. package/dist/src/editor-page/bundle.d.ts +90 -0
  55. package/dist/src/editor-page/bundle.d.ts.map +1 -0
  56. package/dist/src/editor-page/bundle.js +373 -0
  57. package/dist/src/editor-page/bundle.js.map +1 -0
  58. package/dist/src/editor-page/data-schemas.d.ts +16 -0
  59. package/dist/src/editor-page/data-schemas.d.ts.map +1 -0
  60. package/dist/src/editor-page/data-schemas.js +39 -0
  61. package/dist/src/editor-page/data-schemas.js.map +1 -0
  62. package/dist/src/editor-page/emit.d.ts +69 -0
  63. package/dist/src/editor-page/emit.d.ts.map +1 -0
  64. package/dist/src/editor-page/emit.js +254 -0
  65. package/dist/src/editor-page/emit.js.map +1 -0
  66. package/dist/src/editor-page/framing.d.ts +23 -0
  67. package/dist/src/editor-page/framing.d.ts.map +1 -0
  68. package/dist/src/editor-page/framing.js +39 -0
  69. package/dist/src/editor-page/framing.js.map +1 -0
  70. package/dist/src/editor-page/page.d.ts +9 -0
  71. package/dist/src/editor-page/page.d.ts.map +1 -0
  72. package/dist/src/editor-page/page.js +31 -0
  73. package/dist/src/editor-page/page.js.map +1 -0
  74. package/dist/src/editor-page/site-base.d.ts +4 -0
  75. package/dist/src/editor-page/site-base.d.ts.map +1 -0
  76. package/dist/src/editor-page/site-base.js +13 -0
  77. package/dist/src/editor-page/site-base.js.map +1 -0
  78. package/dist/src/git.d.ts +11 -8
  79. package/dist/src/git.d.ts.map +1 -1
  80. package/dist/src/git.js +25 -8
  81. package/dist/src/git.js.map +1 -1
  82. package/dist/src/index.d.ts +4 -1
  83. package/dist/src/index.d.ts.map +1 -1
  84. package/dist/src/index.js +11 -6
  85. package/dist/src/index.js.map +1 -1
  86. package/dist/src/integration.d.ts +1 -1
  87. package/dist/src/integration.d.ts.map +1 -1
  88. package/dist/src/integration.js +377 -416
  89. package/dist/src/integration.js.map +1 -1
  90. package/dist/src/node.d.ts +3 -1
  91. package/dist/src/node.d.ts.map +1 -1
  92. package/dist/src/node.js +7 -2
  93. package/dist/src/node.js.map +1 -1
  94. package/dist/src/preview/_dispatch.d.ts +12 -0
  95. package/dist/src/preview/_dispatch.d.ts.map +1 -1
  96. package/dist/src/preview/_dispatch.js +31 -0
  97. package/dist/src/preview/_dispatch.js.map +1 -1
  98. package/dist/src/preview/_resolve-opts.d.ts +19 -10
  99. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  100. package/dist/src/preview/_resolve-opts.js +24 -11
  101. package/dist/src/preview/_resolve-opts.js.map +1 -1
  102. package/dist/src/preview/banner.d.ts +12 -9
  103. package/dist/src/preview/banner.d.ts.map +1 -1
  104. package/dist/src/preview/banner.js +46 -43
  105. package/dist/src/preview/banner.js.map +1 -1
  106. package/dist/src/preview/cloudflare-adapter.d.ts +35 -0
  107. package/dist/src/preview/cloudflare-adapter.d.ts.map +1 -0
  108. package/dist/src/preview/cloudflare-adapter.js +92 -0
  109. package/dist/src/preview/cloudflare-adapter.js.map +1 -0
  110. package/dist/src/preview/cookie.d.ts +13 -14
  111. package/dist/src/preview/cookie.d.ts.map +1 -1
  112. package/dist/src/preview/cookie.js +19 -26
  113. package/dist/src/preview/cookie.js.map +1 -1
  114. package/dist/src/preview/dispatcher.d.ts +73 -0
  115. package/dist/src/preview/dispatcher.d.ts.map +1 -0
  116. package/dist/src/preview/dispatcher.js +329 -0
  117. package/dist/src/preview/dispatcher.js.map +1 -0
  118. package/dist/src/preview/entry-code.d.ts +33 -0
  119. package/dist/src/preview/entry-code.d.ts.map +1 -0
  120. package/dist/src/preview/entry-code.js +33 -0
  121. package/dist/src/preview/entry-code.js.map +1 -0
  122. package/dist/src/preview/headers.d.ts +24 -4
  123. package/dist/src/preview/headers.d.ts.map +1 -1
  124. package/dist/src/preview/headers.js +35 -7
  125. package/dist/src/preview/headers.js.map +1 -1
  126. package/dist/src/preview/label.d.ts +8 -0
  127. package/dist/src/preview/label.d.ts.map +1 -0
  128. package/dist/src/preview/label.js +14 -0
  129. package/dist/src/preview/label.js.map +1 -0
  130. package/dist/src/preview/landing.d.ts +23 -2
  131. package/dist/src/preview/landing.d.ts.map +1 -1
  132. package/dist/src/preview/landing.js +105 -37
  133. package/dist/src/preview/landing.js.map +1 -1
  134. package/dist/src/preview/middleware.d.ts +49 -22
  135. package/dist/src/preview/middleware.d.ts.map +1 -1
  136. package/dist/src/preview/middleware.js +259 -100
  137. package/dist/src/preview/middleware.js.map +1 -1
  138. package/dist/src/preview/preview-path.d.ts +47 -5
  139. package/dist/src/preview/preview-path.d.ts.map +1 -1
  140. package/dist/src/preview/preview-path.js +65 -8
  141. package/dist/src/preview/preview-path.js.map +1 -1
  142. package/dist/src/preview/redeem-url.d.ts +7 -0
  143. package/dist/src/preview/redeem-url.d.ts.map +1 -0
  144. package/dist/src/preview/redeem-url.js +14 -0
  145. package/dist/src/preview/redeem-url.js.map +1 -0
  146. package/dist/src/preview/site-middleware.d.ts +5 -5
  147. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  148. package/dist/src/preview/site-middleware.js +53 -26
  149. package/dist/src/preview/site-middleware.js.map +1 -1
  150. package/dist/src/preview-build.d.ts +29 -15
  151. package/dist/src/preview-build.d.ts.map +1 -1
  152. package/dist/src/preview-build.js +66 -25
  153. package/dist/src/preview-build.js.map +1 -1
  154. package/dist/src/preview.d.ts +1 -1
  155. package/dist/src/preview.d.ts.map +1 -1
  156. package/dist/src/preview.js +1 -1
  157. package/dist/src/preview.js.map +1 -1
  158. package/dist/src/repository.d.ts +1 -1
  159. package/dist/src/repository.js +1 -1
  160. package/dist/src/resolve-options.d.ts +17 -0
  161. package/dist/src/resolve-options.d.ts.map +1 -0
  162. package/dist/src/resolve-options.js +21 -0
  163. package/dist/src/resolve-options.js.map +1 -0
  164. package/dist/src/site-id.d.ts +0 -2
  165. package/dist/src/site-id.d.ts.map +1 -1
  166. package/dist/src/site-id.js +2 -3
  167. package/dist/src/site-id.js.map +1 -1
  168. package/dist/src/skill.d.ts +11 -0
  169. package/dist/src/skill.d.ts.map +1 -1
  170. package/dist/src/skill.js +32 -9
  171. package/dist/src/skill.js.map +1 -1
  172. package/dist/src/types.d.ts +33 -78
  173. package/dist/src/types.d.ts.map +1 -1
  174. package/package.json +63 -13
  175. package/src/component-manifest.ts +11 -8
  176. package/src/constants.ts +15 -13
  177. package/src/d3-build.ts +315 -0
  178. package/src/descriptors.ts +6 -4
  179. package/src/doctor/checks-address.ts +190 -0
  180. package/src/doctor/checks-live.ts +262 -268
  181. package/src/doctor/checks-offline.ts +32 -279
  182. package/src/doctor/checks-preview-limits.ts +137 -0
  183. package/src/doctor/checks-preview-live.ts +77 -0
  184. package/src/doctor/checks-preview.ts +302 -0
  185. package/src/doctor/config-scan.ts +35 -9
  186. package/src/doctor/run.ts +18 -16
  187. package/src/doctor/types.ts +17 -7
  188. package/src/editor-page/bundle.ts +487 -0
  189. package/src/editor-page/data-schemas.ts +47 -0
  190. package/src/editor-page/emit.ts +362 -0
  191. package/src/editor-page/framing.ts +62 -0
  192. package/src/editor-page/page.ts +37 -0
  193. package/src/editor-page/site-base.ts +11 -0
  194. package/src/git.ts +29 -10
  195. package/src/index.ts +22 -6
  196. package/src/integration.ts +399 -469
  197. package/src/node.ts +18 -2
  198. package/src/preview/_dispatch.ts +36 -1
  199. package/src/preview/_resolve-opts.ts +35 -12
  200. package/src/preview/banner.ts +61 -43
  201. package/src/preview/cloudflare-adapter.ts +103 -0
  202. package/src/preview/cookie.ts +18 -24
  203. package/src/preview/dispatcher.ts +407 -0
  204. package/src/preview/entry-code.ts +51 -0
  205. package/src/preview/headers.ts +35 -7
  206. package/src/preview/label.ts +12 -0
  207. package/src/preview/landing.ts +117 -39
  208. package/src/preview/middleware.ts +302 -115
  209. package/src/preview/preview-path.ts +83 -8
  210. package/src/preview/redeem-url.ts +14 -0
  211. package/src/preview/site-middleware.ts +60 -30
  212. package/src/preview-build.ts +85 -26
  213. package/src/preview-handler.astro +12 -9
  214. package/src/preview.ts +0 -1
  215. package/src/repository.ts +1 -1
  216. package/src/resolve-options.ts +37 -0
  217. package/src/site-id.ts +2 -4
  218. package/src/skill/SKILL.md +63 -55
  219. package/src/skill.ts +36 -8
  220. package/src/types.ts +33 -79
  221. package/src/virtual-modules.d.ts +4 -1
  222. package/dist/src/build-commit.d.ts +0 -19
  223. package/dist/src/build-commit.d.ts.map +0 -1
  224. package/dist/src/build-commit.js +0 -6
  225. package/dist/src/build-commit.js.map +0 -1
  226. package/dist/src/bundle.d.ts +0 -181
  227. package/dist/src/bundle.d.ts.map +0 -1
  228. package/dist/src/bundle.js +0 -413
  229. package/dist/src/bundle.js.map +0 -1
  230. package/dist/src/discovery.d.ts +0 -58
  231. package/dist/src/discovery.d.ts.map +0 -1
  232. package/dist/src/discovery.js +0 -133
  233. package/dist/src/discovery.js.map +0 -1
  234. package/dist/src/register.d.ts +0 -98
  235. package/dist/src/register.d.ts.map +0 -1
  236. package/dist/src/register.js +0 -103
  237. package/dist/src/register.js.map +0 -1
  238. package/src/build-commit.ts +0 -22
  239. package/src/bundle.ts +0 -570
  240. package/src/discovery.ts +0 -183
  241. package/src/register.ts +0 -180
package/src/node.ts CHANGED
@@ -1,5 +1,21 @@
1
1
  // Node-only build-hook entry for `@conloca/cloud-astro`. The site wires
2
- // the integration into `astro.config.mjs` via this subpath.
2
+ // the integration into `astro.config.mjs` via this subpath; every build
3
+ // writes your site's editor page to /_conloca/editor/.
3
4
 
4
- export { conlocaCloud, PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './integration.js';
5
+ export {
6
+ DEFAULT_EDITOR_ENDPOINT,
7
+ EDITOR_HOST_PROTOCOL,
8
+ EDITOR_PAGE_PATH,
9
+ type EditorHostPageData,
10
+ type EditorPageInfo,
11
+ } from '@conloca/content-api/editor-host';
12
+ // The /_conloca/editor/ header rules that `conloca connect` writes and doctor checks.
13
+ export {
14
+ type FramingBlocker,
15
+ type FramingSnippets,
16
+ findFramingBlockers,
17
+ framingSnippets,
18
+ } from './editor-page/framing.js';
19
+ // The default export is what `astro add @conloca/cloud-astro` wires in.
20
+ export { conlocaCloud as default, conlocaCloud, PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './integration.js';
5
21
  export type { ConlocaCloudOptions, PreviewBuildOptions } from './types.js';
@@ -15,6 +15,7 @@ import type { PreviewContext } from './middleware.js';
15
15
  * answers.
16
16
  * - `redirect` — branch installed a redirect at the page's path; callers
17
17
  * issue a 302 (we deliberately downgrade 301 to 302 — see fetchPageStatus).
18
+ * - an ended share link (`grant-revoked`, `grant-expired`, `draft-published`, `draft-discarded`) — Conloca answers 410 and names who shared the link; the site shows that page, never the published one.
18
19
  *
19
20
  * The verdict-to-response mapping lives in the site middleware
20
21
  * (`./site-middleware.ts`), which renders through the site's own route.
@@ -23,7 +24,22 @@ export type PageStatus =
23
24
  | { kind: 'unchanged' }
24
25
  | { kind: 'changed'; embedded: ReadonlyMap<string, LocalizedEntry> }
25
26
  | { kind: 'deleted' }
26
- | { kind: 'redirect'; target: string };
27
+ | { kind: 'redirect'; target: string }
28
+ | { kind: ShareEndedKind; sharedBy: string };
29
+
30
+ /** Why a share link no longer opens: turned off, expired, or its draft was published or discarded. */
31
+ export type ShareEndedKind = 'grant-revoked' | 'grant-expired' | 'draft-published' | 'draft-discarded';
32
+
33
+ const SHARE_ENDED: ReadonlySet<string> = new Set([
34
+ 'grant-revoked',
35
+ 'grant-expired',
36
+ 'draft-published',
37
+ 'draft-discarded',
38
+ ]);
39
+
40
+ export function isShareEndedKind(value: string): value is ShareEndedKind {
41
+ return SHARE_ENDED.has(value);
42
+ }
27
43
 
28
44
  interface FetchPageStatusInput {
29
45
  saasEndpoint: string;
@@ -71,6 +87,10 @@ export async function fetchPageStatus(input: FetchPageStatusInput): Promise<Page
71
87
  const data: unknown = await response.json();
72
88
  return { kind: 'changed', embedded: decodeEmbedded(data) };
73
89
  }
90
+ if (response.status === 410) {
91
+ const ended = await shareEndedOf(response);
92
+ if (ended !== null) return ended;
93
+ }
74
94
  throw new Error(`preview page-status ${input.path}: ${response.status}`);
75
95
  }
76
96
 
@@ -103,3 +123,18 @@ function isLocalizedEntry(value: unknown): value is LocalizedEntry {
103
123
  const l = v.localized as { etag?: unknown; locale?: unknown; content?: unknown };
104
124
  return typeof l.etag === 'string' && typeof l.locale === 'string' && typeof l.content === 'object';
105
125
  }
126
+
127
+ /** The ended-link verdict a 410 names, or null when the body is not one. */
128
+ export async function shareEndedOf(response: Response): Promise<{ kind: ShareEndedKind; sharedBy: string } | null> {
129
+ let body: unknown;
130
+ try {
131
+ body = await response.json();
132
+ } catch {
133
+ return null;
134
+ }
135
+ if (typeof body !== 'object' || body === null) return null;
136
+ const error = 'error' in body ? body.error : undefined;
137
+ const sharedBy = 'sharedBy' in body ? body.sharedBy : undefined;
138
+ if (typeof error !== 'string' || !isShareEndedKind(error)) return null;
139
+ return { kind: error, sharedBy: typeof sharedBy === 'string' ? sharedBy : '' };
140
+ }
@@ -1,13 +1,30 @@
1
1
  import type { PreviewMiddlewareOptions } from './middleware.js';
2
+ import type { PreviewServeMode } from './preview-path.js';
2
3
 
3
4
  /** Values the preview build can bake into the artifact at build time. */
4
5
  export interface BakedPreviewOpts {
5
- secret?: string;
6
6
  saasEndpoint?: string;
7
7
  saasIssuer?: string;
8
8
  saasAudience?: string;
9
9
  /** The commit the preview build was built from; page-status compares the branch's latest commit with it. */
10
10
  buildCommit?: string;
11
+ /** The repository, site and branch the preview build was made from: what every pass must match. */
12
+ repo?: string;
13
+ siteId?: string;
14
+ branch?: string;
15
+ /** Astro's `base` at build time. */
16
+ base?: string;
17
+ /** How this build serves previews (`d2` when not baked). */
18
+ mode?: PreviewServeMode;
19
+ }
20
+
21
+ /** A value only the build can bake; the deployment cannot supply it. */
22
+ function bakedOnly(name: string, bakedValue: string | undefined): string {
23
+ if (bakedValue) return bakedValue;
24
+ throw new Error(
25
+ `@conloca/cloud-astro: the preview server is missing the baked ${name}; the preview build bakes it ` +
26
+ 'when previewBuild is given as an object, so rebuild',
27
+ );
11
28
  }
12
29
 
13
30
  /**
@@ -15,17 +32,18 @@ export interface BakedPreviewOpts {
15
32
  * falling back to the runtime environment.
16
33
  *
17
34
  * Baking is what removes the deployer's setup burden: every value is already
18
- * known while the preview build runs — the secret arrived with registration,
19
- * the endpoint and audience are integration options — so a correctly built
20
- * preview artifact needs NO env vars on the deployment. It also removes a
21
- * chicken-and-egg loop: the secret is generated during the build but the
22
- * deployment that would carry it happens afterwards.
35
+ * known while the preview build runs — the endpoint and audience are
36
+ * integration options, the repository, site and branch are what the build
37
+ * was made from — so a correctly built preview artifact needs NO env vars on
38
+ * the deployment.
23
39
  *
24
- * The environment still wins when set, so one artifact can be promoted across
25
- * environments without a rebuild.
40
+ * For the endpoint, issuer and audience the environment still wins when set,
41
+ * so one artifact can be promoted across environments without a rebuild. The
42
+ * repository, site and branch come only from the build: they are what a pass
43
+ * must match, and the deployment cannot change what the artifact serves.
26
44
  *
27
- * Throws naming the missing variable — a misconfigured preview runtime must
28
- * not silently accept requests.
45
+ * Throws naming the missing value — a misconfigured preview runtime must not
46
+ * silently accept requests.
29
47
  */
30
48
  export function resolveFromBaked(
31
49
  baked: BakedPreviewOpts,
@@ -41,11 +59,16 @@ export function resolveFromBaked(
41
59
  `set ${envName} on the deployment to override.`,
42
60
  );
43
61
  };
62
+ const saasIssuer = readEnvVar('CONLOCA_SAAS_ISSUER') || baked.saasIssuer;
44
63
  return {
45
- secret: pick('CONLOCA_PREVIEW_SECRET', baked.secret),
46
64
  saasEndpoint: pick('CONLOCA_SAAS_ENDPOINT', baked.saasEndpoint),
47
- saasIssuer: pick('CONLOCA_SAAS_ISSUER', baked.saasIssuer),
65
+ ...(saasIssuer ? { saasIssuer } : {}),
48
66
  saasAudience: pick('CONLOCA_SAAS_AUDIENCE', baked.saasAudience),
67
+ repo: bakedOnly('repo', baked.repo),
68
+ siteId: bakedOnly('siteId', baked.siteId),
69
+ branch: bakedOnly('branch', baked.branch),
70
+ base: baked.base || '/',
71
+ mode: baked.mode ?? 'd2',
49
72
  // Optional: an artifact built before this was baked has none, and the
50
73
  // endpoint then falls back to the branch's registered build.
51
74
  ...(baked.buildCommit ? { buildCommit: baked.buildCommit } : {}),
@@ -15,24 +15,33 @@ import type { PreviewContext } from './middleware.js';
15
15
  * encodes both `"` and `</script>` sequences safely, which is the
16
16
  * canonical way to embed server data in a same-origin inline script.
17
17
  */
18
- export function getBannerScriptText(ctx: PreviewContext, endpoint?: string, exitPath?: string): string {
18
+ export function getBannerScriptText(
19
+ ctx: Pick<PreviewContext, 'branch' | 'grant'>,
20
+ endpoint?: string,
21
+ exitPath?: string,
22
+ shareUrl?: string,
23
+ pagePath?: string,
24
+ ): string {
19
25
  // Serialize then patch the `<` character that JSON.stringify does NOT
20
26
  // escape. Browsers terminate inline scripts on `</script>` regardless of
21
27
  // string-literal context, so a branch name containing `</script>` would
22
28
  // break out of the script tag. Replacing `</` with `<\/` is the standard
23
29
  // mitigation (also done by ASP.NET's Json.Encode, Rails' j helper, etc.).
24
30
  //
25
- // The endpoint rides the envelope alongside the preview ctx so the
26
- // "Share Preview" button can call `GET {endpoint}/preview/share` from the
27
- // browser with the preview JWT (the same credential the cookie carries; the
28
- // cookie is HttpOnly, so the button reads the JWT from here). Absent an
29
- // endpoint the button is inert. `endpoint: undefined` drops out of the JSON.
30
- //
31
- // `exitPath` is the server-side exit route (secret-prefixed). Embedding it
32
- // here does not widen the secret's exposure: this script is served only to
33
- // credentialed preview visitors, who already hold the secret — it is in the
34
- // entry/share URL they arrived through — and the response is no-store.
35
- const ctxJson = JSON.stringify({ ...ctx, endpoint, exitPath }).replace(/</g, '\\u003c');
31
+ // Only the branch name and public addresses reach the page, never the pass:
32
+ // every script on the page, third-party tags included, could read it. A
33
+ // share viewer gets who shared the draft and when the link expires instead
34
+ // of the editor links. `undefined` values drop out of the JSON.
35
+ const embedded =
36
+ ctx.grant === undefined
37
+ ? { branch: ctx.branch, endpoint, exitPath, shareUrl, path: pagePath }
38
+ : {
39
+ branch: ctx.branch,
40
+ exitPath,
41
+ path: pagePath,
42
+ viewer: { sharedBy: ctx.grant.sharedBy, expiresAt: ctx.grant.expiresAt },
43
+ };
44
+ const ctxJson = JSON.stringify(embedded).replace(/</g, '\\u003c');
36
45
  return [
37
46
  `var __conlocaPreview = ${ctxJson};`,
38
47
  "var __conlocaCollapseKey = 'conloca.preview.collapsed';",
@@ -42,34 +51,24 @@ export function getBannerScriptText(ctx: PreviewContext, endpoint?: string, exit
42
51
  " var host = document.createElement('div');",
43
52
  " host.id = 'conloca-preview-banner';",
44
53
  " host.style.cssText = 'position:fixed;bottom:16px;right:16px;z-index:2147483647;font-family:system-ui,sans-serif;background:#111;color:#fff;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,0.35);padding:8px 12px;font-size:13px;display:flex;gap:12px;align-items:center;';",
45
- " var label = document.createElement('span'); label.textContent = 'Preview: ' + __conlocaPreview.branch; host.appendChild(label);",
54
+ " var label = document.createElement('span');",
55
+ ' if (__conlocaPreview.viewer) {',
56
+ ' var days = Math.max(1, Math.ceil((__conlocaPreview.viewer.expiresAt * 1000 - Date.now()) / 86400000));',
57
+ " label.textContent = 'Draft: ' + __conlocaPreview.branch + (__conlocaPreview.viewer.sharedBy ? ' · Shared by ' + __conlocaPreview.viewer.sharedBy : '') + ' · Expires in ' + days + (days === 1 ? ' day' : ' days');",
58
+ " } else { label.textContent = 'Preview: ' + __conlocaPreview.branch; }",
59
+ ' host.appendChild(label);',
46
60
  // "Edit" reuses the landing page's `/login?return=` contract:
47
61
  // the endpoint's login route already knows how to send an authenticated
48
62
  // session into the editor for the requested page.
49
63
  " var edit = document.createElement('a'); edit.textContent = 'Edit'; edit.style.color = '#9cf';",
50
- " if (__conlocaPreview.endpoint) { edit.href = __conlocaPreview.endpoint + '/login?return=' + encodeURIComponent(location.pathname); host.appendChild(edit); }",
64
+ " if (__conlocaPreview.endpoint) { edit.href = __conlocaPreview.endpoint + '/login?return=' + encodeURIComponent(__conlocaPreview.path || location.pathname); host.appendChild(edit); }",
65
+ // Share opens the editor's share dialog for this page in a new tab.
66
+ " if (__conlocaPreview.shareUrl) { var share = document.createElement('a'); share.textContent = 'Share'; share.style.color = '#9cf'; share.href = __conlocaPreview.shareUrl; share.target = '_blank'; share.rel = 'noopener'; host.appendChild(share); }",
51
67
  // "Exit Preview" must round-trip the server: the cookie is HttpOnly, so
52
68
  // only a Set-Cookie response can expire it. `to` returns the visitor to
53
69
  // this page, now published.
54
70
  " var exitLink = document.createElement('a'); exitLink.textContent = 'Exit Preview'; exitLink.style.color = '#9cf';",
55
- " if (__conlocaPreview.exitPath) { exitLink.href = __conlocaPreview.exitPath + '?to=' + encodeURIComponent(location.pathname); host.appendChild(exitLink); }",
56
- " var share = document.createElement('button'); share.type = 'button'; share.textContent = 'Share Preview'; share.style.cssText = 'background:#333;color:#fff;border:1px solid #555;border-radius:4px;padding:2px 8px;cursor:pointer;'; host.appendChild(share);",
57
- // "Share Preview": mint a fresh shareable link via GET {endpoint}/preview/share
58
- // and copy it to the clipboard. Bearer-authenticated with the preview JWT
59
- // (the route reads Authorization/?token=, never the HttpOnly cookie). The
60
- // button briefly reflects the outcome, then restores.
61
- " share.addEventListener('click', function () {",
62
- ' if (!__conlocaPreview.endpoint) return;',
63
- " var shareUrl = __conlocaPreview.endpoint + '/preview/share?branch=' + encodeURIComponent(__conlocaPreview.branch);",
64
- ' var previousLabel = share.textContent;',
65
- ' share.disabled = true;',
66
- " fetch(shareUrl, { headers: { authorization: 'Bearer ' + __conlocaPreview.jwt } })",
67
- " .then(function (res) { if (!res.ok) throw new Error('share ' + res.status); return res.json(); })",
68
- " .then(function (data) { if (!data || typeof data.url !== 'string') throw new Error('missing url'); return navigator.clipboard.writeText(data.url); })",
69
- " .then(function () { share.textContent = 'Link copied'; })",
70
- " .catch(function () { share.textContent = 'Copy failed'; })",
71
- ' .then(function () { setTimeout(function () { share.textContent = previousLabel; share.disabled = false; }, 2000); });',
72
- ' });',
71
+ " if (__conlocaPreview.exitPath) { exitLink.href = __conlocaPreview.exitPath + '?to=' + encodeURIComponent(__conlocaPreview.path || location.pathname); host.appendChild(exitLink); }",
73
72
  " var collapse = document.createElement('button'); collapse.type = 'button'; collapse.textContent = __conlocaIsCollapsed() ? '+' : '-'; collapse.style.cssText = 'background:transparent;color:#fff;border:none;cursor:pointer;font-size:16px;line-height:1;'; host.appendChild(collapse);",
74
73
  " collapse.addEventListener('click', function () { var c = !__conlocaIsCollapsed(); __conlocaSetCollapsed(c); host.style.display = c ? 'none' : ''; });",
75
74
  " if (__conlocaIsCollapsed()) host.style.display = 'none';",
@@ -79,18 +78,37 @@ export function getBannerScriptText(ctx: PreviewContext, endpoint?: string, exit
79
78
  ].join(' ');
80
79
  }
81
80
 
81
+ const ROBOTS_META = '<meta name="robots" content="noindex, nofollow">';
82
+ // Any `<meta name=robots …>`, whatever the case, quoting or attribute order; `robots-extra` and `googlebot` are other names.
83
+ const SITE_ROBOTS_META_RE = /<meta\b[^>]*?\sname\s*=\s*["']?robots(?=["'\s/>])[^>]*>/giu;
84
+
82
85
  /**
83
- * Returns `html` with the preview banner script and `<meta robots noindex>`
84
- * tag injected before the closing `</body>` tag.
86
+ * Returns `html` with the preview banner script (or, on a share pass, the
87
+ * viewer banner) injected before the closing `</body>` tag, and the page's robots metas replaced by one
88
+ * `<meta robots noindex>`. The site's own robots meta (often
89
+ * `index, follow`) must not sit next to the preview's. Ours takes the first
90
+ * one's place, or goes before `</body>` when the page has none.
85
91
  *
86
- * The injection uses `String.prototype.replace` with a string argument
87
- * (not a regex), so only the FIRST `</body>` match is rewritten. That
88
- * matters because a misconfigured renderer can emit malformed HTML with
89
- * multiple `</body>` tags; we never want to inject the banner more than
90
- * once per response.
92
+ * The `</body>` injection uses `String.prototype.replace` with a string
93
+ * argument (not a regex), so only the FIRST `</body>` match is rewritten.
94
+ * That matters because a misconfigured renderer can emit malformed HTML with
95
+ * multiple `</body>` tags; we never want to inject the banner more than once
96
+ * per response.
91
97
  */
92
- export function injectPreviewBanner(html: string, ctx: PreviewContext, endpoint?: string, exitPath?: string): string {
93
- const robotsMeta = '<meta name="robots" content="noindex, nofollow">';
94
- const script = `<script>${getBannerScriptText(ctx, endpoint, exitPath)}</script>`;
95
- return html.replace('</body>', `${robotsMeta + script}</body>`);
98
+ export function injectPreviewBanner(
99
+ html: string,
100
+ ctx: Pick<PreviewContext, 'branch' | 'grant'>,
101
+ endpoint?: string,
102
+ exitPath?: string,
103
+ shareUrl?: string,
104
+ pagePath?: string,
105
+ ): string {
106
+ const script = `<script>${getBannerScriptText(ctx, endpoint, exitPath, shareUrl, pagePath)}</script>`;
107
+ let replaced = false;
108
+ const page = html.replace(SITE_ROBOTS_META_RE, () => {
109
+ const first = !replaced;
110
+ replaced = true;
111
+ return first ? ROBOTS_META : '';
112
+ });
113
+ return page.replace('</body>', `${replaced ? '' : ROBOTS_META}${script}</body>`);
96
114
  }
@@ -0,0 +1,103 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
6
+ import type { AstroIntegration } from 'astro';
7
+ import { parse } from 'jsonc-parser';
8
+ import { PACKAGE_NAME } from '../constants.js';
9
+
10
+ /**
11
+ * A `wrangler.jsonc` text → its object (comments and trailing commas allowed), else undefined. The return type is
12
+ * `isRecord`'s narrowing, inferred: anti-slop's `no-unsafe-dictionary-type` refuses the type written out.
13
+ */
14
+ export function parseWranglerConfig(text: string) {
15
+ const value: unknown = parse(text, [], { allowTrailingComma: true });
16
+ return isRecord(value) ? value : undefined;
17
+ }
18
+
19
+ /** `wrangler.jsonc`, else `wrangler.json`, in the project; undefined when it has neither. */
20
+ export function wranglerConfigPath(root: string): string | undefined {
21
+ return ['wrangler.jsonc', 'wrangler.json'].map((name) => join(root, name)).find((path) => existsSync(path));
22
+ }
23
+
24
+ /** Where `@astrojs/cloudflare` resolves from the project; throws naming the fix when it is not installed. */
25
+ export function resolveCloudflareAdapter(root: string): string {
26
+ try {
27
+ return createRequire(join(root, 'package.json')).resolve('@astrojs/cloudflare');
28
+ } catch {
29
+ throw new Error(
30
+ `${PACKAGE_NAME}: a static site's preview server runs on Cloudflare Workers and needs the Cloudflare adapter: ` +
31
+ 'install @astrojs/cloudflare in this project',
32
+ );
33
+ }
34
+ }
35
+
36
+ /** What the preview build passes `@astrojs/cloudflare`. */
37
+ interface ChildAdapterOptions {
38
+ configPath?: string;
39
+ imageService?: { build: 'compile'; runtime: 'passthrough' };
40
+ }
41
+
42
+ // Returns `object`, not `unknown`: anti-slop's no-unknown-returns reads function types too; `isIntegration` narrows the result.
43
+ function isAdapterFactory(value: unknown): value is (options: ChildAdapterOptions) => object {
44
+ return typeof value === 'function';
45
+ }
46
+
47
+ function isIntegration(value: unknown): value is AstroIntegration {
48
+ return isRecord(value) && typeof value.name === 'string' && isRecord(value.hooks);
49
+ }
50
+
51
+ /**
52
+ * The adapter options per mode. Under D3 the child reads its config copy, and compiles images at build time: on-demand
53
+ * draft pages then emit `/_image` URLs the passthrough endpoint answers from the static files, with no `IMAGES` binding,
54
+ * which the dispatcher's config doesn't declare (the real-build round trip serves a fixture image through it).
55
+ * Under D4 the preview deploy is a Cloudflare Worker of its own and keeps the adapter's defaults.
56
+ */
57
+ export function childAdapterOptions(mode: 'd3' | 'd4', configPath: string | undefined): ChildAdapterOptions {
58
+ if (mode === 'd4') return {};
59
+ return {
60
+ ...(configPath === undefined ? {} : { configPath }),
61
+ imageService: { build: 'compile', runtime: 'passthrough' },
62
+ };
63
+ }
64
+
65
+ /**
66
+ * The adapter for the preview build of a site that names none. Under D3 it reads a copy of the site's `wrangler.jsonc`
67
+ * without `main` and `assets`, at the top level and in every env block (both inherit): those belong to the dispatcher in
68
+ * front of the static site, and the adapter would take `main` for its own entry. Under D4 the site's own config, with the env
69
+ * block the build selects, is the preview deploy's.
70
+ * shortcut: relative paths inside the copy resolve from .conloca/; rewrite them when a site's config carries one.
71
+ */
72
+ export async function cloudflareAdapter(rootUrl: URL, mode: 'd3' | 'd4'): Promise<AstroIntegration> {
73
+ const root = fileURLToPath(rootUrl);
74
+ const module: unknown = await import(pathToFileURL(resolveCloudflareAdapter(root)).href);
75
+ // Not isRecord: Bun gives a module namespace a prototype object, Node gives it none.
76
+ const factory = typeof module === 'object' && module !== null && 'default' in module ? module.default : undefined;
77
+ if (!isAdapterFactory(factory)) throw new Error(`${PACKAGE_NAME}: @astrojs/cloudflare has no default export`);
78
+ let configPath: string | undefined;
79
+ if (mode === 'd3') {
80
+ const path = wranglerConfigPath(root);
81
+ const child = { ...(path === undefined ? {} : (parseWranglerConfig(readFileSync(path, 'utf8')) ?? {})) };
82
+ delete child.main;
83
+ delete child.assets;
84
+ if (isRecord(child.env)) {
85
+ const blocks = { ...child.env };
86
+ for (const [name, block] of Object.entries(blocks)) {
87
+ if (!isRecord(block)) continue;
88
+ const kept = { ...block };
89
+ delete kept.main;
90
+ delete kept.assets;
91
+ blocks[name] = kept;
92
+ }
93
+ child.env = blocks;
94
+ }
95
+ configPath = join(root, '.conloca', 'wrangler.child.json');
96
+ mkdirSync(join(root, '.conloca'), { recursive: true });
97
+ writeFileSync(configPath, `${JSON.stringify(child, null, 2)}\n`);
98
+ }
99
+ const adapter = factory(childAdapterOptions(mode, configPath));
100
+ if (!isIntegration(adapter))
101
+ throw new Error(`${PACKAGE_NAME}: @astrojs/cloudflare did not return an Astro integration`);
102
+ return adapter;
103
+ }
@@ -1,27 +1,18 @@
1
1
  /**
2
- * Minimal cookie-header parser. We only need to look up cookies by exact name
3
- * (the secret-derived preview cookie); a full RFC 6265 parser would be
4
- * overkill, and pulling in a dependency for this would be YAGNI.
5
- *
6
- * The parser intentionally rejects malformed segments silently rather than
7
- * throwing — a bad cookie header from a misbehaving client must not crash
8
- * the SSR handler. Callers always check whether the requested cookie was
9
- * actually present.
2
+ * Every value a cookie header carries under `name`, in header order. A browser sends one cookie per name, domain and
3
+ * path it holds, so a sibling subdomain can plant a second cookie with the preview's name: callers try each value,
4
+ * never just the first. Malformed segments are skipped, not thrown on: a bad header from a misbehaving client must
5
+ * not crash the handler.
10
6
  */
11
- export function parseCookies(cookieHeader: string | null | undefined): Map<string, string> {
12
- const out = new Map<string, string>();
13
- if (!cookieHeader) return out;
7
+ export function parseCookieValues(cookieHeader: string | null | undefined, name: string): string[] {
8
+ if (!cookieHeader) return [];
9
+ const values: string[] = [];
14
10
  for (const segment of cookieHeader.split(';')) {
15
11
  const eq = segment.indexOf('=');
16
12
  if (eq <= 0) continue;
17
- const name = segment.slice(0, eq).trim();
18
- const value = segment.slice(eq + 1).trim();
19
- if (!name) continue;
20
- // First occurrence wins; matches the spec-compliant behaviour of the
21
- // browsers' document.cookie reader for duplicate names.
22
- if (!out.has(name)) out.set(name, value);
13
+ if (segment.slice(0, eq).trim() === name) values.push(segment.slice(eq + 1).trim());
23
14
  }
24
- return out;
15
+ return values;
25
16
  }
26
17
 
27
18
  /**
@@ -30,7 +21,10 @@ export function parseCookies(cookieHeader: string | null | undefined): Map<strin
30
21
  *
31
22
  * Splitting this out from the middleware keeps the request handler
32
23
  * declarative and lets the cookie defaults be reviewed in one place: the
33
- * secret must never leak into a script-readable cookie.
24
+ * pass must never leak into a script-readable cookie.
25
+ *
26
+ * These defaults meet the `__Host-` prefix rules the cookie name relies on:
27
+ * Secure, `Path=/` and no `Domain`, so no other host can set or read it.
34
28
  *
35
29
  * `SameSite=Lax`, not `Strict`: the share link always arrives from the editor
36
30
  * origin, and Chrome withholds a `Strict` cookie on the request that FOLLOWS a
@@ -39,16 +33,16 @@ export function parseCookies(cookieHeader: string | null | undefined): Map<strin
39
33
  * cross-site POSTs and subresource loads, which is the threat that matters for
40
34
  * a read-only preview credential.
41
35
  *
42
- * `Path=/` is load-bearing: the browser sends the cookie on every same-origin
43
- * request, which is what lets the preview follow internal links instead of
44
- * surviving exactly one page view.
36
+ * `Path=/` is load-bearing for D2 and D4: the browser sends the cookie on every same-origin request, which is what
37
+ * lets the preview follow internal links instead of surviving exactly one page view. D3 passes its route instead:
38
+ * there every page link is rewritten under it, and two branches keep two cookies.
45
39
  *
46
40
  * `maxAgeSeconds` bounds the cookie to the credential it carries — pass the
47
41
  * JWT's remaining lifetime so a stale cookie cannot outlive the token and
48
42
  * strand the visitor on the landing page.
49
43
  */
50
- export function serializePreviewCookie(name: string, value: string, maxAgeSeconds?: number): string {
51
- const base = `${name}=${value}; HttpOnly; Secure; SameSite=Lax; Path=/`;
44
+ export function serializePreviewCookie(name: string, value: string, maxAgeSeconds?: number, path = '/'): string {
45
+ const base = `${name}=${value}; HttpOnly; Secure; SameSite=Lax; Path=${path}`;
52
46
  if (maxAgeSeconds === undefined) return base;
53
47
  return `${base}; Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}`;
54
48
  }