@tinacms/astro 0.0.0-00ff25a-20260605030238

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 (75) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +178 -0
  3. package/dist/bridge.d.ts +7 -0
  4. package/dist/bridge.js +2 -0
  5. package/dist/data.d.ts +19 -0
  6. package/dist/data.js +64 -0
  7. package/dist/data.test-d.d.ts +1 -0
  8. package/dist/experimental.d.ts +10 -0
  9. package/dist/experimental.js +87 -0
  10. package/dist/index.d.ts +36 -0
  11. package/dist/index.js +94 -0
  12. package/dist/integration.d.ts +12 -0
  13. package/dist/integration.js +93 -0
  14. package/dist/internal/admin-origin.d.ts +6 -0
  15. package/dist/internal/escape.d.ts +8 -0
  16. package/dist/internal/forms-store.d.ts +12 -0
  17. package/dist/internal/request-context.d.ts +16 -0
  18. package/dist/is-edit-mode.d.ts +32 -0
  19. package/dist/is-edit-mode.js +37 -0
  20. package/dist/island-route.d.ts +18 -0
  21. package/dist/island-route.js +87 -0
  22. package/dist/middleware.d.ts +3 -0
  23. package/dist/middleware.js +123 -0
  24. package/dist/sanitize.d.ts +12 -0
  25. package/dist/sanitize.js +41 -0
  26. package/dist/tina-field.d.ts +1 -0
  27. package/dist/tina-field.js +2 -0
  28. package/dist/types.d.ts +92 -0
  29. package/dist/types.js +0 -0
  30. package/dist/vite.d.ts +21 -0
  31. package/dist/vite.js +24 -0
  32. package/package.json +151 -0
  33. package/src/CodeBlockNode.astro +28 -0
  34. package/src/Container.astro +56 -0
  35. package/src/ImageNode.astro +17 -0
  36. package/src/Leaf.astro +42 -0
  37. package/src/LinkNode.astro +22 -0
  38. package/src/MdxNode.astro +24 -0
  39. package/src/Node.astro +73 -0
  40. package/src/TinaIsland.astro +44 -0
  41. package/src/TinaMarkdown.astro +36 -0
  42. package/src/__tests__/IslandStub.astro +8 -0
  43. package/src/__tests__/TinaIsland.test.ts +60 -0
  44. package/src/__tests__/TinaMarkdown.test.ts +112 -0
  45. package/src/__tests__/__snapshots__/TinaMarkdown.test.ts.snap +7 -0
  46. package/src/__tests__/fixtures/FancyHeading.astro +3 -0
  47. package/src/__tests__/fixtures/MyFeature.astro +4 -0
  48. package/src/__tests__/fixtures/basic-kitchen-sink.json +60 -0
  49. package/src/__tests__/fixtures/code-block.json +34 -0
  50. package/src/__tests__/fixtures/leaf-marks.json +199 -0
  51. package/src/__tests__/fixtures/mdx-jsx-flow.json +40 -0
  52. package/src/__tests__/fixtures/mdx-jsx-text.json +53 -0
  53. package/src/__tests__/forms-store.test.ts +70 -0
  54. package/src/__tests__/integration.test.ts +228 -0
  55. package/src/__tests__/island-route.test.ts +119 -0
  56. package/src/__tests__/middleware.test.ts +102 -0
  57. package/src/__tests__/sanitize.test.ts +75 -0
  58. package/src/__tests__/vite.test.ts +67 -0
  59. package/src/bridge.ts +7 -0
  60. package/src/data.test-d.ts +53 -0
  61. package/src/data.ts +73 -0
  62. package/src/experimental.ts +14 -0
  63. package/src/index.ts +54 -0
  64. package/src/integration.ts +162 -0
  65. package/src/internal/admin-origin.ts +19 -0
  66. package/src/internal/escape.ts +15 -0
  67. package/src/internal/forms-store.ts +50 -0
  68. package/src/internal/request-context.ts +23 -0
  69. package/src/is-edit-mode.ts +68 -0
  70. package/src/island-route.ts +109 -0
  71. package/src/middleware.ts +89 -0
  72. package/src/sanitize.ts +64 -0
  73. package/src/tina-field.ts +1 -0
  74. package/src/types.ts +97 -0
  75. package/src/vite.ts +40 -0
package/LICENSE ADDED
@@ -0,0 +1,176 @@
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 reasonable and customary use in describing the
141
+ origin of the Work and 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 Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,178 @@
1
+ # @tinacms/astro
2
+
3
+ The one-stop [TinaCMS](https://tina.io) integration for Astro. Ships:
4
+
5
+ - A vanilla-Astro **rich-text renderer** that mirrors the React `TinaMarkdown` API — same `content` prop, same `components` map shape, but emits pure HTML with no React in the page tree.
6
+ - The framework-agnostic **`@tinacms/bridge`** re-exported under `@tinacms/astro/bridge` so you only install one package.
7
+
8
+ > **Adopting in a new project?** Follow the step-by-step [GETTING_STARTED.md](./GETTING_STARTED.md) — covers install (incl. `@tinacms/cli`), integration wiring, data loaders, island registry, and troubleshooting. The rest of this README is the API reference.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pnpm add @tinacms/astro tinacms
14
+ pnpm add -D @tinacms/cli
15
+ ```
16
+
17
+ Requires Astro 5 or 6 and an SSR adapter (`@astrojs/node`, `vercel`, `netlify`, or `cloudflare`) — the island-refresh endpoint (`/tina-island/[name]`) is on-demand. `output: 'server'` is the simplest choice; `output: 'static'` also works as long as editable regions are wrapped in [`<TinaIsland>`](#static-site-editing) and the adapter can serve that one on-demand route.
18
+
19
+ ## Usage
20
+
21
+ Add the integration to `astro.config.mjs` once. It wires the request-scoped middleware and stages the bundled bridge as a static asset at `/admin/bridge.js` — everything else is auto-injected only on edit-mode requests:
22
+
23
+ ```ts
24
+ // astro.config.mjs
25
+ import { defineConfig } from 'astro/config';
26
+ import tina from '@tinacms/astro/integration';
27
+
28
+ export default defineConfig({
29
+ integrations: [tina()],
30
+ });
31
+ ```
32
+
33
+ Then load data the same way you would in any TinaCMS project — call the generated client, wrap the result with `requestWithMetadata()`:
34
+
35
+ ```astro
36
+ ---
37
+ import TinaMarkdown from '@tinacms/astro/TinaMarkdown.astro';
38
+ import { requestWithMetadata, tinaField } from '@tinacms/astro';
39
+ import client from '../tina/__generated__/client';
40
+
41
+ const post = await requestWithMetadata(
42
+ client.queries.post({ relativePath: 'hello.md' }),
43
+ );
44
+ ---
45
+ <article>
46
+ <h1 data-tina-field={tinaField(post.data.post, 'title')}>
47
+ {post.data.post.title}
48
+ </h1>
49
+ <div data-tina-field={tinaField(post.data.post, '_body')}>
50
+ <TinaMarkdown content={post.data.post._body} />
51
+ </div>
52
+ </article>
53
+ ```
54
+
55
+ That's the whole user surface. No wiring component in your layout, no `forms` prop to maintain, no `Astro.request` to thread. The integration's middleware buffers each HTML response, and on edit-mode requests splices the form payloads and a `<script type="module" src="/admin/bridge.js">` before `</head>`. Production visitors get **byte-identical HTML to a Tina-free Astro app** — no `data-tina-form` divs, no script tag, no bundle preload. (Exception: pages that use [`<TinaIsland>`](#static-site-editing) carry a one-line inline bootstrap so editing also works when the page is statically built.)
56
+
57
+ For cross-origin admin deployments (Codespaces, separate-domain self-hosted), set `PUBLIC_TINA_ADMIN_ORIGIN` in your env (comma-separate to allow multiple). The middleware embeds it inline so the bridge validates inbound `postMessage` events.
58
+
59
+ ## Static-site editing
60
+
61
+ `output: 'static'` is supported. The middleware described above only runs on on-demand-rendered routes, so on a prerendered page it never injects anything — instead, **`<TinaIsland>` emits a tiny in-iframe bootstrap script** that loads `/admin/bridge.js` *only* when the page is inside the admin iframe (a no-op for everyone else). On boot the bridge "primes" the page by fetching each island's `/tina-island/[name]` endpoint — which is `prerender = false`, so the adapter still renders it on demand — to pick up the page's form payloads, after which editing works exactly as it does in an SSR project.
62
+
63
+ Requirements for static editing:
64
+
65
+ - Wrap every editable region in `<TinaIsland>` with a registered island (see [GETTING_STARTED.md](./GETTING_STARTED.md) steps 5–7) — that's both how the bridge re-renders regions and how the bootstrap gets onto the page.
66
+ - Pass `primary` on your page's main `<TinaIsland>` (`<TinaIsland name="post" params={{ slug }} primary>`). On a static page the bridge can't tell which island is "the page", so without this the editor may land on the multi-document "Referenced Files" list when the page also has e.g. a global-config form. (On SSR pages the first `requestWithMetadata()` call is treated as primary automatically; pass `{ priority: 'primary' }` as the second argument if you need to override that.) Mark at most one per page.
67
+ - Keep the `tina-island/[name].ts` route (`export const prerender = false`).
68
+
69
+ Trade-off: a page that uses `<TinaIsland>` carries that one-line inline bootstrap in its production HTML, so it's no longer byte-identical to a Tina-free Astro app. Pages without `<TinaIsland>` are unaffected. (On `output: 'server'` the middleware path is unchanged; the bootstrap and the middleware's own injection coexist harmlessly — `bridge.init()` is idempotent.)
70
+
71
+ ## Subpath exports
72
+
73
+ | Subpath | What it gives you |
74
+ |---------|-------------------|
75
+ | `@tinacms/astro` | `requestWithMetadata`, `tinaField`, `QueryResult`, and types |
76
+ | `@tinacms/astro/TinaMarkdown.astro` | `<TinaMarkdown content components />` — rich-text renderer. Import from this subpath so Astro's check sees a real `.astro` component (the bare-package default resolves through the types condition to a placeholder). |
77
+ | `@tinacms/astro/integration` | `tina()` integration — auto-wires the middleware and stages the static `/admin/bridge.js` asset so `requestWithMetadata()` works without you threading `Astro.request` or writing wiring components |
78
+ | `@tinacms/astro/TinaIsland.astro` | `<TinaIsland name wrapper params [primary] />` — marker wrapper for an editable region; pass `primary` on the page's main region so the editor opens that form instead of the "Referenced Files" list |
79
+ | `@tinacms/astro/types` | `TinaRichTextContent`, `CustomComponentsMap`, `TinaRichTextNode`, `MdxElement`, `TextElement` |
80
+ | `@tinacms/astro/sanitize` | `sanitizeHref` / `sanitizeImageSrc` for CMS-supplied URLs |
81
+ | `@tinacms/astro/bridge` | `init`, `refreshForms`, and the rest of `@tinacms/bridge` |
82
+ | `@tinacms/astro/tina-field` | `tinaField()` helper |
83
+ | `@tinacms/astro/is-edit-mode` | `isEditMode(request)` — server-side admin-iframe detection |
84
+ | `@tinacms/astro/middleware` | The middleware the integration auto-wires — exported here in case you need to compose it manually |
85
+ | `@tinacms/astro/vite` | `tinaAdminDevRedirect()` — dev-only Vite plugin that redirects `/admin` and `/admin/` to `/admin/index.html` so the admin SPA is reachable from a bare URL during `astro dev` |
86
+ | `@tinacms/astro/experimental` | `experimental_createIslandRoute()` — opt-in helper built on Astro's unstable `experimental_AstroContainer` |
87
+
88
+ ## Custom MDX components
89
+
90
+ Register Astro components against the names Tina uses for them in the editor:
91
+
92
+ ```astro
93
+ ---
94
+ import TinaMarkdown from '@tinacms/astro/TinaMarkdown.astro';
95
+ import type { CustomComponentsMap } from '@tinacms/astro/types';
96
+ import BlockQuote from '../components/BlockQuote.astro';
97
+ import NewsletterSignup from '../components/NewsletterSignup.astro';
98
+
99
+ const components: CustomComponentsMap = {
100
+ BlockQuote,
101
+ NewsletterSignup,
102
+ };
103
+ ---
104
+ <TinaMarkdown content={post.data.post._body} components={components} />
105
+ ```
106
+
107
+ The renderer dispatches `mdxJsxFlowElement` and `mdxJsxTextElement` nodes by `node.name`. Unknown names render a visible placeholder so you spot missing registrations during development.
108
+
109
+ ## Default-tag overrides
110
+
111
+ The same `components` map can override the default HTML tag a node renders to. Useful for styling without forking the renderer:
112
+
113
+ ```ts
114
+ const components: CustomComponentsMap = {
115
+ p: Paragraph, // Tailwind-styled <p>
116
+ h1: Heading1,
117
+ blockquote: BlockquoteTag,
118
+ code_block: CodeBlock, // e.g. shiki-highlighted
119
+ a: Anchor,
120
+ img: Img,
121
+ };
122
+ ```
123
+
124
+ Supported override keys: `p`, `h1`–`h6`, `ul`, `ol`, `li`, `blockquote`, `lic`, `a`, `img`, `code_block`, `hr`, `break`.
125
+
126
+ ## Visual editing markers
127
+
128
+ The renderer doesn't emit `data-tina-field` attributes — wrap the call site to add them at whatever granularity makes sense:
129
+
130
+ ```astro
131
+ ---
132
+ import TinaMarkdown from '@tinacms/astro/TinaMarkdown.astro';
133
+ import { tinaField } from '@tinacms/astro/tina-field';
134
+ ---
135
+ <div data-tina-field={tinaField(post.data.post, '_body')}>
136
+ <TinaMarkdown content={post.data.post._body} components={components} />
137
+ </div>
138
+ ```
139
+
140
+ Coarse-grained boundaries (the whole `_body`) are usually what you want — clicking any rich-text node focuses the editor on that field.
141
+
142
+ ## Supported node types
143
+
144
+ | Type | Default rendering | Override key |
145
+ |------|-------------------|--------------|
146
+ | `p`, `h1`–`h6` | `<p>`, `<h1>`–`<h6>` | same |
147
+ | `ul`, `ol`, `li` | `<ul>`, `<ol>`, `<li>` | same |
148
+ | `blockquote` | `<blockquote>` | `blockquote` |
149
+ | `lic` | `<div>` | `lic` |
150
+ | `a` | `<a href={sanitized}>` | `a` |
151
+ | `img` | `<img src={sanitized}>` | `img` |
152
+ | `code_block` | `<pre><code class="language-…">` | `code_block` |
153
+ | `hr` | `<hr>` | `hr` |
154
+ | `break` | `<br>` | `break` |
155
+ | `text` (with `bold`/`italic`/`underline`/`strikethrough`/`code`/`highlight`) | nested `<strong>`/`<em>`/`<u>`/`<s>`/`<code>`/`<mark>` | n/a |
156
+ | `mdxJsxFlowElement`, `mdxJsxTextElement` | dispatched by `node.name` | n/a — register by name |
157
+ | `html`, `html_inline` | raw HTML via `set:html` | n/a |
158
+ | `invalid_markdown` | `<pre>{value}</pre>` | n/a |
159
+
160
+ CMS-supplied URLs in `a` and `img` nodes pass through `sanitizeHref` / `sanitizeImageSrc`, blocking `javascript:`, `data:`, `vbscript:`, and protocol-relative URLs. Both helpers are exposed on `@tinacms/astro/sanitize` for use in your own components (e.g. block-level Hero images, navigation anchors).
161
+
162
+ ## Testing
163
+
164
+ Tests use Astro's [`experimental_AstroContainer`](https://docs.astro.build/en/reference/container-reference/). Fixtures are synced from `@tinacms/mdx`'s parser test corpus so renderer assertions track real editor output.
165
+
166
+ ```bash
167
+ pnpm test
168
+ ```
169
+
170
+ To pull a fresh fixture set after adding a new node type to `@tinacms/mdx`:
171
+
172
+ ```bash
173
+ pnpm sync-fixtures
174
+ ```
175
+
176
+ ## License
177
+
178
+ Apache 2.0
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Re-exports of `@tinacms/bridge` so Astro projects can pull the bridge from
3
+ * `@tinacms/astro/bridge` instead of installing it separately. The bridge
4
+ * package stays publishable on its own for non-Astro frontends (Hugo, plain
5
+ * HTML, Eleventy).
6
+ */
7
+ export * from '@tinacms/bridge';
package/dist/bridge.js ADDED
@@ -0,0 +1,2 @@
1
+ // src/bridge.ts
2
+ export * from "@tinacms/bridge";
package/dist/data.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ export interface QueryResult<TData> {
2
+ data: TData;
3
+ query: string;
4
+ variables: Record<string, unknown>;
5
+ id: string;
6
+ }
7
+ type ClientResult<TData> = {
8
+ data: TData;
9
+ query: string;
10
+ variables: Record<string, unknown>;
11
+ } | null | undefined;
12
+ export interface RequestOptions {
13
+ /** Mark the page's own document so the admin opens it on load instead
14
+ * of a layout-level global. Mirrors `useTina`'s
15
+ * `experimental___selectFormByFormId`. */
16
+ priority?: 'primary';
17
+ }
18
+ export declare function requestWithMetadata<TData>(source: ClientResult<TData> | Promise<ClientResult<TData>>, options?: RequestOptions): Promise<QueryResult<TData>>;
19
+ export {};
package/dist/data.js ADDED
@@ -0,0 +1,64 @@
1
+ // src/data.ts
2
+ import { addMetadata, hashFromQuery } from "@tinacms/bridge/metadata";
3
+ import { readOverlay } from "@tinacms/bridge/preview";
4
+
5
+ // src/internal/forms-store.ts
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
+ var STORE_KEY = Symbol.for("@tinacms/astro/forms-store");
8
+ var slot = globalThis;
9
+ var formsStore = slot[STORE_KEY] ??= new AsyncLocalStorage();
10
+ function recordForm(form) {
11
+ const list = formsStore.getStore();
12
+ if (!list) return;
13
+ const existing = list.find((entry) => entry.id === form.id);
14
+ if (existing) {
15
+ if (form.priority === "primary") existing.priority = "primary";
16
+ return;
17
+ }
18
+ list.push(form);
19
+ }
20
+
21
+ // src/internal/request-context.ts
22
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
23
+ var STORE_KEY2 = Symbol.for("@tinacms/astro/request-context");
24
+ var slot2 = globalThis;
25
+ var requestStore = slot2[STORE_KEY2] ??= new AsyncLocalStorage2();
26
+
27
+ // src/data.ts
28
+ async function requestWithMetadata(source, options) {
29
+ let result = null;
30
+ try {
31
+ result = await source ?? null;
32
+ } catch (error) {
33
+ console.warn("[@tinacms/astro] client query failed", error);
34
+ }
35
+ const query = result?.query ?? "";
36
+ const variables = result?.variables ?? {};
37
+ const id = hashFromQuery(JSON.stringify({ query, variables }));
38
+ const data = result?.data ?? {};
39
+ const request = requestStore.getStore();
40
+ let resolvedData = data;
41
+ if (request) {
42
+ const overlay = await readOverlay(request, id);
43
+ if (overlay !== void 0) {
44
+ resolvedData = overlay;
45
+ }
46
+ }
47
+ const enriched = {
48
+ data: addMetadata(id, resolvedData),
49
+ query,
50
+ variables,
51
+ id
52
+ };
53
+ recordForm({
54
+ id,
55
+ query,
56
+ variables,
57
+ data: enriched.data,
58
+ priority: options?.priority
59
+ });
60
+ return enriched;
61
+ }
62
+ export {
63
+ requestWithMetadata
64
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Experimental surface area. Anything here may change in a minor or
3
+ * patch release — opt in only when the underlying tradeoff is worth
4
+ * it for your project.
5
+ *
6
+ * `experimental_createIslandRoute` builds on Astro's
7
+ * `experimental_AstroContainer`, which Astro itself flags as unstable;
8
+ * this re-export inherits the same caveat.
9
+ */
10
+ export { experimental_createIslandRoute, type IslandConfig, type IslandRegistry, } from './island-route';
@@ -0,0 +1,87 @@
1
+ // src/island-route.ts
2
+ import { PREVIEW_CONTENT_TYPE, PRIME_HEADER } from "@tinacms/bridge/preview";
3
+ import { experimental_AstroContainer as AstroContainer } from "astro/container";
4
+
5
+ // src/internal/escape.ts
6
+ function escapeAttr(s) {
7
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
8
+ }
9
+
10
+ // src/internal/forms-store.ts
11
+ import { AsyncLocalStorage } from "node:async_hooks";
12
+ var STORE_KEY = Symbol.for("@tinacms/astro/forms-store");
13
+ var slot = globalThis;
14
+ var formsStore = slot[STORE_KEY] ??= new AsyncLocalStorage();
15
+ function sortByPriority(forms) {
16
+ return [...forms].sort(
17
+ (a, b) => (a.priority === "primary" ? 0 : 1) - (b.priority === "primary" ? 0 : 1)
18
+ );
19
+ }
20
+ function renderFormPayloadDiv(form, primary) {
21
+ return `<div data-tina-form="${escapeAttr(JSON.stringify(form))}"${primary ? " data-tina-primary" : ""} hidden></div>`;
22
+ }
23
+
24
+ // src/internal/request-context.ts
25
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
26
+ var STORE_KEY2 = Symbol.for("@tinacms/astro/request-context");
27
+ var slot2 = globalThis;
28
+ var requestStore = slot2[STORE_KEY2] ??= new AsyncLocalStorage2();
29
+
30
+ // src/island-route.ts
31
+ function experimental_createIslandRoute(islands) {
32
+ return async ({ params, request, url }) => {
33
+ const rejection = rejectIfUnsafe(request);
34
+ if (rejection) return rejection;
35
+ const island = islands[params.name ?? ""];
36
+ if (!island) {
37
+ return new Response(`Unknown island "${params.name}"`, { status: 404 });
38
+ }
39
+ const priming = request.headers.get(PRIME_HEADER) !== null;
40
+ try {
41
+ const forms = [];
42
+ const html = await requestStore.run(
43
+ request,
44
+ () => formsStore.run(forms, async () => {
45
+ const data = await island.fetch(request, url.searchParams);
46
+ const container = await AstroContainer.create();
47
+ return container.renderToString(island.component, {
48
+ props: island.propsFromData(data, url.searchParams)
49
+ });
50
+ })
51
+ );
52
+ const body = (priming ? renderFormPayloads(forms) : "") + wrapIsland(html, island.wrapper, url);
53
+ return new Response(body, {
54
+ headers: {
55
+ "Content-Type": "text/html; charset=utf-8",
56
+ "Cache-Control": "no-store"
57
+ }
58
+ });
59
+ } catch {
60
+ return new Response("Island render failed", { status: 500 });
61
+ }
62
+ };
63
+ }
64
+ function rejectIfUnsafe(request) {
65
+ if (request.method !== "POST") {
66
+ return new Response("Method Not Allowed", { status: 405 });
67
+ }
68
+ const contentType = request.headers.get("content-type") ?? "";
69
+ if (!contentType.includes(PREVIEW_CONTENT_TYPE)) {
70
+ return new Response("Not Found", { status: 404 });
71
+ }
72
+ if (request.headers.get("sec-fetch-site") === "cross-site") {
73
+ return new Response("Forbidden", { status: 403 });
74
+ }
75
+ return null;
76
+ }
77
+ function renderFormPayloads(forms) {
78
+ return sortByPriority(forms).map((form) => renderFormPayloadDiv(form, form.priority === "primary")).join("");
79
+ }
80
+ function wrapIsland(html, wrapper, url) {
81
+ const cls = wrapper.className ? ` class="${escapeAttr(wrapper.className)}"` : "";
82
+ const marker = escapeAttr(`${url.pathname}${url.search}`);
83
+ return `<${wrapper.tag}${cls} data-tina-island="${marker}">${html}</${wrapper.tag}>`;
84
+ }
85
+ export {
86
+ experimental_createIslandRoute
87
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Runtime entry for the package's `.` subpath. Astro consumers resolve
3
+ * through the `astro` export condition straight to `src/TinaMarkdown.astro`
4
+ * — they get the real component as the default export plus the named
5
+ * helpers re-exported from the .astro frontmatter.
6
+ *
7
+ * This file is the fallback for any tool that *doesn't* understand the
8
+ * `astro` condition (TypeScript types, plain Node ESM resolution). It
9
+ * exposes the named runtime helpers and a placeholder default that
10
+ * throws with a clear redirect if someone reaches it.
11
+ */
12
+ import type { AstroComponentFactory } from 'astro/runtime/server/index.js';
13
+ import type { CustomComponentsMap, TinaRichTextContent } from './types';
14
+ export { requestWithMetadata, type QueryResult } from './data';
15
+ export { tinaField } from './tina-field';
16
+ export type { AstroComponent, CustomComponentsMap, MdxElement, TextElement, TinaRichTextContent, TinaRichTextNode, TinaRichTextRoot, } from './types';
17
+ /**
18
+ * Typed shape of `<TinaMarkdown content={...} components={...} />` for tools
19
+ * that resolve through the `types` / `default` export condition rather than
20
+ * the `astro` condition. The actual component is `src/TinaMarkdown.astro`;
21
+ * this placeholder throws if invoked because the only legitimate caller is
22
+ * Astro's component pipeline, which reaches the .astro file directly.
23
+ *
24
+ * The intersection of `AstroComponentFactory` (Astro's component-validity
25
+ * check) and a typed prop signature (TinaMarkdown's actual API) gives the
26
+ * Astro language server enough shape to both recognise this as a renderable
27
+ * component AND offer prop completions / type errors at the call site.
28
+ */
29
+ type TinaMarkdownComponent = AstroComponentFactory & {
30
+ (props: {
31
+ content: TinaRichTextContent;
32
+ components?: CustomComponentsMap;
33
+ }): unknown;
34
+ };
35
+ declare const TinaMarkdownPlaceholder: TinaMarkdownComponent;
36
+ export default TinaMarkdownPlaceholder;