@avocadostudio-ai/astro 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Avocado Studio Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # @avocadostudio-ai/astro
2
+
3
+ The Avocado Studio integration for Astro. Install it, name your content module,
4
+ and the editor can open your site — with your own `.astro` components doing the
5
+ rendering. No React islands, nothing ported, no second copy of your templates.
6
+
7
+ ```bash
8
+ npm install @avocadostudio-ai/astro @avocadostudio-ai/site-sdk @avocadostudio-ai/shared
9
+ ```
10
+
11
+ ```ts astro.config.ts
12
+ import { defineConfig } from "astro/config"
13
+ import avocado from "@avocadostudio-ai/astro"
14
+
15
+ export default defineConfig({
16
+ output: "static",
17
+ integrations: [
18
+ avocado({
19
+ siteId: "my-site",
20
+ content: "./src/avocado/content.ts",
21
+ editablePages: ["src/pages/index.astro"],
22
+ }),
23
+ ],
24
+ })
25
+ ```
26
+
27
+ That is the wiring. The integration mounts the five `/api/editor/*` routes,
28
+ injects the preview bridge, and makes the pages you named renderable on demand
29
+ in `astro dev`.
30
+
31
+ ## The site renders itself
32
+
33
+ Avocado supplies the schema, the draft props, the editable markers and
34
+ publishing. Your components render. This is the mode Avocado calls
35
+ *site-renders-itself*, and it is what makes Astro workable at all: the
36
+ alternative would be re-implementing every `.astro` component as a React block,
37
+ which is a rewrite disguised as an integration.
38
+
39
+ What you provide is a **content module** — one default export saying where your
40
+ content lives:
41
+
42
+ ```ts src/avocado/content.ts
43
+ import type { PageDoc } from "@avocadostudio-ai/shared"
44
+ import { registerFieldTable } from "@avocadostudio-ai/site-sdk/lens"
45
+ import { FIELD_TABLE } from "./field-table"
46
+ import { getPages, writePage } from "./pages"
47
+
48
+ export default {
49
+ getPages: async (): Promise<PageDoc[]> => getPages(),
50
+ registerBlocks: () => registerFieldTable(FIELD_TABLE),
51
+ blockTypes: Object.keys(FIELD_TABLE),
52
+ onPublish: async (pages: PageDoc[]) => {
53
+ for (const page of pages) await writePage(page)
54
+ return { ok: true }
55
+ },
56
+ }
57
+ ```
58
+
59
+ On a static template, `onPublish` writing the page back to a file under `src/`
60
+ is not a limitation to work around — it is what "published" means. The file is
61
+ committed, reviewed as a diff, and the site rebuilt from it.
62
+
63
+ `content` is a **path**, not a value. The editor API route has to render on
64
+ demand, and `astro build` fails on an on-demand route in `src/pages` when there
65
+ is no adapter — whether or not anyone intends to serve it. So the integration
66
+ injects the route itself, and needs somewhere to import your content from.
67
+
68
+ ## `editablePages` — why it is a list
69
+
70
+ The pages you name render on demand during `astro dev` and are prerendered in a
71
+ build. Both halves are load-bearing.
72
+
73
+ A prerendered route has no request: `Astro.request.headers` is empty, so the
74
+ middleware sees no `__editor` parameter and no draft cookie, and resolves every
75
+ request as a visitor's. The preview then renders the *published* page —
76
+ correctly, and with no editable markers — which looks exactly like an
77
+ integration nobody wired up.
78
+
79
+ Your site cannot opt out of that on its own. `export const prerender = false`
80
+ makes `astro build` fail with `NoAdapterInstalled`, and `!import.meta.env.DEV`
81
+ is not a literal by the time Astro's route analysis reads it, so the route stays
82
+ prerendered regardless.
83
+
84
+ It is a list rather than "every page" because a route built from
85
+ `getStaticPaths` cannot render on demand at all.
86
+
87
+ ## Marking a field editable
88
+
89
+ `blockProps` returns the attributes the overlay looks for. Pass it the editor
90
+ flag the middleware left on `Astro.locals`, and a published page emits nothing
91
+ at all — no classes, no data attributes, no view-transition names.
92
+
93
+ ```astro
94
+ ---
95
+ import { blockProps } from "@avocadostudio-ai/astro/markers"
96
+
97
+ const { avocado } = Astro.locals
98
+ const { block } = Astro.props
99
+ ---
100
+ <section {...blockProps(Boolean(avocado?.isEditor), block.id, block.type)}>
101
+ <h1 data-editable-target="title">{block.props.title}</h1>
102
+ </section>
103
+ ```
104
+
105
+ `Astro.locals.avocado` also carries `editorQuery` — append it to every link the
106
+ page renders, or the first in-preview navigation lands on the published page
107
+ instead of the draft.
108
+
109
+ ## Entry points
110
+
111
+ | Import | What it is |
112
+ | --- | --- |
113
+ | `@avocadostudio-ai/astro` | the integration, plus `AvocadoIntegrationOptions` |
114
+ | `@avocadostudio-ai/astro/runtime` | `resolveEditorRequest`, `AvocadoLocals` |
115
+ | `@avocadostudio-ai/astro/markers` | `blockProps` and the field kinds |
116
+ | `@avocadostudio-ai/astro/middleware` | `createAvocadoMiddleware`, if you compose your own |
117
+ | `@avocadostudio-ai/astro/editor-api` | `createAvocadoEditorApi`, if you mount the route yourself |
118
+ | `@avocadostudio-ai/astro/bridge` | `startAvocadoBridge`, for a custom preview script |
119
+
120
+ Most sites need only the first and the middle two. The last three exist for
121
+ sites that already own their middleware chain or their API routing.
122
+
123
+ ## Documentation
124
+
125
+ Full walkthrough, the field table, and the publishing contract:
126
+ [docs.avocadostudio.dev](https://docs.avocadostudio.dev)
@@ -0,0 +1,30 @@
1
+ export type AvocadoBridgeOptions = {
2
+ /** The content slug this page renders. Defaults to `location.pathname`. */
3
+ slug?: string;
4
+ /** The editor's origin. Read from the page URL when omitted. */
5
+ editorOrigin?: string;
6
+ };
7
+ /**
8
+ * Carry the editor's parameters onto a link.
9
+ *
10
+ * Without this the first click inside the preview loads a document with no
11
+ * `__editor`, no session and no secret — the published page, in the editor's
12
+ * own iframe, with no bridge on it. The signed cookie covers the same ground,
13
+ * but only where third-party cookies are allowed, which is exactly the
14
+ * condition that cannot be relied on inside a cross-origin iframe.
15
+ */
16
+ export declare function withEditorParams(href: string, from?: URLSearchParams): string;
17
+ /**
18
+ * Start the bridge and keep it attached across client-side navigation.
19
+ *
20
+ * `<ClientRouter />` swaps the document on navigation, so listeners bound to the
21
+ * old nodes survive as references to elements that are no longer in the page:
22
+ * the preview keeps rendering and silently stops responding to the editor.
23
+ * Re-attaching on `astro:page-load` — which fires on the initial load as well as
24
+ * every swap — is what keeps that from happening, and detaching on
25
+ * `astro:before-swap` is what keeps the overlay from being carried into the next
26
+ * document.
27
+ *
28
+ * Returns a function that stops the bridge entirely.
29
+ */
30
+ export declare function startAvocadoBridge(options?: AvocadoBridgeOptions): () => void;
package/dist/bridge.js ADDED
@@ -0,0 +1,125 @@
1
+ import { attachBridge, attachImageRevealWatcher, postRouteChanged } from "@avocadostudio-ai/preview-adapter/bridge-controller";
2
+ /** Query parameters that must survive every in-preview navigation. */
3
+ const EDITOR_PARAMS = ["__editor", "session", "siteId", "editorOrigin", "secret"];
4
+ /**
5
+ * Carry the editor's parameters onto a link.
6
+ *
7
+ * Without this the first click inside the preview loads a document with no
8
+ * `__editor`, no session and no secret — the published page, in the editor's
9
+ * own iframe, with no bridge on it. The signed cookie covers the same ground,
10
+ * but only where third-party cookies are allowed, which is exactly the
11
+ * condition that cannot be relied on inside a cross-origin iframe.
12
+ */
13
+ export function withEditorParams(href, from = new URLSearchParams(location.search)) {
14
+ const url = new URL(href, location.origin);
15
+ for (const key of EDITOR_PARAMS) {
16
+ const value = from.get(key);
17
+ if (value !== null && !url.searchParams.has(key))
18
+ url.searchParams.set(key, value);
19
+ }
20
+ return `${url.pathname}${url.search}${url.hash}`;
21
+ }
22
+ /**
23
+ * Replace `<main>` with the same page re-fetched from the server.
24
+ *
25
+ * This is `refresh`, and it is emphatically not `location.reload()`.
26
+ * `smoothRefresh()` in the bridge schedules `restoreAndFocus()` behind two
27
+ * animation frames and then polls `applyBlockFocus` twenty times at 45 ms, so
28
+ * that the block being edited keeps its caret and scroll position across a
29
+ * refresh. A document reload destroys every one of those timers along with the
30
+ * DOM they were about to act on, so the caret jumps to the top of the page on
31
+ * each committed keystroke.
32
+ *
33
+ * Swapping only `<main>` also leaves the bridge's own overlay chrome — badges,
34
+ * handles, highlights — outside the replaced subtree, where the mutation
35
+ * observer can reconcile it rather than rebuild it.
36
+ */
37
+ async function refreshMain() {
38
+ const response = await fetch(location.href, { headers: { "x-avocado-refresh": "1" }, cache: "no-store" });
39
+ if (!response.ok)
40
+ return;
41
+ const html = await response.text();
42
+ const incoming = new DOMParser().parseFromString(html, "text/html").querySelector("main");
43
+ const current = document.querySelector("main");
44
+ if (incoming && current)
45
+ current.replaceWith(incoming);
46
+ }
47
+ /**
48
+ * Start the bridge and keep it attached across client-side navigation.
49
+ *
50
+ * `<ClientRouter />` swaps the document on navigation, so listeners bound to the
51
+ * old nodes survive as references to elements that are no longer in the page:
52
+ * the preview keeps rendering and silently stops responding to the editor.
53
+ * Re-attaching on `astro:page-load` — which fires on the initial load as well as
54
+ * every swap — is what keeps that from happening, and detaching on
55
+ * `astro:before-swap` is what keeps the overlay from being carried into the next
56
+ * document.
57
+ *
58
+ * Returns a function that stops the bridge entirely.
59
+ */
60
+ export function startAvocadoBridge(options = {}) {
61
+ const params = new URLSearchParams(location.search);
62
+ const editorOrigin = options.editorOrigin ?? params.get("editorOrigin") ?? "";
63
+ // Not in the editor's iframe, or no origin to talk to: do nothing at all.
64
+ if (!editorOrigin || window.parent === window)
65
+ return () => { };
66
+ /*
67
+ * The overlay's stylesheet — block outlines, hover affordances, inline-edit
68
+ * cursors. Without it every marker is in the document and none of it is
69
+ * visible, which is the most confusing way for an integration to be wrong.
70
+ *
71
+ * Imported dynamically, and deliberately *after* the iframe check: Vite emits
72
+ * it as its own chunk, so a visitor on the published site never requests it.
73
+ * A static import would put it in the page's stylesheet for everyone.
74
+ */
75
+ void import("@avocadostudio-ai/preview-adapter/styles.css");
76
+ let detach = null;
77
+ let detachReveal = null;
78
+ const attach = () => {
79
+ detach?.();
80
+ detachReveal?.();
81
+ const slug = options.slug ?? location.pathname;
82
+ detach = attachBridge({
83
+ slug,
84
+ editorOrigin,
85
+ pathname: location.pathname,
86
+ navigate: (href) => {
87
+ const target = withEditorParams(href);
88
+ /*
89
+ * `<ClientRouter />` exposes no imperative navigate, and a bare
90
+ * `pushState` changes the URL without rendering anything. A same-origin
91
+ * assignment is the honest primitive here: it is a real navigation, the
92
+ * editor parameters are on it, and the bridge re-attaches on the
93
+ * `astro:page-load` that follows.
94
+ */
95
+ location.assign(target);
96
+ },
97
+ refresh: () => {
98
+ void refreshMain();
99
+ },
100
+ liveStore: null,
101
+ });
102
+ detachReveal = attachImageRevealWatcher();
103
+ postRouteChanged(slug, editorOrigin);
104
+ };
105
+ const teardown = () => {
106
+ detach?.();
107
+ detachReveal?.();
108
+ detach = null;
109
+ detachReveal = null;
110
+ };
111
+ document.addEventListener("astro:page-load", attach);
112
+ document.addEventListener("astro:before-swap", teardown);
113
+ /*
114
+ * `astro:page-load` does not fire on a page without `<ClientRouter />`, and
115
+ * on a page with it the event has usually already fired by the time a
116
+ * module script runs. Attaching once here covers both; `attach` detaches
117
+ * first, so the duplicate case costs one teardown.
118
+ */
119
+ attach();
120
+ return () => {
121
+ document.removeEventListener("astro:page-load", attach);
122
+ document.removeEventListener("astro:before-swap", teardown);
123
+ teardown();
124
+ };
125
+ }
@@ -0,0 +1,19 @@
1
+ import type { DraftRouteAdapter } from "@avocadostudio-ai/site-sdk/routes/core";
2
+ /**
3
+ * What `createDraftEnableHandlerCore` needs from a framework, answered for
4
+ * Astro.
5
+ *
6
+ * Next's version of this calls `draftMode().enable()` and lets the framework
7
+ * set its own cookie. Astro has no draft mode, so enabling one means setting
8
+ * ours — but the core calls `enableDraftMode()` before it has resolved which
9
+ * session the redirect is for, and that session is what the cookie has to
10
+ * carry. So enabling records the intent, and the cookie is minted in
11
+ * `createRedirect`, where the session is finally known.
12
+ *
13
+ * The same adapter instance therefore cannot be shared across requests. The
14
+ * handler factories take it per call; `createAstroDraftAdapter()` is called per
15
+ * request, which is also why it holds no state beyond a boolean.
16
+ */
17
+ export declare function createAstroDraftAdapter(options?: {
18
+ secret?: string;
19
+ }): DraftRouteAdapter;
@@ -0,0 +1,67 @@
1
+ import { ASTRO_DRAFT_COOKIE, DRAFT_COOKIE_MAX_AGE_SECONDS, draftSecret, mintDraftCookie } from "./draft-cookie.js";
2
+ /**
3
+ * What `createDraftEnableHandlerCore` needs from a framework, answered for
4
+ * Astro.
5
+ *
6
+ * Next's version of this calls `draftMode().enable()` and lets the framework
7
+ * set its own cookie. Astro has no draft mode, so enabling one means setting
8
+ * ours — but the core calls `enableDraftMode()` before it has resolved which
9
+ * session the redirect is for, and that session is what the cookie has to
10
+ * carry. So enabling records the intent, and the cookie is minted in
11
+ * `createRedirect`, where the session is finally known.
12
+ *
13
+ * The same adapter instance therefore cannot be shared across requests. The
14
+ * handler factories take it per call; `createAstroDraftAdapter()` is called per
15
+ * request, which is also why it holds no state beyond a boolean.
16
+ */
17
+ export function createAstroDraftAdapter(options) {
18
+ let enabled = false;
19
+ const secret = options?.secret ?? draftSecret();
20
+ const cookieHeader = (name, value, maxAge) => [
21
+ `${name}=${value}`,
22
+ "Path=/",
23
+ `Max-Age=${maxAge}`,
24
+ "HttpOnly",
25
+ /*
26
+ * `SameSite=None; Secure`, not `Lax`. The site is rendered in the
27
+ * editor's cross-origin iframe, and a `Lax` cookie is not sent on those
28
+ * subresource requests at all — the cookie would be set and then never
29
+ * arrive, which is precisely the failure the cookie exists to prevent.
30
+ * `Secure` is mandatory alongside `None`, so preview over plain http
31
+ * works only on localhost, where browsers exempt it.
32
+ */
33
+ "SameSite=None",
34
+ "Secure",
35
+ ].join("; ");
36
+ return {
37
+ enableDraftMode: async () => {
38
+ enabled = true;
39
+ },
40
+ disableDraftMode: async () => {
41
+ enabled = false;
42
+ },
43
+ createRedirect: (url, cookies) => {
44
+ const headers = new Headers({ Location: url.toString() });
45
+ for (const c of cookies ?? []) {
46
+ headers.append("Set-Cookie", c.delete ? cookieHeader(c.name, "", 0) : cookieHeader(c.name, c.value, DRAFT_COOKIE_MAX_AGE_SECONDS));
47
+ }
48
+ if (enabled) {
49
+ const session = url.searchParams.get("session")?.trim() || "dev";
50
+ const siteId = url.searchParams.get("siteId")?.trim() || "";
51
+ const value = mintDraftCookie({ session, siteId }, secret);
52
+ /*
53
+ * No secret, no cookie — not an unsigned one. Verification would then
54
+ * have to accept unsigned cookies to be useful, which is the same as
55
+ * having no cookie check at all.
56
+ */
57
+ if (value)
58
+ headers.append("Set-Cookie", cookieHeader(ASTRO_DRAFT_COOKIE, value, DRAFT_COOKIE_MAX_AGE_SECONDS));
59
+ }
60
+ else {
61
+ headers.append("Set-Cookie", cookieHeader(ASTRO_DRAFT_COOKIE, "", 0));
62
+ }
63
+ // 307: the method survives, and a preview redirect is never permanent.
64
+ return new Response(null, { status: 307, headers });
65
+ },
66
+ };
67
+ }
@@ -0,0 +1,26 @@
1
+ export declare const ASTRO_DRAFT_COOKIE = "avocado_draft";
2
+ /** The draft session this cookie authorizes. */
3
+ export type DraftCookiePayload = {
4
+ session: string;
5
+ siteId: string;
6
+ /** Unix seconds. */
7
+ exp: number;
8
+ };
9
+ /** How long a draft cookie stays valid. An editing session outlives a short one, and a long one outlives the tab. */
10
+ export declare const DRAFT_COOKIE_MAX_AGE_SECONDS: number;
11
+ /**
12
+ * A cookie value for this draft session, or `null` when no secret is configured
13
+ * — in which case the integration must not set one at all, rather than set an
14
+ * unsigned one that verification would have to accept.
15
+ */
16
+ export declare function mintDraftCookie(payload: Omit<DraftCookiePayload, "exp">, secret: string | undefined, now?: number): string | null;
17
+ /**
18
+ * The session a cookie authorizes, or `null` if it does not.
19
+ *
20
+ * Returns null rather than throwing for every failure — malformed, unsigned,
21
+ * wrongly signed, expired — because every one of them means the same thing to
22
+ * the caller: this request is not authorized to see drafts.
23
+ */
24
+ export declare function verifyDraftCookie(value: string | undefined, secret: string | undefined, now?: number): DraftCookiePayload | null;
25
+ /** The secret both this cookie and `/api/editor/draft` are checked against. */
26
+ export declare function draftSecret(env?: Record<string, string | undefined>): string | undefined;