@craftware/crafty-sdk 0.4.1 → 0.5.1
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/README.md +35 -1
- package/dist/client.d.ts +2 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +2 -0
- package/dist/client.js.map +1 -1
- package/dist/crafty-visual-editing.global.js +1 -1
- package/dist/crafty-visual-editing.global.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/resources/llms.d.ts +28 -0
- package/dist/resources/llms.d.ts.map +1 -0
- package/dist/resources/llms.js +54 -0
- package/dist/resources/llms.js.map +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/skills/crafty-cms/SKILL.md +31 -9
- package/skills/crafty-cms/references/mcp-configuration.md +53 -40
- package/skills/crafty-cms/references/sdk-development.md +66 -1
- package/skills/crafty-cms/references/visual-editor.md +5 -4
package/README.md
CHANGED
|
@@ -131,6 +131,40 @@ Supported common `query` params:
|
|
|
131
131
|
- `per_page`
|
|
132
132
|
- `page`
|
|
133
133
|
|
|
134
|
+
## llms.txt
|
|
135
|
+
|
|
136
|
+
Crafty generates `llms.txt` and `llms-full.txt` from your published content. Title, summary, language, and which collections without a route are opted in come from the "llms.txt" settings screen in the admin, or the `configure_llms` MCP tool; URLs are resolved from the visual editor routes. A collection without a route pattern is excluded by default — opt it in to have its entries appear under "## Optional" in the index and in `llms-full.txt`.
|
|
137
|
+
|
|
138
|
+
Sites hosted by Crafty get both files injected at the site root on their **next deploy**; a deploy already made before you started using this feature is not retroactively updated. A file the site's own build already ships (an `llms.txt` / `llms-full.txt` already in the deploy output) always wins — Crafty only adds the files when they are missing.
|
|
139
|
+
|
|
140
|
+
Serve them from your own domain:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
// Next.js — app/llms.txt/route.ts
|
|
144
|
+
export const GET = crafty.llms.handler();
|
|
145
|
+
|
|
146
|
+
// Next.js — app/llms-full.txt/route.ts
|
|
147
|
+
export const GET = crafty.llms.handler({ full: true });
|
|
148
|
+
|
|
149
|
+
// Astro — src/pages/llms.txt.ts
|
|
150
|
+
export const GET = crafty.llms.handler();
|
|
151
|
+
|
|
152
|
+
// Nuxt — server/routes/llms.txt.ts
|
|
153
|
+
export default defineEventHandler(() => crafty.llms.handler()());
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
For a static build, write the files into `dist/` yourself at build time instead of relying on deploy-time injection:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
// e.g. a postbuild script, run after `vite build` / `astro build`
|
|
160
|
+
import { writeFile } from "node:fs/promises";
|
|
161
|
+
|
|
162
|
+
await writeFile("dist/llms.txt", await crafty.llms.index());
|
|
163
|
+
await writeFile("dist/llms-full.txt", await crafty.llms.full());
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Advertise it in `<head>` with `crafty.llms.linkTags()` (HTML string) or `crafty.llms.linkTagAttrs()` (objects for `useHead` / `<Head>`).
|
|
167
|
+
|
|
134
168
|
## Request options (per call)
|
|
135
169
|
|
|
136
170
|
Every method accepts `options?` as the last argument:
|
|
@@ -304,7 +338,7 @@ Without a bundler:
|
|
|
304
338
|
<script>CraftyVisualEditing.enableVisualEditing();</script>
|
|
305
339
|
```
|
|
306
340
|
|
|
307
|
-
For production, pin an exact version (`@0.4.
|
|
341
|
+
For production, pin an exact version (`@0.4.1`) and add `integrity="sha384-…" crossorigin="anonymous"` with the hash jsDelivr shows for that file.
|
|
308
342
|
|
|
309
343
|
Sites not hosted on Crafty Hosting must allow the admin to frame them: `Content-Security-Policy: frame-ancestors 'self' https://<tenant>.crafty.do`.
|
|
310
344
|
|
package/dist/client.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { previewFromRequest } from "./preview.js";
|
|
|
3
3
|
import { CollectionsResource } from "./resources/collections.js";
|
|
4
4
|
import { EntriesResource } from "./resources/entries.js";
|
|
5
5
|
import { FormsResource } from "./resources/forms.js";
|
|
6
|
+
import { LlmsResource } from "./resources/llms.js";
|
|
6
7
|
import { MediaCollectionsResource } from "./resources/mediaCollections.js";
|
|
7
8
|
import { MediaFilesResource } from "./resources/mediaFiles.js";
|
|
8
9
|
import { PagesResource } from "./resources/pages.js";
|
|
@@ -11,6 +12,7 @@ export type CraftyClient = {
|
|
|
11
12
|
collections: CollectionsResource;
|
|
12
13
|
entries: EntriesResource;
|
|
13
14
|
forms: FormsResource;
|
|
15
|
+
llms: LlmsResource;
|
|
14
16
|
mediaCollections: MediaCollectionsResource;
|
|
15
17
|
mediaFiles: MediaFilesResource;
|
|
16
18
|
pages: PagesResource;
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,MAAM,MAAM,YAAY,GAAG;IACzB,WAAW,EAAE,mBAAmB,CAAC;IACjC,OAAO,EAAE,eAAe,CAAC;IACzB,KAAK,EAAE,aAAa,CAAC;IACrB,gBAAgB,EAAE,wBAAwB,CAAC;IAC3C,UAAU,EAAE,kBAAkB,CAAC;IAC/B,KAAK,EAA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,kBAAkB,GAAG,YAAY,CAe3E"}
|
package/dist/client.js
CHANGED
|
@@ -4,6 +4,7 @@ import { previewFromRequest } from "./preview.js";
|
|
|
4
4
|
import { CollectionsResource } from "./resources/collections.js";
|
|
5
5
|
import { EntriesResource } from "./resources/entries.js";
|
|
6
6
|
import { FormsResource } from "./resources/forms.js";
|
|
7
|
+
import { LlmsResource } from "./resources/llms.js";
|
|
7
8
|
import { MediaCollectionsResource } from "./resources/mediaCollections.js";
|
|
8
9
|
import { MediaFilesResource } from "./resources/mediaFiles.js";
|
|
9
10
|
import { PagesResource } from "./resources/pages.js";
|
|
@@ -13,6 +14,7 @@ export function createCraftyClient(config) {
|
|
|
13
14
|
collections: new CollectionsResource(http),
|
|
14
15
|
entries: new EntriesResource(http),
|
|
15
16
|
forms: new FormsResource(http),
|
|
17
|
+
llms: new LlmsResource(http),
|
|
16
18
|
mediaCollections: new MediaCollectionsResource(http),
|
|
17
19
|
mediaFiles: new MediaFilesResource(http),
|
|
18
20
|
pages: new PagesResource(http),
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAgBrD,MAAM,UAAU,kBAAkB,CAAC,MAA0B;IAC3D,MAAM,IAAI,GAAG,UAAU,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;IAEjD,OAAO;QACL,WAAW,EAAE,IAAI,mBAAmB,CAAC,IAAI,CAAC;QAC1C,OAAO,EAAE,IAAI,eAAe,CAAC,IAAI,CAAC;QAClC,KAAK,EAAE,IAAI,aAAa,CAAC,IAAI,CAAC;QAC9B,IAAI,EAAE,IAAI,YAAY,CAAC,IAAI,CAAC;QAC5B,gBAAgB,EAAE,IAAI,wBAAwB,CAAC,IAAI,CAAC;QACpD,UAAU,EAAE,IAAI,kBAAkB,CAAC,IAAI,CAAC;QACxC,KAAK,EAAE,IAAI,aAAa,CAAC,IAAI,CAAC;QAC9B,KAAK;QACL,SAAS;QACT,kBAAkB;KACnB,CAAC;AACJ,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var CraftyVisualEditing=(()=>{var I=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var We=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},Ke=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Fe(t))!He.call(e,i)&&i!==n&&I(e,i,{get:()=>t[i],enumerable:!(r=Ie(t,i))||r.enumerable});return e};var $e=e=>Ke(I({},"__esModule",{value:!0}),e);var dt={};We(dt,{PROTOCOL_VERSION:()=>k,attrs:()=>F,attrsHtml:()=>le,enableVisualEditing:()=>Le});function De(e){if(e==null||typeof e!="object")return null;let t=e,n=typeof t.id=="string"?Number(t.id.trim()):t.id;return typeof n!="number"||!Number.isInteger(n)||n<=0?null:t.kind==="block"||t.kind==="entry"?{type:t.kind,id:n}:{type:typeof t.order=="number"&&typeof t.data=="object"&&t.data!==null&&"type"in t?"block":"entry",id:n}}function F(e,t,n={}){let r=De(e),i=typeof t=="string"?t.trim():"";if(r===null||i==="")return{};let l=r.type==="block"?{"data-crafty-block":String(r.id),"data-crafty-field":i}:{"data-crafty-entry":String(r.id),"data-crafty-field":i},a=typeof n.label=="string"?n.label.trim():"";a!==""&&(l["data-crafty-label"]=a);let s=typeof n.hrefField=="string"?n.hrefField.trim():"";if(s!==""){l["data-crafty-href-field"]=s;let d=typeof n.hrefLabel=="string"?n.hrefLabel.trim():"";d!==""&&(l["data-crafty-href-label"]=d)}return l}function le(e,t,n={}){return Object.entries(F(e,t,n)).map(([r,i])=>`${r}="${Ue(String(i))}"`).join(" ")}function Ue(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}var $="crafty_preview";var T="crafty:preview-invalid",D="crafty:preview-content",U="crafty:preview-active",W="crafty:preview-token",ae="crafty:preview-url-token",Ge="crafty:preview-invalid-token",Ye="__CRAFTY_PREVIEW_CONTENT__",ze="__CRAFTY_PREVIEW_STATUS__";function A(){return typeof window=="undefined"?null:window}function H(e){var t,n;try{return(n=(t=A())==null?void 0:t.sessionStorage.getItem(e))!=null?n:null}catch{return null}}function K(e,t){var n;try{(n=A())==null||n.sessionStorage.setItem(e,t)}catch{}}function G(e){return typeof e=="string"&&e.trim()!==""?e.trim():null}function Be(e){try{return G(new URL(e,"http://localhost").searchParams.get($))}catch{return null}}function se(){var r;let e=A();if(e===null)return null;let t=Be(e.location.href),n;return t!==null&&t!==H(ae)?(K(ae,t),K(W,t),n=t):n=(r=G(H(W)))!=null?r:t,n!==null&&n===H(Ge)?null:n}function de(e){let t=G(e);t!==null&&K(W,t)}function ce(){let e=A(),t=e==null?void 0:e[Ye];return t?{page:t.page,entries:[...t.entries]}:{page:null,entries:[]}}function ue(){let e=A(),t=e==null?void 0:e[ze];return t==="active"||t==="invalid"?t:null}var fe="0.
|
|
1
|
+
"use strict";var CraftyVisualEditing=(()=>{var I=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var We=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},Ke=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Fe(t))!He.call(e,i)&&i!==n&&I(e,i,{get:()=>t[i],enumerable:!(r=Ie(t,i))||r.enumerable});return e};var $e=e=>Ke(I({},"__esModule",{value:!0}),e);var dt={};We(dt,{PROTOCOL_VERSION:()=>k,attrs:()=>F,attrsHtml:()=>le,enableVisualEditing:()=>Le});function De(e){if(e==null||typeof e!="object")return null;let t=e,n=typeof t.id=="string"?Number(t.id.trim()):t.id;return typeof n!="number"||!Number.isInteger(n)||n<=0?null:t.kind==="block"||t.kind==="entry"?{type:t.kind,id:n}:{type:typeof t.order=="number"&&typeof t.data=="object"&&t.data!==null&&"type"in t?"block":"entry",id:n}}function F(e,t,n={}){let r=De(e),i=typeof t=="string"?t.trim():"";if(r===null||i==="")return{};let l=r.type==="block"?{"data-crafty-block":String(r.id),"data-crafty-field":i}:{"data-crafty-entry":String(r.id),"data-crafty-field":i},a=typeof n.label=="string"?n.label.trim():"";a!==""&&(l["data-crafty-label"]=a);let s=typeof n.hrefField=="string"?n.hrefField.trim():"";if(s!==""){l["data-crafty-href-field"]=s;let d=typeof n.hrefLabel=="string"?n.hrefLabel.trim():"";d!==""&&(l["data-crafty-href-label"]=d)}return l}function le(e,t,n={}){return Object.entries(F(e,t,n)).map(([r,i])=>`${r}="${Ue(String(i))}"`).join(" ")}function Ue(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}var $="crafty_preview";var T="crafty:preview-invalid",D="crafty:preview-content",U="crafty:preview-active",W="crafty:preview-token",ae="crafty:preview-url-token",Ge="crafty:preview-invalid-token",Ye="__CRAFTY_PREVIEW_CONTENT__",ze="__CRAFTY_PREVIEW_STATUS__";function A(){return typeof window=="undefined"?null:window}function H(e){var t,n;try{return(n=(t=A())==null?void 0:t.sessionStorage.getItem(e))!=null?n:null}catch{return null}}function K(e,t){var n;try{(n=A())==null||n.sessionStorage.setItem(e,t)}catch{}}function G(e){return typeof e=="string"&&e.trim()!==""?e.trim():null}function Be(e){try{return G(new URL(e,"http://localhost").searchParams.get($))}catch{return null}}function se(){var r;let e=A();if(e===null)return null;let t=Be(e.location.href),n;return t!==null&&t!==H(ae)?(K(ae,t),K(W,t),n=t):n=(r=G(H(W)))!=null?r:t,n!==null&&n===H(Ge)?null:n}function de(e){let t=G(e);t!==null&&K(W,t)}function ce(){let e=A(),t=e==null?void 0:e[Ye];return t?{page:t.page,entries:[...t.entries]}:{page:null,entries:[]}}function ue(){let e=A(),t=e==null?void 0:e[ze];return t==="active"||t==="invalid"?t:null}var fe="0.5.1";var k=1;var Xe=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+|\[\d+\])*$/,je=/^[\x21-\x7E]+$/;function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qe(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}function pe(e){if(typeof e!="string")return null;let t=e.trim();return t===""||t.length>255||!Xe.test(t)?null:t}function ye(e){return typeof e=="string"?e.trim().slice(0,120).trim():""}function x(e){if(!S(e))return null;let{type:t,id:n}=e,r=pe(e.field);return t!=="block"&&t!=="entry"||!qe(n)||r===null?null:{type:t,id:n,field:r}}function ge(e){let t=x(e);if(t===null||!S(e))return null;let n={...t},r=ye(e.label),i=pe(e.hrefField);if(r!==""&&(n.label=r),i!==null){n.hrefField=i;let l=ye(e.hrefLabel);l!==""&&(n.hrefLabel=l)}return n}function Qe(e){if(!S(e)||e.v!==1||typeof e.type!="string")return null;let t=e.payload===void 0?{}:e.payload;return S(t)?{type:e.type,payload:t}:null}function Ee(e){let t=Qe(e);if(t===null)return null;let{payload:n}=t;switch(t.type){case"crafty:token":{let r=typeof n.token=="string"?n.token.trim():"";return r!==""&&r.length<=4096&&je.test(r)?{v:1,type:"crafty:token",payload:{token:r}}:null}case"crafty:refresh":return{v:1,type:"crafty:refresh",payload:{}};case"crafty:highlight":{let r=x(n);return r?{v:1,type:"crafty:highlight",payload:r}:null}case"crafty:preview-field":{let r=x(n),i=n.value;return r&&typeof i=="string"&&i.length<=1e5?{v:1,type:"crafty:preview-field",payload:{...r,value:i}}:null}case"crafty:preview-reset":{let r=x(n);return r?{v:1,type:"crafty:preview-reset",payload:r}:null}default:return null}}var R="[data-crafty-field]";function L(e){var i;let t=e.getAttribute("data-crafty-block"),n=e.getAttribute("data-crafty-entry"),r=t!=null?t:n;return r===null?null:ge({type:t!==null?"block":"entry",id:r.trim()===""?Number.NaN:Number(r),field:(i=e.getAttribute("data-crafty-field"))!=null?i:"",label:e.getAttribute("data-crafty-label"),hrefField:e.getAttribute("data-crafty-href-field"),hrefLabel:e.getAttribute("data-crafty-href-label")})}function E(e){return`${e.type}:${e.id}:${e.field}`}function _(e){let t=[];return e.querySelectorAll(R).forEach(n=>{let r=L(n);r!==null&&t.push({element:n,field:r})}),t}function Y(e){let t=new Set,n=[];for(let{field:r}of e){let i=E(r);t.has(i)||(t.add(i),n.push(r))}return n}function ve(e){let t=new Map,n=new Map,r=a=>Array.from(e.querySelectorAll(R)).filter(s=>{let d=L(s);return d!==null&&E(d)===a}),i=(a,s)=>{var d;n.has(a)||n.set(a,(d=a.textContent)!=null?d:""),a.textContent!==s&&(a.textContent=s)},l=a=>{for(let[s,d]of n){let y=L(s);(a===null||y!==null&&E(y)===a)&&(s.textContent!==d&&(s.textContent=d),n.delete(s))}};return{set(a,s){let d=E(a);t.set(d,s),r(d).forEach(y=>i(y,s))},reset(a){let s=E(a);t.delete(s),l(s)},reapply(){for(let a of[...n.keys()])a.isConnected||n.delete(a);for(let[a,s]of t)r(a).forEach(d=>i(d,s))},resetAll(){t.clear(),l(null)},get size(){return t.size}}}var he=[/^https:\/\/([a-z0-9-]+\.)*crafty\.do$/];function me(e){try{return new URL(e).origin}catch{return null}}function ke(e,t){return e===""||e==="null"?!1:t.some(n=>typeof n=="string"?me(n)===e:(n.lastIndex=0,n.test(e)))}function be(e){let t=e.location.ancestorOrigins,n=t&&t.length>0?t[0]:void 0;if(typeof n=="string"&&n!=="")return n;let r=e.document.referrer;return r?me(r):null}var Ze="crafty-visual-editing-style",z="#4f46e5",B="crafty-ve-flash",Je=["[data-crafty-field]{cursor:pointer}",`.crafty-ve-box{position:fixed;top:0;left:0;pointer-events:none;z-index:2147483647;box-sizing:border-box;border:2px solid ${z};border-radius:4px;background:rgba(79,70,229,.06)}`,".crafty-ve-box[hidden]{display:none}",`.crafty-ve-label{position:absolute;left:-2px;bottom:100%;margin-bottom:4px;padding:2px 8px;max-width:320px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border-radius:4px;background:${z};color:#fff;font:500 12px/1.5 system-ui,-apple-system,sans-serif}`,`.${B}{outline:2px dashed ${z} !important;outline-offset:2px !important}`].join(`
|
|
2
2
|
`);function Ce(e){let t=e.defaultView,n=e.createElement("style");n.id=Ze,n.textContent=Je;let r=e.createElement("div");r.setAttribute("data-crafty-overlay",""),r.className="crafty-ve-box",r.hidden=!0;let i=e.createElement("span");i.className="crafty-ve-label",r.appendChild(i);let l=null,a=[],s,d=t==null?void 0:t.ResizeObserver,y=()=>{if(l===null)return;let c=l.getBoundingClientRect();r.style.top=`${c.top}px`,r.style.left=`${c.left}px`,r.style.width=`${c.width}px`,r.style.height=`${c.height}px`},f=typeof d=="function"?new d(()=>y()):null,v=c=>{l!==c&&(l!==null&&(f==null||f.unobserve(l)),l=c,l!==null&&(f==null||f.observe(l)))},g=()=>{a.forEach(c=>c.classList.remove(B)),a=[],s!==void 0&&(t==null||t.clearTimeout(s),s=void 0)},h=()=>{var c,m;n.isConnected||((c=e.head)!=null?c:e.documentElement).appendChild(n),r.isConnected||((m=e.body)!=null?m:e.documentElement).appendChild(r)};return h(),t==null||t.addEventListener("scroll",y,{capture:!0,passive:!0}),t==null||t.addEventListener("resize",y,{passive:!0}),{show(c,m){h(),v(c),i.textContent!==m&&(i.textContent=m),r.hidden=!1,y()},hide(){v(null),r.hidden=!0},reposition(){y()},flash(c,m){g(),a=[...c],a.forEach(w=>w.classList.add(B)),s=t==null?void 0:t.setTimeout(g,m)},ensureAttached:h,contains(c){return c!==null&&(r===c||r.contains(c)||n===c||n.contains(c))},destroy(){g(),t==null||t.removeEventListener("scroll",y,{capture:!0}),t==null||t.removeEventListener("resize",y),f==null||f.disconnect(),r.remove(),n.remove(),l=null}}}var j="crafty:scroll-y",et=50,tt=1500,nt=["data-crafty-field","data-crafty-block","data-crafty-entry","data-crafty-label","data-crafty-href-field","data-crafty-href-label"],N={active:!1,disable:()=>{}},b=null;function Le(e={}){var i;if(typeof window=="undefined"||typeof document=="undefined")return N;if(b!==null)return b;let t=window;if(t.parent===null||t.parent===t||se()===null)return N;let n=be(t);if(n===null||!ke(n,(i=e.adminOrigins)!=null?i:he))return N;let r=ue();return r==="invalid"?(we(t,n),N):(b=r==="active"?Oe(t,n,e):rt(t,n,e),b)}function we(e,t){let n={v:1,type:"crafty:preview-invalid",payload:{}};e.parent.postMessage(n,t)}function rt(e,t,n){var f;let r=null,i=!1,l=()=>{i=!0,e.removeEventListener(U,s),e.removeEventListener(T,d)},a=()=>{b===y&&(b=null)},s=()=>{i||(l(),r=Oe(e,t,n,a))},d=()=>{i||(l(),a(),we(e,t))},y={get active(){var v;return(v=r==null?void 0:r.active)!=null?v:!1},disable(){l(),r==null||r.disable(),a()}};return e.addEventListener(U,s),e.addEventListener(T,d),(f=n.client)==null||f.pages.list({per_page:1}).catch(()=>{}),y}function Oe(e,t,n,r){let i=e.document,l=Ce(i),a=ve(i),s=at(e),d=[],y=null,f,v=!1,g=!0,h=o=>{e.parent.postMessage(o,t)},c=()=>{var p,C,O;let o=Y(d),u=ce();y=Re(o),h({v:1,type:"crafty:ready",payload:{sdkVersion:fe,path:_e(e),fields:o,page:(C=(p=u.page)!=null?p:n.page)!=null?C:null,entries:it(u.entries,(O=n.entries)!=null?O:[])}})},m=()=>{f=void 0,g&&(l.ensureAttached(),d=_(i),a.reapply(),(v||Re(Y(d))!==y)&&(v=!1,c()))},w=()=>{g&&f===void 0&&(f=e.setTimeout(m,et))},q=new MutationObserver(o=>{o.some(u=>!l.contains(u.target))&&w()}),V=o=>{var u;return(u=o.label)!=null?u:o.field},Q=o=>{if(o.pointerType==="touch")return;let u=X(o.target);u!==null?l.show(u.element,V(u.field)):l.hide()},P=o=>{o.preventDefault(),o.stopPropagation()},Z=o=>{let u=X(o.target);if(u!==null){P(o),l.show(u.element,V(u.field)),h({v:1,type:"crafty:select",payload:u.field});return}let p=ot(o,e);p.kind!=="allow"&&(P(o),p.kind==="navigate"&&h({v:1,type:"crafty:navigate",payload:{path:p.path}}))},J=o=>{(X(o.target)!==null||xe(o.target)!==null)&&P(o)},ee=o=>{P(o)},te=o=>{o.key!=="Escape"||o.repeat||o.isComposing||o.defaultPrevented||h({v:1,type:"crafty:key",payload:{key:"Escape"}})},Se=o=>{var O;let u=E(o),p=_(i).find(Me=>E(Me.field)===u);if(p===void 0)return;let C=p.element;(O=C.scrollIntoView)==null||O.call(C,{block:"center",behavior:"smooth"}),l.show(p.element,V(p.field))},Ne=async()=>{if(n.onRefresh){try{await n.onRefresh()}finally{w()}return}try{e.sessionStorage.setItem(j,String(e.scrollY))}catch{}e.location.reload()},Ve=o=>{switch(o.type){case"crafty:token":de(o.payload.token);return;case"crafty:refresh":Ne().catch(u=>console.error("[crafty] onRefresh failed",u));return;case"crafty:highlight":Se(o.payload);return;case"crafty:preview-field":a.set(o.payload,o.payload.value),l.reposition();return;case"crafty:preview-reset":a.reset(o.payload),l.reposition();return}},ne=o=>{if(o.source!==e.parent||o.origin!==t)return;let u=Ee(o.data);u!==null&&Ve(u)},re=()=>{h({v:1,type:"crafty:preview-invalid",payload:{}})},ie=()=>{v=!0,w()},M=()=>{var o;g&&(d=_(i),c(),lt(e)&&l.flash(d.map(u=>u.element),(o=n.touchHighlightMs)!=null?o:tt),st(e,s))};e.addEventListener("message",ne),e.addEventListener("click",Z,!0),e.addEventListener("auxclick",J,!0),e.addEventListener("submit",ee,!0),e.addEventListener("keydown",te),i.addEventListener("pointerover",Q,!0),e.addEventListener(T,re),e.addEventListener(D,ie),q.observe(i.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:nt}),i.readyState==="loading"?i.addEventListener("DOMContentLoaded",M,{once:!0}):M();let oe={get active(){return g},disable(){g&&(g=!1,e.removeEventListener("message",ne),e.removeEventListener("click",Z,!0),e.removeEventListener("auxclick",J,!0),e.removeEventListener("submit",ee,!0),e.removeEventListener("keydown",te),i.removeEventListener("pointerover",Q,!0),i.removeEventListener("DOMContentLoaded",M),e.removeEventListener(T,re),e.removeEventListener(D,ie),q.disconnect(),f!==void 0&&(e.clearTimeout(f),f=void 0),a.resetAll(),l.destroy(),b===oe&&(b=null),r==null||r())}};return oe}function Te(e){return e!==null&&typeof e.closest=="function"?e:null}function Re(e){return e.map(t=>{var n,r,i;return`${E(t)}|${(n=t.label)!=null?n:""}|${(r=t.hrefField)!=null?r:""}|${(i=t.hrefLabel)!=null?i:""}`}).join(`
|
|
3
3
|
`)}function it(e,t){let n=new Set;return[...e,...t].filter(r=>{let i=`${r.collection}:${r.id}`;return n.has(i)?!1:(n.add(i),!0)})}function Ae(e){return e.searchParams.delete($),`${e.pathname}${e.search}`}function _e(e){return Ae(new URL(e.location.href))}var Pe="a[href], area[href]";function X(e){var r,i,l;let t=Te(e);if(t===null)return null;for(let a=t.closest(R);a!==null;a=(i=(r=a.parentElement)==null?void 0:r.closest(R))!=null?i:null){let s=L(a);if(s!==null)return{element:a,field:s}}let n=t.closest(Pe);return n!==null&&(l=_(n)[0])!=null?l:null}function xe(e){var t,n;return(n=(t=Te(e))==null?void 0:t.closest(Pe))!=null?n:null}function ot(e,t){var s;let n=xe(e.target);if(n===null)return{kind:"allow"};if(e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||n.hasAttribute("download"))return{kind:"block"};let r=n.getAttribute("target");if(r!==null&&r!==""&&r!=="_self")return{kind:"block"};let i=(s=n.getAttribute("href"))!=null?s:"",l;try{l=new URL(i,t.location.href)}catch{return{kind:"block"}}if(l.origin!==t.location.origin||l.protocol!=="http:"&&l.protocol!=="https:")return{kind:"block"};let a=Ae(l);return(l.hash!==""||i.startsWith("#"))&&a===_e(t)?{kind:"allow"}:{kind:"navigate",path:a}}function lt(e){return typeof e.matchMedia=="function"&&e.matchMedia("(hover: none)").matches}function at(e){try{let t=e.sessionStorage.getItem(j);e.sessionStorage.removeItem(j);let n=t===null?Number.NaN:Number(t);return Number.isFinite(n)?n:null}catch{return null}}function st(e,t){if(t===null)return;let n=()=>e.scrollTo(0,t);e.document.readyState==="complete"?n():e.addEventListener("load",n,{once:!0})}return $e(dt);})();
|
|
4
4
|
//# sourceMappingURL=crafty-visual-editing.global.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/cdn.ts", "../src/attrs.ts", "../src/preview.ts", "../src/version.ts", "../src/visual-editing/protocol.ts", "../src/visual-editing/markers.ts", "../src/visual-editing/live-preview.ts", "../src/visual-editing/origin.ts", "../src/visual-editing/overlay.ts", "../src/visual-editing/bridge.ts"],
|
|
4
|
-
"sourcesContent": ["/** Entry for the `<script>` build: exposed as `window.CraftyVisualEditing`. */\nexport { attrs, attrsHtml } from \"./attrs.js\";\nexport { enableVisualEditing } from \"./visual-editing/bridge.js\";\nexport { PROTOCOL_VERSION } from \"./visual-editing/protocol.js\";\n", "import type { CraftyBlock, CraftyEntry } from \"./types/public.js\";\n\nexport type CraftyEditTargetType = \"block\" | \"entry\";\n\n/**\n * A block or entry as returned by the API, or an explicit reference for\n * ambiguous shapes (e.g. an entry with fields named `order`, `data` and `type`).\n */\nexport type CraftyEditTarget =\n | CraftyBlock\n | CraftyEntry\n | { kind: CraftyEditTargetType; id: number | string };\n\nexport type CraftyAttrsOptions = {\n /** Human label shown by the visual editor, e.g. \"T\u00EDtulo de la secci\u00F3n\". */\n label?: string;\n /**\n * Field holding the link destination of this element (a button or link whose\n * text is `field`), e.g. `hero.cta.href`. The editor then edits both together.\n */\n hrefField?: string;\n /** Human label for `hrefField`. Defaults to \"Enlace\" in the editor. */\n hrefLabel?: string;\n};\n\nexport type CraftyEditAttributes = {\n \"data-crafty-block\"?: string;\n \"data-crafty-entry\"?: string;\n \"data-crafty-field\"?: string;\n \"data-crafty-label\"?: string;\n \"data-crafty-href-field\"?: string;\n \"data-crafty-href-label\"?: string;\n};\n\nexport function resolveEditTarget(\n target: CraftyEditTarget | null | undefined\n): { type: CraftyEditTargetType; id: number } | null {\n if (target === null || target === undefined || typeof target !== \"object\") {\n return null;\n }\n\n const record = target as Record<string, unknown>;\n const id = typeof record.id === \"string\" ? Number(record.id.trim()) : record.id;\n\n if (typeof id !== \"number\" || !Number.isInteger(id) || id <= 0) {\n return null;\n }\n\n if (record.kind === \"block\" || record.kind === \"entry\") {\n return { type: record.kind, id };\n }\n\n const looksLikeBlock =\n typeof record.order === \"number\" &&\n typeof record.data === \"object\" &&\n record.data !== null &&\n \"type\" in record;\n\n return { type: looksLikeBlock ? \"block\" : \"entry\", id };\n}\n\n/**\n * DOM attributes that let the visual editor map an element to a field.\n * Always emitted (static sites render them at build time without a token).\n * `field` is a top-level field key or a JSON path such as `sections[3].title`.\n */\nexport function attrs(\n target: CraftyEditTarget | null | undefined,\n field: string,\n options: CraftyAttrsOptions = {}\n): CraftyEditAttributes {\n const resolved = resolveEditTarget(target);\n const normalizedField = typeof field === \"string\" ? field.trim() : \"\";\n\n if (resolved === null || normalizedField === \"\") {\n return {};\n }\n\n const attributes: CraftyEditAttributes =\n resolved.type === \"block\"\n ? { \"data-crafty-block\": String(resolved.id), \"data-crafty-field\": normalizedField }\n : { \"data-crafty-entry\": String(resolved.id), \"data-crafty-field\": normalizedField };\n\n const label = typeof options.label === \"string\" ? options.label.trim() : \"\";\n\n if (label !== \"\") {\n attributes[\"data-crafty-label\"] = label;\n }\n\n const hrefField = typeof options.hrefField === \"string\" ? options.hrefField.trim() : \"\";\n\n if (hrefField !== \"\") {\n attributes[\"data-crafty-href-field\"] = hrefField;\n\n const hrefLabel = typeof options.hrefLabel === \"string\" ? options.hrefLabel.trim() : \"\";\n\n if (hrefLabel !== \"\") {\n attributes[\"data-crafty-href-label\"] = hrefLabel;\n }\n }\n\n return attributes;\n}\n\n/** Same as `attrs()`, rendered for HTML string templates. */\nexport function attrsHtml(\n target: CraftyEditTarget | null | undefined,\n field: string,\n options: CraftyAttrsOptions = {}\n): string {\n return Object.entries(attrs(target, field, options))\n .map(([name, value]) => `${name}=\"${escapeAttribute(String(value))}\"`)\n .join(\" \");\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n", "export const PREVIEW_QUERY_PARAM = \"crafty_preview\";\nexport const PREVIEW_HEADER = \"X-Crafty-Preview\";\nexport const PREVIEW_STATUS_HEADER = \"X-Crafty-Preview-Status\";\nexport const PREVIEW_INVALID_EVENT = \"crafty:preview-invalid\";\nexport const PREVIEW_CONTENT_EVENT = \"crafty:preview-content\";\nexport const PREVIEW_ACTIVE_EVENT = \"crafty:preview-active\";\n\nconst TOKEN_STORAGE_KEY = \"crafty:preview-token\";\nconst URL_TOKEN_STORAGE_KEY = \"crafty:preview-url-token\";\nconst INVALID_TOKEN_STORAGE_KEY = \"crafty:preview-invalid-token\";\nconst CONTENT_GLOBAL_KEY = \"__CRAFTY_PREVIEW_CONTENT__\";\nconst STATUS_GLOBAL_KEY = \"__CRAFTY_PREVIEW_STATUS__\";\n\nexport type PreviewPage = { id: number; slug: string };\nexport type PreviewEntry = { id: number; collection: string };\nexport type PreviewContent = { page: PreviewPage | null; entries: PreviewEntry[] };\n/** Last `X-Crafty-Preview-Status` the API answered in this window, or null before any preview request. */\nexport type PreviewStatus = \"active\" | \"invalid\";\n\n/** A URL, a Web `Request`, a Node `IncomingMessage` or an Express-style request. */\nexport type PreviewRequestLike =\n | string\n | URL\n | { url?: string | undefined; query?: Record<string, unknown> | undefined };\n\ntype ContentHost = Record<string, PreviewContent | undefined>;\n\nfunction browserWindow(): Window | null {\n return typeof window === \"undefined\" ? null : window;\n}\n\nfunction storageGet(key: string): string | null {\n try {\n return browserWindow()?.sessionStorage.getItem(key) ?? null;\n } catch {\n return null;\n }\n}\n\nfunction storageSet(key: string, value: string): void {\n try {\n browserWindow()?.sessionStorage.setItem(key, value);\n } catch {\n // Storage can be blocked (private mode, sandboxed frames); the URL token still works.\n }\n}\n\nfunction storageRemove(key: string): void {\n try {\n browserWindow()?.sessionStorage.removeItem(key);\n } catch {\n // Ignore blocked storage.\n }\n}\n\nfunction normalizeToken(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : null;\n}\n\nfunction tokenFromUrl(url: string): string | null {\n try {\n return normalizeToken(new URL(url, \"http://localhost\").searchParams.get(PREVIEW_QUERY_PARAM));\n } catch {\n return null;\n }\n}\n\n/**\n * Preview token for browser requests. A token the URL brings for the first time\n * wins; afterwards the stored token wins, so a renewal received over\n * `postMessage` is not overwritten by the stale token still in the URL.\n */\nexport function readPreviewToken(): string | null {\n const win = browserWindow();\n\n if (win === null) {\n return null;\n }\n\n const urlToken = tokenFromUrl(win.location.href);\n let token: string | null;\n\n if (urlToken !== null && urlToken !== storageGet(URL_TOKEN_STORAGE_KEY)) {\n storageSet(URL_TOKEN_STORAGE_KEY, urlToken);\n storageSet(TOKEN_STORAGE_KEY, urlToken);\n token = urlToken;\n } else {\n token = normalizeToken(storageGet(TOKEN_STORAGE_KEY)) ?? urlToken;\n }\n\n return token !== null && token === storageGet(INVALID_TOKEN_STORAGE_KEY) ? null : token;\n}\n\n/**\n * Forgets a browser token the API reported invalid, so later requests stop\n * sending it (the stale copy in the URL included) until a new token arrives\n * over `postMessage` or a new URL. Explicit server-side tokens are untouched.\n */\nexport function discardPreviewToken(token: string): void {\n const win = browserWindow();\n const normalized = normalizeToken(token);\n\n if (win === null || normalized === null) {\n return;\n }\n\n const isStored = normalizeToken(storageGet(TOKEN_STORAGE_KEY)) === normalized;\n\n if (!isStored && tokenFromUrl(win.location.href) !== normalized) {\n return;\n }\n\n if (isStored) {\n storageRemove(TOKEN_STORAGE_KEY);\n }\n\n storageSet(INVALID_TOKEN_STORAGE_KEY, normalized);\n}\n\nexport function storePreviewToken(token: string): void {\n const normalized = normalizeToken(token);\n\n if (normalized !== null) {\n storageSet(TOKEN_STORAGE_KEY, normalized);\n }\n}\n\nexport function clearPreviewToken(): void {\n storageRemove(TOKEN_STORAGE_KEY);\n storageRemove(URL_TOKEN_STORAGE_KEY);\n storageRemove(INVALID_TOKEN_STORAGE_KEY);\n setPreviewStatus(null);\n}\n\n/** Server-side helper: the preview token of an incoming request, or null. */\nexport function previewFromRequest(request: PreviewRequestLike | null | undefined): string | null {\n if (request === null || request === undefined) {\n return null;\n }\n\n if (typeof request === \"string\" || request instanceof URL) {\n return tokenFromUrl(String(request));\n }\n\n const queryValue = request.query?.[PREVIEW_QUERY_PARAM];\n const fromQuery = normalizeToken(Array.isArray(queryValue) ? queryValue[0] : queryValue);\n\n if (fromQuery !== null) {\n return fromQuery;\n }\n\n return typeof request.url === \"string\" ? tokenFromUrl(request.url) : null;\n}\n\nexport function getPreviewContent(): PreviewContent {\n const win = browserWindow() as (Window & ContentHost) | null;\n const content = win?.[CONTENT_GLOBAL_KEY];\n\n return content ? { page: content.page, entries: [...content.entries] } : { page: null, entries: [] };\n}\n\nexport function recordPreviewContent(\n item: ({ type: \"page\" } & PreviewPage) | ({ type: \"entry\" } & PreviewEntry)\n): void {\n const win = browserWindow() as (Window & ContentHost) | null;\n\n if (win === null) {\n return;\n }\n\n const content = win[CONTENT_GLOBAL_KEY] ?? { page: null, entries: [] };\n win[CONTENT_GLOBAL_KEY] = content;\n\n if (item.type === \"page\") {\n content.page = { id: item.id, slug: item.slug };\n } else if (!content.entries.some((entry) => entry.id === item.id && entry.collection === item.collection)) {\n content.entries.push({ id: item.id, collection: item.collection });\n }\n\n dispatch(PREVIEW_CONTENT_EVENT);\n}\n\nexport function resetPreviewContent(): void {\n const win = browserWindow() as (Window & ContentHost) | null;\n\n if (win !== null) {\n win[CONTENT_GLOBAL_KEY] = undefined;\n }\n}\n\n/**\n * Kept on `window` (like the shown content) so a separately bundled bridge, such\n * as the `<script>` build, sees what the site's own SDK copy recorded.\n */\nexport function getPreviewStatus(): PreviewStatus | null {\n const win = browserWindow() as (Window & Record<string, unknown>) | null;\n const status = win?.[STATUS_GLOBAL_KEY];\n\n return status === \"active\" || status === \"invalid\" ? status : null;\n}\n\nfunction setPreviewStatus(status: PreviewStatus | null): void {\n const win = browserWindow() as (Window & Record<string, unknown>) | null;\n\n if (win !== null) {\n win[STATUS_GLOBAL_KEY] = status ?? undefined;\n }\n}\n\nexport function notifyPreviewActive(): void {\n setPreviewStatus(\"active\");\n dispatch(PREVIEW_ACTIVE_EVENT);\n}\n\nexport function notifyPreviewInvalid(): void {\n setPreviewStatus(\"invalid\");\n dispatch(PREVIEW_INVALID_EVENT);\n}\n\nfunction dispatch(name: string): void {\n const win = browserWindow();\n\n if (win !== null && typeof win.dispatchEvent === \"function\") {\n win.dispatchEvent(new Event(name));\n }\n}\n", "// Generated by scripts/write-version.mjs from package.json. Do not edit.\nexport const SDK_VERSION = \"0.4.1\";\n", "export const PROTOCOL_VERSION = 1;\n\nexport type CraftyTargetType = \"block\" | \"entry\";\nexport type CraftyFieldRef = { type: CraftyTargetType; id: number; field: string };\n/** `hrefField` is the field with the link destination of the same element (same target). */\nexport type CraftyMarkedField = CraftyFieldRef & { label?: string; hrefField?: string; hrefLabel?: string };\nexport type CraftyShownPage = { id: number; slug: string };\nexport type CraftyShownEntry = { id: number; collection: string };\n\nexport type ReadyPayload = {\n sdkVersion: string;\n path: string;\n fields: CraftyMarkedField[];\n page: CraftyShownPage | null;\n entries: CraftyShownEntry[];\n};\n\ntype Version = typeof PROTOCOL_VERSION;\n\n/**\n * Keys forwarded to the admin (`crafty:key`, SDK >= 0.4.1): the admin never\n * sees keydowns while focus is inside the iframe, so Escape could not close\n * its sheets and dialogs. Older admins ignore the message.\n */\nexport type ForwardedKey = \"Escape\";\ntype EmptyPayload = Record<string, never>;\n\n/** iframe -> admin. `crafty:ready` is a snapshot that may be re-sent; the last one wins. */\nexport type OutboundMessage =\n | { v: Version; type: \"crafty:ready\"; payload: ReadyPayload }\n | { v: Version; type: \"crafty:select\"; payload: CraftyMarkedField }\n | { v: Version; type: \"crafty:navigate\"; payload: { path: string } }\n | { v: Version; type: \"crafty:preview-invalid\"; payload: EmptyPayload }\n | { v: Version; type: \"crafty:key\"; payload: { key: ForwardedKey } };\n\n/** admin -> iframe. */\nexport type InboundMessage =\n | { v: Version; type: \"crafty:token\"; payload: { token: string } }\n | { v: Version; type: \"crafty:refresh\"; payload: EmptyPayload }\n | { v: Version; type: \"crafty:highlight\"; payload: CraftyFieldRef }\n | { v: Version; type: \"crafty:preview-field\"; payload: CraftyFieldRef & { value: string } }\n | { v: Version; type: \"crafty:preview-reset\"; payload: CraftyFieldRef };\n\n/** Same limits as the Crafty admin and backend (content_drafts.field / label). */\nconst MAX_FIELD_LENGTH = 255;\nconst MAX_LABEL_LENGTH = 120;\nconst MAX_TOKEN_LENGTH = 4096;\nconst MAX_VALUE_LENGTH = 100_000;\nconst MAX_PATH_LENGTH = 2048;\nconst FIELD_PATTERN = /^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+|\\[\\d+\\])*$/;\nconst TOKEN_PATTERN = /^[\\x21-\\x7E]+$/;\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001F\\u007F]/;\nconst PATH_BASE = \"https://crafty.invalid\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isPositiveInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value > 0;\n}\n\nfunction parseFieldPath(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const trimmed = value.trim();\n\n return trimmed === \"\" || trimmed.length > MAX_FIELD_LENGTH || !FIELD_PATTERN.test(trimmed) ? null : trimmed;\n}\n\nfunction parseLabel(value: unknown): string {\n return typeof value === \"string\" ? value.trim().slice(0, MAX_LABEL_LENGTH).trim() : \"\";\n}\n\nexport function parseFieldRef(value: unknown): CraftyFieldRef | null {\n if (!isRecord(value)) {\n return null;\n }\n\n const { type, id } = value;\n const field = parseFieldPath(value.field);\n\n if ((type !== \"block\" && type !== \"entry\") || !isPositiveInteger(id) || field === null) {\n return null;\n }\n\n return { type, id, field };\n}\n\n/** An invalid `hrefField` is dropped; the text field stays selectable. */\nexport function parseMarkedField(value: unknown): CraftyMarkedField | null {\n const ref = parseFieldRef(value);\n\n if (ref === null || !isRecord(value)) {\n return null;\n }\n\n const marked: CraftyMarkedField = { ...ref };\n const label = parseLabel(value.label);\n const hrefField = parseFieldPath(value.hrefField);\n\n if (label !== \"\") {\n marked.label = label;\n }\n\n if (hrefField !== null) {\n marked.hrefField = hrefField;\n\n const hrefLabel = parseLabel(value.hrefLabel);\n\n if (hrefLabel !== \"\") {\n marked.hrefLabel = hrefLabel;\n }\n }\n\n return marked;\n}\n\nfunction isSameOriginPath(value: string): boolean {\n if (!value.startsWith(\"/\") || value.startsWith(\"//\") || value.startsWith(\"/\\\\\")) {\n return false;\n }\n\n try {\n const url = new URL(value, PATH_BASE);\n\n // Dot segments can still resolve to a protocol-relative path (\"/.//evil.example\").\n return url.origin === PATH_BASE && !url.pathname.startsWith(\"//\") && !url.pathname.startsWith(\"/\\\\\");\n } catch {\n return false;\n }\n}\n\nfunction parsePath(value: unknown): string | null {\n if (typeof value !== \"string\" || value.length > MAX_PATH_LENGTH || CONTROL_CHARACTERS.test(value)) {\n return null;\n }\n\n return isSameOriginPath(value) ? value : null;\n}\n\nfunction parseShownEntry(value: unknown): CraftyShownEntry | null {\n return isRecord(value) && isPositiveInteger(value.id) && typeof value.collection === \"string\"\n ? { id: value.id, collection: value.collection }\n : null;\n}\n\nfunction readEnvelope(data: unknown): { type: string; payload: Record<string, unknown> } | null {\n if (!isRecord(data) || data.v !== PROTOCOL_VERSION || typeof data.type !== \"string\") {\n return null;\n }\n\n const payload = data.payload === undefined ? {} : data.payload;\n\n return isRecord(payload) ? { type: data.type, payload } : null;\n}\n\nexport function parseInboundMessage(data: unknown): InboundMessage | null {\n const message = readEnvelope(data);\n\n if (message === null) {\n return null;\n }\n\n const { payload } = message;\n\n switch (message.type) {\n case \"crafty:token\": {\n const token = typeof payload.token === \"string\" ? payload.token.trim() : \"\";\n\n return token !== \"\" && token.length <= MAX_TOKEN_LENGTH && TOKEN_PATTERN.test(token)\n ? { v: PROTOCOL_VERSION, type: \"crafty:token\", payload: { token } }\n : null;\n }\n case \"crafty:refresh\":\n return { v: PROTOCOL_VERSION, type: \"crafty:refresh\", payload: {} };\n case \"crafty:highlight\": {\n const ref = parseFieldRef(payload);\n\n return ref ? { v: PROTOCOL_VERSION, type: \"crafty:highlight\", payload: ref } : null;\n }\n case \"crafty:preview-field\": {\n const ref = parseFieldRef(payload);\n const value = payload.value;\n\n return ref && typeof value === \"string\" && value.length <= MAX_VALUE_LENGTH\n ? { v: PROTOCOL_VERSION, type: \"crafty:preview-field\", payload: { ...ref, value } }\n : null;\n }\n case \"crafty:preview-reset\": {\n const ref = parseFieldRef(payload);\n\n return ref ? { v: PROTOCOL_VERSION, type: \"crafty:preview-reset\", payload: ref } : null;\n }\n default:\n return null;\n }\n}\n\nexport function parseOutboundMessage(data: unknown): OutboundMessage | null {\n const message = readEnvelope(data);\n\n if (message === null) {\n return null;\n }\n\n const { payload } = message;\n\n switch (message.type) {\n case \"crafty:ready\": {\n const path = parsePath(payload.path);\n const rawPage = payload.page;\n\n if (typeof payload.sdkVersion !== \"string\" || path === null || !Array.isArray(payload.fields) || !Array.isArray(payload.entries)) {\n return null;\n }\n\n return {\n v: PROTOCOL_VERSION,\n type: \"crafty:ready\",\n payload: {\n sdkVersion: payload.sdkVersion,\n path,\n fields: payload.fields\n .map((field: unknown) => parseMarkedField(field))\n .filter((field): field is CraftyMarkedField => field !== null),\n page:\n isRecord(rawPage) && isPositiveInteger(rawPage.id) && typeof rawPage.slug === \"string\"\n ? { id: rawPage.id, slug: rawPage.slug }\n : null,\n entries: payload.entries\n .map((entry: unknown) => parseShownEntry(entry))\n .filter((entry): entry is CraftyShownEntry => entry !== null)\n }\n };\n }\n case \"crafty:select\": {\n const field = parseMarkedField(payload);\n\n return field ? { v: PROTOCOL_VERSION, type: \"crafty:select\", payload: field } : null;\n }\n case \"crafty:navigate\": {\n const path = parsePath(payload.path);\n\n return path ? { v: PROTOCOL_VERSION, type: \"crafty:navigate\", payload: { path } } : null;\n }\n case \"crafty:preview-invalid\":\n return { v: PROTOCOL_VERSION, type: \"crafty:preview-invalid\", payload: {} };\n case \"crafty:key\":\n return payload.key === \"Escape\" ? { v: PROTOCOL_VERSION, type: \"crafty:key\", payload: { key: \"Escape\" } } : null;\n default:\n return null;\n }\n}\n", "import { parseMarkedField, type CraftyFieldRef, type CraftyMarkedField } from \"./protocol.js\";\n\nexport const MARKED_SELECTOR = \"[data-crafty-field]\";\n\nexport type MarkedElement = { element: Element; field: CraftyMarkedField };\n\nexport function readMarkedField(element: Element): CraftyMarkedField | null {\n const blockId = element.getAttribute(\"data-crafty-block\");\n const entryId = element.getAttribute(\"data-crafty-entry\");\n const rawId = blockId ?? entryId;\n\n if (rawId === null) {\n return null;\n }\n\n return parseMarkedField({\n type: blockId !== null ? \"block\" : \"entry\",\n id: rawId.trim() === \"\" ? Number.NaN : Number(rawId),\n field: element.getAttribute(\"data-crafty-field\") ?? \"\",\n label: element.getAttribute(\"data-crafty-label\"),\n hrefField: element.getAttribute(\"data-crafty-href-field\"),\n hrefLabel: element.getAttribute(\"data-crafty-href-label\")\n });\n}\n\nexport function refKey(ref: CraftyFieldRef): string {\n return `${ref.type}:${ref.id}:${ref.field}`;\n}\n\nexport function scanMarked(root: ParentNode): MarkedElement[] {\n const marked: MarkedElement[] = [];\n\n root.querySelectorAll(MARKED_SELECTOR).forEach((element) => {\n const field = readMarkedField(element);\n\n if (field !== null) {\n marked.push({ element, field });\n }\n });\n\n return marked;\n}\n\nexport function uniqueFields(marked: MarkedElement[]): CraftyMarkedField[] {\n const seen = new Set<string>();\n const fields: CraftyMarkedField[] = [];\n\n for (const { field } of marked) {\n const key = refKey(field);\n\n if (!seen.has(key)) {\n seen.add(key);\n fields.push(field);\n }\n }\n\n return fields;\n}\n", "import { MARKED_SELECTOR, readMarkedField, refKey } from \"./markers.js\";\nimport type { CraftyFieldRef } from \"./protocol.js\";\n\nexport type LivePreview = {\n set(ref: CraftyFieldRef, value: string): void;\n reset(ref: CraftyFieldRef): void;\n reapply(): void;\n resetAll(): void;\n readonly size: number;\n};\n\n/**\n * Plain-text live preview. Values are written with `textContent` (never HTML),\n * and each element's own original text is kept so a reset restores exactly what\n * the site rendered, even for elements rendered after the value was set.\n */\nexport function createLivePreview(root: ParentNode): LivePreview {\n const values = new Map<string, string>();\n const originals = new Map<Element, string>();\n\n const matching = (key: string): Element[] =>\n Array.from(root.querySelectorAll(MARKED_SELECTOR)).filter((element) => {\n const field = readMarkedField(element);\n\n return field !== null && refKey(field) === key;\n });\n\n const write = (element: Element, value: string): void => {\n if (!originals.has(element)) {\n originals.set(element, element.textContent ?? \"\");\n }\n\n if (element.textContent !== value) {\n element.textContent = value;\n }\n };\n\n const restore = (key: string | null): void => {\n for (const [element, original] of originals) {\n const field = readMarkedField(element);\n\n if (key === null || (field !== null && refKey(field) === key)) {\n if (element.textContent !== original) {\n element.textContent = original;\n }\n\n originals.delete(element);\n }\n }\n };\n\n return {\n set(ref, value) {\n const key = refKey(ref);\n values.set(key, value);\n matching(key).forEach((element) => write(element, value));\n },\n reset(ref) {\n const key = refKey(ref);\n values.delete(key);\n restore(key);\n },\n reapply() {\n for (const element of [...originals.keys()]) {\n if (!element.isConnected) {\n originals.delete(element);\n }\n }\n\n for (const [key, value] of values) {\n matching(key).forEach((element) => write(element, value));\n }\n },\n resetAll() {\n values.clear();\n restore(null);\n },\n get size() {\n return values.size;\n }\n };\n}\n", "/** Crafty admin panels: https://crafty.do and https://<tenant>.crafty.do. */\nexport const DEFAULT_ADMIN_ORIGINS: ReadonlyArray<string | RegExp> = [/^https:\\/\\/([a-z0-9-]+\\.)*crafty\\.do$/];\n\nfunction originOf(value: string): string | null {\n try {\n return new URL(value).origin;\n } catch {\n return null;\n }\n}\n\nexport function isAllowedAdminOrigin(origin: string, allowlist: ReadonlyArray<string | RegExp>): boolean {\n if (origin === \"\" || origin === \"null\") {\n return false;\n }\n\n return allowlist.some((allowed) => {\n if (typeof allowed === \"string\") {\n return originOf(allowed) === origin;\n }\n\n allowed.lastIndex = 0;\n\n return allowed.test(origin);\n });\n}\n\n/**\n * Origin of the embedding admin. `ancestorOrigins` (Chromium, WebKit) cannot be\n * spoofed by the framed page; Firefox falls back to the referrer the admin sent\n * when it set the iframe `src`.\n */\nexport function resolveParentOrigin(win: Window): string | null {\n const ancestors = win.location.ancestorOrigins as ArrayLike<string> | undefined;\n const first = ancestors && ancestors.length > 0 ? ancestors[0] : undefined;\n\n if (typeof first === \"string\" && first !== \"\") {\n return first;\n }\n\n const referrer = win.document.referrer;\n\n return referrer ? originOf(referrer) : null;\n}\n", "const STYLE_ELEMENT_ID = \"crafty-visual-editing-style\";\nconst ACCENT = \"#4f46e5\";\n\nexport const FLASH_CLASS = \"crafty-ve-flash\";\n\nconst STYLES = [\n \"[data-crafty-field]{cursor:pointer}\",\n `.crafty-ve-box{position:fixed;top:0;left:0;pointer-events:none;z-index:2147483647;box-sizing:border-box;border:2px solid ${ACCENT};border-radius:4px;background:rgba(79,70,229,.06)}`,\n \".crafty-ve-box[hidden]{display:none}\",\n `.crafty-ve-label{position:absolute;left:-2px;bottom:100%;margin-bottom:4px;padding:2px 8px;max-width:320px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border-radius:4px;background:${ACCENT};color:#fff;font:500 12px/1.5 system-ui,-apple-system,sans-serif}`,\n `.${FLASH_CLASS}{outline:2px dashed ${ACCENT} !important;outline-offset:2px !important}`\n].join(\"\\n\");\n\nexport type Overlay = {\n show(element: Element, label: string): void;\n hide(): void;\n /** Re-measures the highlighted element, e.g. after its content changed. */\n reposition(): void;\n flash(elements: Element[], durationMs: number): void;\n ensureAttached(): void;\n contains(node: Node | null): boolean;\n destroy(): void;\n};\n\nexport function createOverlay(doc: Document): Overlay {\n const win = doc.defaultView;\n const style = doc.createElement(\"style\");\n style.id = STYLE_ELEMENT_ID;\n style.textContent = STYLES;\n\n const box = doc.createElement(\"div\");\n box.setAttribute(\"data-crafty-overlay\", \"\");\n box.className = \"crafty-ve-box\";\n box.hidden = true;\n\n const label = doc.createElement(\"span\");\n label.className = \"crafty-ve-label\";\n box.appendChild(label);\n\n let target: Element | null = null;\n let flashed: Element[] = [];\n let flashTimer: number | undefined;\n const Observer = (win as (Window & { ResizeObserver?: typeof ResizeObserver }) | null)?.ResizeObserver;\n\n const place = (): void => {\n if (target === null) {\n return;\n }\n\n const rect = target.getBoundingClientRect();\n box.style.top = `${rect.top}px`;\n box.style.left = `${rect.left}px`;\n box.style.width = `${rect.width}px`;\n box.style.height = `${rect.height}px`;\n };\n\n const resizeObserver = typeof Observer === \"function\" ? new Observer(() => place()) : null;\n\n const track = (element: Element | null): void => {\n if (target === element) {\n return;\n }\n\n if (target !== null) {\n resizeObserver?.unobserve(target);\n }\n\n target = element;\n\n if (target !== null) {\n resizeObserver?.observe(target);\n }\n };\n\n const clearFlash = (): void => {\n flashed.forEach((element) => element.classList.remove(FLASH_CLASS));\n flashed = [];\n\n if (flashTimer !== undefined) {\n win?.clearTimeout(flashTimer);\n flashTimer = undefined;\n }\n };\n\n const ensureAttached = (): void => {\n if (!style.isConnected) {\n (doc.head ?? doc.documentElement).appendChild(style);\n }\n\n if (!box.isConnected) {\n (doc.body ?? doc.documentElement).appendChild(box);\n }\n };\n\n ensureAttached();\n win?.addEventListener(\"scroll\", place, { capture: true, passive: true });\n win?.addEventListener(\"resize\", place, { passive: true });\n\n return {\n show(element, text) {\n ensureAttached();\n track(element);\n\n if (label.textContent !== text) {\n label.textContent = text;\n }\n\n box.hidden = false;\n place();\n },\n hide() {\n track(null);\n box.hidden = true;\n },\n reposition() {\n place();\n },\n flash(elements, durationMs) {\n clearFlash();\n flashed = [...elements];\n flashed.forEach((element) => element.classList.add(FLASH_CLASS));\n flashTimer = win?.setTimeout(clearFlash, durationMs);\n },\n ensureAttached,\n contains(node) {\n return node !== null && (box === node || box.contains(node) || style === node || style.contains(node));\n },\n destroy() {\n clearFlash();\n win?.removeEventListener(\"scroll\", place, { capture: true });\n win?.removeEventListener(\"resize\", place);\n resizeObserver?.disconnect();\n box.remove();\n style.remove();\n target = null;\n }\n };\n}\n", "import type { CraftyClient } from \"../client.js\";\nimport {\n PREVIEW_ACTIVE_EVENT,\n PREVIEW_CONTENT_EVENT,\n PREVIEW_INVALID_EVENT,\n PREVIEW_QUERY_PARAM,\n getPreviewContent,\n getPreviewStatus,\n readPreviewToken,\n storePreviewToken\n} from \"../preview.js\";\nimport { SDK_VERSION } from \"../version.js\";\nimport { createLivePreview } from \"./live-preview.js\";\nimport { MARKED_SELECTOR, readMarkedField, refKey, scanMarked, uniqueFields, type MarkedElement } from \"./markers.js\";\nimport { DEFAULT_ADMIN_ORIGINS, isAllowedAdminOrigin, resolveParentOrigin } from \"./origin.js\";\nimport { createOverlay } from \"./overlay.js\";\nimport {\n PROTOCOL_VERSION,\n parseInboundMessage,\n type CraftyFieldRef,\n type CraftyMarkedField,\n type CraftyShownEntry,\n type CraftyShownPage,\n type InboundMessage,\n type OutboundMessage\n} from \"./protocol.js\";\n\nexport type VisualEditingOptions = {\n /** Allowed admin origins. Replaces the default (`https://*.crafty.do`). */\n adminOrigins?: ReadonlyArray<string | RegExp>;\n /** Re-fetch and re-render instead of a full reload when the admin asks for a refresh. */\n onRefresh?: () => void | Promise<void>;\n /** Page rendered by the server (SSR sites, where the browser did not fetch it). */\n page?: CraftyShownPage | null;\n /** Entries rendered by the server (SSR sites). */\n entries?: CraftyShownEntry[];\n /** How long touch devices highlight every editable after load. Default 1500 ms. */\n touchHighlightMs?: number;\n /**\n * Client used to confirm the preview token when no preview request has been\n * answered yet (one `pages.list({ per_page: 1 })` call). Without it the bridge\n * waits for the site's own first Crafty request to confirm the token.\n */\n client?: Pick<CraftyClient, \"pages\">;\n};\n\nexport type VisualEditingHandle = {\n readonly active: boolean;\n disable(): void;\n};\n\nconst SCROLL_STORAGE_KEY = \"crafty:scroll-y\";\nconst RESCAN_DELAY_MS = 50;\nconst DEFAULT_TOUCH_HIGHLIGHT_MS = 1500;\nconst WATCHED_ATTRIBUTES = [\n \"data-crafty-field\",\n \"data-crafty-block\",\n \"data-crafty-entry\",\n \"data-crafty-label\",\n \"data-crafty-href-field\",\n \"data-crafty-href-label\"\n];\n\nconst inactiveHandle: VisualEditingHandle = { active: false, disable: () => undefined };\nlet activeHandle: VisualEditingHandle | null = null;\n\n/**\n * Connects the page to the Crafty visual editor. No-op unless the page runs in\n * an iframe, carries a preview token, and its parent is an allowed admin origin.\n *\n * The default allowlist (`*.crafty.do`) also covers sites hosted by Crafty, so\n * the bridge stays inert (no overlay, no listeners, no messages) until the API\n * answers a preview request with `X-Crafty-Preview-Status: active`. On `invalid`\n * it only tells the admin `crafty:preview-invalid` and stays inert.\n */\nexport function enableVisualEditing(options: VisualEditingOptions = {}): VisualEditingHandle {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return inactiveHandle;\n }\n\n if (activeHandle !== null) {\n return activeHandle;\n }\n\n const win = window;\n\n if (win.parent === null || win.parent === win || readPreviewToken() === null) {\n return inactiveHandle;\n }\n\n const parentOrigin = resolveParentOrigin(win);\n\n if (parentOrigin === null || !isAllowedAdminOrigin(parentOrigin, options.adminOrigins ?? DEFAULT_ADMIN_ORIGINS)) {\n return inactiveHandle;\n }\n\n const status = getPreviewStatus();\n\n if (status === \"invalid\") {\n postPreviewInvalid(win, parentOrigin);\n\n return inactiveHandle;\n }\n\n activeHandle = status === \"active\" ? startBridge(win, parentOrigin, options) : awaitConfirmation(win, parentOrigin, options);\n\n return activeHandle;\n}\n\nfunction postPreviewInvalid(win: Window, parentOrigin: string): void {\n const message: OutboundMessage = { v: PROTOCOL_VERSION, type: \"crafty:preview-invalid\", payload: {} };\n win.parent.postMessage(message, parentOrigin);\n}\n\n/**\n * Pending handle: waits for the API to confirm the token before starting the\n * bridge, verifying it through `options.client` when one is given.\n */\nfunction awaitConfirmation(win: Window, parentOrigin: string, options: VisualEditingOptions): VisualEditingHandle {\n let bridge: VisualEditingHandle | null = null;\n let settled = false;\n\n const stopWaiting = (): void => {\n settled = true;\n win.removeEventListener(PREVIEW_ACTIVE_EVENT, onActive);\n win.removeEventListener(PREVIEW_INVALID_EVENT, onInvalid);\n };\n\n const release = (): void => {\n if (activeHandle === handle) {\n activeHandle = null;\n }\n };\n\n const onActive = (): void => {\n if (settled) {\n return;\n }\n\n stopWaiting();\n bridge = startBridge(win, parentOrigin, options, release);\n };\n\n const onInvalid = (): void => {\n if (settled) {\n return;\n }\n\n stopWaiting();\n release();\n postPreviewInvalid(win, parentOrigin);\n };\n\n const handle: VisualEditingHandle = {\n get active() {\n return bridge?.active ?? false;\n },\n disable() {\n stopWaiting();\n bridge?.disable();\n release();\n }\n };\n\n win.addEventListener(PREVIEW_ACTIVE_EVENT, onActive);\n win.addEventListener(PREVIEW_INVALID_EVENT, onInvalid);\n\n // The status handlers above settle the outcome; request errors leave the bridge waiting.\n options.client?.pages.list({ per_page: 1 }).catch(() => undefined);\n\n return handle;\n}\n\nfunction startBridge(\n win: Window,\n parentOrigin: string,\n options: VisualEditingOptions,\n onDisable?: () => void\n): VisualEditingHandle {\n const doc = win.document;\n const overlay = createOverlay(doc);\n const livePreview = createLivePreview(doc);\n const pendingScrollY = takeStoredScroll(win);\n\n let marked: MarkedElement[] = [];\n let sentSignature: string | null = null;\n let rescanTimer: number | undefined;\n let forceReady = false;\n let active = true;\n\n const post = (message: OutboundMessage): void => {\n win.parent.postMessage(message, parentOrigin);\n };\n\n const sendReady = (): void => {\n const fields = uniqueFields(marked);\n const content = getPreviewContent();\n sentSignature = signatureOf(fields);\n\n post({\n v: PROTOCOL_VERSION,\n type: \"crafty:ready\",\n payload: {\n sdkVersion: SDK_VERSION,\n path: currentPath(win),\n fields,\n page: content.page ?? options.page ?? null,\n entries: mergeEntries(content.entries, options.entries ?? [])\n }\n });\n };\n\n const rescan = (): void => {\n rescanTimer = undefined;\n\n if (!active) {\n return;\n }\n\n overlay.ensureAttached();\n marked = scanMarked(doc);\n livePreview.reapply();\n\n if (forceReady || signatureOf(uniqueFields(marked)) !== sentSignature) {\n forceReady = false;\n sendReady();\n }\n };\n\n const scheduleRescan = (): void => {\n if (active && rescanTimer === undefined) {\n rescanTimer = win.setTimeout(rescan, RESCAN_DELAY_MS);\n }\n };\n\n const observer = new MutationObserver((records) => {\n if (records.some((record) => !overlay.contains(record.target))) {\n scheduleRescan();\n }\n });\n\n const labelOf = (field: CraftyMarkedField): string => field.label ?? field.field;\n\n const onPointerOver = (event: PointerEvent): void => {\n if (event.pointerType === \"touch\") {\n return;\n }\n\n const hit = hitFrom(event.target);\n\n if (hit !== null) {\n overlay.show(hit.element, labelOf(hit.field));\n } else {\n overlay.hide();\n }\n };\n\n const block = (event: Event): void => {\n event.preventDefault();\n event.stopPropagation();\n };\n\n /**\n * Runs in the capture phase on `window`, before any site listener, so a marked\n * element always selects even when it is (or sits inside) a link or button,\n * and nothing the site renders can take the iframe out of the editor.\n */\n const onClick = (event: MouseEvent): void => {\n const hit = hitFrom(event.target);\n\n if (hit !== null) {\n block(event);\n overlay.show(hit.element, labelOf(hit.field));\n post({ v: PROTOCOL_VERSION, type: \"crafty:select\", payload: hit.field });\n\n return;\n }\n\n const action = linkAction(event, win);\n\n if (action.kind === \"allow\") {\n return;\n }\n\n block(event);\n\n if (action.kind === \"navigate\") {\n post({ v: PROTOCOL_VERSION, type: \"crafty:navigate\", payload: { path: action.path } });\n }\n };\n\n /** Middle clicks open links in a new tab: never let them leave the editor. */\n const onAuxClick = (event: MouseEvent): void => {\n if (hitFrom(event.target) !== null || closestLink(event.target) !== null) {\n block(event);\n }\n };\n\n const onSubmit = (event: Event): void => {\n block(event);\n };\n\n /**\n * Escape pressed while focus is inside the iframe never reaches the admin\n * window: forward it so the admin closes its topmost sheet or dialog. Runs in\n * the bubble phase, after the site, and skips an Escape the site handled\n * (`preventDefault`, e.g. to close its own menu).\n */\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.repeat || event.isComposing || event.defaultPrevented) {\n return;\n }\n\n post({ v: PROTOCOL_VERSION, type: \"crafty:key\", payload: { key: \"Escape\" } });\n };\n\n const highlight = (ref: CraftyFieldRef): void => {\n const key = refKey(ref);\n const match = scanMarked(doc).find((item) => refKey(item.field) === key);\n\n if (match === undefined) {\n return;\n }\n\n const element = match.element as Element & { scrollIntoView?: (options?: ScrollIntoViewOptions) => void };\n element.scrollIntoView?.({ block: \"center\", behavior: \"smooth\" });\n overlay.show(match.element, labelOf(match.field));\n };\n\n const refresh = async (): Promise<void> => {\n if (options.onRefresh) {\n try {\n await options.onRefresh();\n } finally {\n scheduleRescan();\n }\n\n return;\n }\n\n try {\n win.sessionStorage.setItem(SCROLL_STORAGE_KEY, String(win.scrollY));\n } catch {\n // Storage blocked: reload without restoring the scroll position.\n }\n\n win.location.reload();\n };\n\n const handleInbound = (message: InboundMessage): void => {\n switch (message.type) {\n case \"crafty:token\":\n storePreviewToken(message.payload.token);\n return;\n case \"crafty:refresh\":\n refresh().catch((error: unknown) => console.error(\"[crafty] onRefresh failed\", error));\n return;\n case \"crafty:highlight\":\n highlight(message.payload);\n return;\n case \"crafty:preview-field\":\n livePreview.set(message.payload, message.payload.value);\n overlay.reposition();\n return;\n case \"crafty:preview-reset\":\n livePreview.reset(message.payload);\n overlay.reposition();\n return;\n }\n };\n\n const onMessage = (event: MessageEvent): void => {\n if (event.source !== win.parent || event.origin !== parentOrigin) {\n return;\n }\n\n const message = parseInboundMessage(event.data);\n\n if (message !== null) {\n handleInbound(message);\n }\n };\n\n const onPreviewInvalid = (): void => {\n post({ v: PROTOCOL_VERSION, type: \"crafty:preview-invalid\", payload: {} });\n };\n\n const onPreviewContent = (): void => {\n forceReady = true;\n scheduleRescan();\n };\n\n const start = (): void => {\n if (!active) {\n return;\n }\n\n marked = scanMarked(doc);\n sendReady();\n\n if (isTouchDevice(win)) {\n overlay.flash(\n marked.map((item) => item.element),\n options.touchHighlightMs ?? DEFAULT_TOUCH_HIGHLIGHT_MS\n );\n }\n\n restoreScroll(win, pendingScrollY);\n };\n\n win.addEventListener(\"message\", onMessage);\n win.addEventListener(\"click\", onClick, true);\n win.addEventListener(\"auxclick\", onAuxClick, true);\n win.addEventListener(\"submit\", onSubmit, true);\n win.addEventListener(\"keydown\", onKeyDown);\n doc.addEventListener(\"pointerover\", onPointerOver, true);\n win.addEventListener(PREVIEW_INVALID_EVENT, onPreviewInvalid);\n win.addEventListener(PREVIEW_CONTENT_EVENT, onPreviewContent);\n observer.observe(doc.documentElement, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: WATCHED_ATTRIBUTES\n });\n\n if (doc.readyState === \"loading\") {\n doc.addEventListener(\"DOMContentLoaded\", start, { once: true });\n } else {\n start();\n }\n\n const handle: VisualEditingHandle = {\n get active() {\n return active;\n },\n disable() {\n if (!active) {\n return;\n }\n\n active = false;\n win.removeEventListener(\"message\", onMessage);\n win.removeEventListener(\"click\", onClick, true);\n win.removeEventListener(\"auxclick\", onAuxClick, true);\n win.removeEventListener(\"submit\", onSubmit, true);\n win.removeEventListener(\"keydown\", onKeyDown);\n doc.removeEventListener(\"pointerover\", onPointerOver, true);\n doc.removeEventListener(\"DOMContentLoaded\", start);\n win.removeEventListener(PREVIEW_INVALID_EVENT, onPreviewInvalid);\n win.removeEventListener(PREVIEW_CONTENT_EVENT, onPreviewContent);\n observer.disconnect();\n\n if (rescanTimer !== undefined) {\n win.clearTimeout(rescanTimer);\n rescanTimer = undefined;\n }\n\n livePreview.resetAll();\n overlay.destroy();\n\n if (activeHandle === handle) {\n activeHandle = null;\n }\n\n onDisable?.();\n }\n };\n\n return handle;\n}\n\nfunction asElement(target: EventTarget | null): Element | null {\n return target !== null && typeof (target as Element).closest === \"function\" ? (target as Element) : null;\n}\n\nfunction signatureOf(fields: CraftyMarkedField[]): string {\n return fields.map((field) => `${refKey(field)}|${field.label ?? \"\"}|${field.hrefField ?? \"\"}|${field.hrefLabel ?? \"\"}`).join(\"\\n\");\n}\n\nfunction mergeEntries(fetched: CraftyShownEntry[], declared: CraftyShownEntry[]): CraftyShownEntry[] {\n const seen = new Set<string>();\n\n return [...fetched, ...declared].filter((entry) => {\n const key = `${entry.collection}:${entry.id}`;\n\n if (seen.has(key)) {\n return false;\n }\n\n seen.add(key);\n\n return true;\n });\n}\n\nfunction stripPreviewParam(url: URL): string {\n url.searchParams.delete(PREVIEW_QUERY_PARAM);\n\n return `${url.pathname}${url.search}`;\n}\n\nfunction currentPath(win: Window): string {\n return stripPreviewParam(new URL(win.location.href));\n}\n\ntype LinkAction = { kind: \"allow\" } | { kind: \"block\" } | { kind: \"navigate\"; path: string };\n\n/**\n * Only links fall back to their marked descendant: following them would leave\n * the editor. Buttons, `<summary>` and labels keep their own behavior (menus,\n * accordions, tabs) when the click misses the marked element.\n */\nconst LINK_SELECTOR = \"a[href], area[href]\";\n\n/**\n * The marked element a pointer or click target maps to: the innermost valid\n * marked ancestor (or the target itself), else the first marked element inside\n * the link that was clicked, so clicking a link button's padding or icon\n * selects its label.\n */\nfunction hitFrom(target: EventTarget | null): MarkedElement | null {\n const element = asElement(target);\n\n if (element === null) {\n return null;\n }\n\n for (let node = element.closest(MARKED_SELECTOR); node !== null; node = node.parentElement?.closest(MARKED_SELECTOR) ?? null) {\n const field = readMarkedField(node);\n\n if (field !== null) {\n return { element: node, field };\n }\n }\n\n const link = element.closest(LINK_SELECTOR);\n\n return link !== null ? (scanMarked(link)[0] ?? null) : null;\n}\n\nfunction closestLink(target: EventTarget | null): Element | null {\n return asElement(target)?.closest(LINK_SELECTOR) ?? null;\n}\n\n/**\n * What to do with a click that hit no marked element. Only same-page anchors\n * run as usual; same-origin links become `crafty:navigate`; anything that\n * would leave the editor (other origins, `mailto:`/`tel:`, new tabs,\n * downloads, modified clicks) is blocked.\n */\nfunction linkAction(event: MouseEvent, win: Window): LinkAction {\n const anchor = closestLink(event.target);\n\n if (anchor === null) {\n return { kind: \"allow\" };\n }\n\n if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || anchor.hasAttribute(\"download\")) {\n return { kind: \"block\" };\n }\n\n const target = anchor.getAttribute(\"target\");\n\n if (target !== null && target !== \"\" && target !== \"_self\") {\n return { kind: \"block\" };\n }\n\n const href = anchor.getAttribute(\"href\") ?? \"\";\n let url: URL;\n\n try {\n url = new URL(href, win.location.href);\n } catch {\n return { kind: \"block\" };\n }\n\n if (url.origin !== win.location.origin || (url.protocol !== \"http:\" && url.protocol !== \"https:\")) {\n return { kind: \"block\" };\n }\n\n const path = stripPreviewParam(url);\n\n if ((url.hash !== \"\" || href.startsWith(\"#\")) && path === currentPath(win)) {\n return { kind: \"allow\" };\n }\n\n return { kind: \"navigate\", path };\n}\n\nfunction isTouchDevice(win: Window): boolean {\n return typeof win.matchMedia === \"function\" && win.matchMedia(\"(hover: none)\").matches;\n}\n\nfunction takeStoredScroll(win: Window): number | null {\n try {\n const raw = win.sessionStorage.getItem(SCROLL_STORAGE_KEY);\n win.sessionStorage.removeItem(SCROLL_STORAGE_KEY);\n const scrollY = raw === null ? Number.NaN : Number(raw);\n\n return Number.isFinite(scrollY) ? scrollY : null;\n } catch {\n return null;\n }\n}\n\nfunction restoreScroll(win: Window, scrollY: number | null): void {\n if (scrollY === null) {\n return;\n }\n\n const apply = (): void => win.scrollTo(0, scrollY);\n\n if (win.document.readyState === \"complete\") {\n apply();\n } else {\n win.addEventListener(\"load\", apply, { once: true });\n }\n}\n"],
|
|
4
|
+
"sourcesContent": ["/** Entry for the `<script>` build: exposed as `window.CraftyVisualEditing`. */\nexport { attrs, attrsHtml } from \"./attrs.js\";\nexport { enableVisualEditing } from \"./visual-editing/bridge.js\";\nexport { PROTOCOL_VERSION } from \"./visual-editing/protocol.js\";\n", "import type { CraftyBlock, CraftyEntry } from \"./types/public.js\";\n\nexport type CraftyEditTargetType = \"block\" | \"entry\";\n\n/**\n * A block or entry as returned by the API, or an explicit reference for\n * ambiguous shapes (e.g. an entry with fields named `order`, `data` and `type`).\n */\nexport type CraftyEditTarget =\n | CraftyBlock\n | CraftyEntry\n | { kind: CraftyEditTargetType; id: number | string };\n\nexport type CraftyAttrsOptions = {\n /** Human label shown by the visual editor, e.g. \"T\u00EDtulo de la secci\u00F3n\". */\n label?: string;\n /**\n * Field holding the link destination of this element (a button or link whose\n * text is `field`), e.g. `hero.cta.href`. The editor then edits both together.\n */\n hrefField?: string;\n /** Human label for `hrefField`. Defaults to \"Enlace\" in the editor. */\n hrefLabel?: string;\n};\n\nexport type CraftyEditAttributes = {\n \"data-crafty-block\"?: string;\n \"data-crafty-entry\"?: string;\n \"data-crafty-field\"?: string;\n \"data-crafty-label\"?: string;\n \"data-crafty-href-field\"?: string;\n \"data-crafty-href-label\"?: string;\n};\n\nexport function resolveEditTarget(\n target: CraftyEditTarget | null | undefined\n): { type: CraftyEditTargetType; id: number } | null {\n if (target === null || target === undefined || typeof target !== \"object\") {\n return null;\n }\n\n const record = target as Record<string, unknown>;\n const id = typeof record.id === \"string\" ? Number(record.id.trim()) : record.id;\n\n if (typeof id !== \"number\" || !Number.isInteger(id) || id <= 0) {\n return null;\n }\n\n if (record.kind === \"block\" || record.kind === \"entry\") {\n return { type: record.kind, id };\n }\n\n const looksLikeBlock =\n typeof record.order === \"number\" &&\n typeof record.data === \"object\" &&\n record.data !== null &&\n \"type\" in record;\n\n return { type: looksLikeBlock ? \"block\" : \"entry\", id };\n}\n\n/**\n * DOM attributes that let the visual editor map an element to a field.\n * Always emitted (static sites render them at build time without a token).\n * `field` is a top-level field key or a JSON path such as `sections[3].title`.\n */\nexport function attrs(\n target: CraftyEditTarget | null | undefined,\n field: string,\n options: CraftyAttrsOptions = {}\n): CraftyEditAttributes {\n const resolved = resolveEditTarget(target);\n const normalizedField = typeof field === \"string\" ? field.trim() : \"\";\n\n if (resolved === null || normalizedField === \"\") {\n return {};\n }\n\n const attributes: CraftyEditAttributes =\n resolved.type === \"block\"\n ? { \"data-crafty-block\": String(resolved.id), \"data-crafty-field\": normalizedField }\n : { \"data-crafty-entry\": String(resolved.id), \"data-crafty-field\": normalizedField };\n\n const label = typeof options.label === \"string\" ? options.label.trim() : \"\";\n\n if (label !== \"\") {\n attributes[\"data-crafty-label\"] = label;\n }\n\n const hrefField = typeof options.hrefField === \"string\" ? options.hrefField.trim() : \"\";\n\n if (hrefField !== \"\") {\n attributes[\"data-crafty-href-field\"] = hrefField;\n\n const hrefLabel = typeof options.hrefLabel === \"string\" ? options.hrefLabel.trim() : \"\";\n\n if (hrefLabel !== \"\") {\n attributes[\"data-crafty-href-label\"] = hrefLabel;\n }\n }\n\n return attributes;\n}\n\n/** Same as `attrs()`, rendered for HTML string templates. */\nexport function attrsHtml(\n target: CraftyEditTarget | null | undefined,\n field: string,\n options: CraftyAttrsOptions = {}\n): string {\n return Object.entries(attrs(target, field, options))\n .map(([name, value]) => `${name}=\"${escapeAttribute(String(value))}\"`)\n .join(\" \");\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n", "export const PREVIEW_QUERY_PARAM = \"crafty_preview\";\nexport const PREVIEW_HEADER = \"X-Crafty-Preview\";\nexport const PREVIEW_STATUS_HEADER = \"X-Crafty-Preview-Status\";\nexport const PREVIEW_INVALID_EVENT = \"crafty:preview-invalid\";\nexport const PREVIEW_CONTENT_EVENT = \"crafty:preview-content\";\nexport const PREVIEW_ACTIVE_EVENT = \"crafty:preview-active\";\n\nconst TOKEN_STORAGE_KEY = \"crafty:preview-token\";\nconst URL_TOKEN_STORAGE_KEY = \"crafty:preview-url-token\";\nconst INVALID_TOKEN_STORAGE_KEY = \"crafty:preview-invalid-token\";\nconst CONTENT_GLOBAL_KEY = \"__CRAFTY_PREVIEW_CONTENT__\";\nconst STATUS_GLOBAL_KEY = \"__CRAFTY_PREVIEW_STATUS__\";\n\nexport type PreviewPage = { id: number; slug: string };\nexport type PreviewEntry = { id: number; collection: string };\nexport type PreviewContent = { page: PreviewPage | null; entries: PreviewEntry[] };\n/** Last `X-Crafty-Preview-Status` the API answered in this window, or null before any preview request. */\nexport type PreviewStatus = \"active\" | \"invalid\";\n\n/** A URL, a Web `Request`, a Node `IncomingMessage` or an Express-style request. */\nexport type PreviewRequestLike =\n | string\n | URL\n | { url?: string | undefined; query?: Record<string, unknown> | undefined };\n\ntype ContentHost = Record<string, PreviewContent | undefined>;\n\nfunction browserWindow(): Window | null {\n return typeof window === \"undefined\" ? null : window;\n}\n\nfunction storageGet(key: string): string | null {\n try {\n return browserWindow()?.sessionStorage.getItem(key) ?? null;\n } catch {\n return null;\n }\n}\n\nfunction storageSet(key: string, value: string): void {\n try {\n browserWindow()?.sessionStorage.setItem(key, value);\n } catch {\n // Storage can be blocked (private mode, sandboxed frames); the URL token still works.\n }\n}\n\nfunction storageRemove(key: string): void {\n try {\n browserWindow()?.sessionStorage.removeItem(key);\n } catch {\n // Ignore blocked storage.\n }\n}\n\nfunction normalizeToken(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : null;\n}\n\nfunction tokenFromUrl(url: string): string | null {\n try {\n return normalizeToken(new URL(url, \"http://localhost\").searchParams.get(PREVIEW_QUERY_PARAM));\n } catch {\n return null;\n }\n}\n\n/**\n * Preview token for browser requests. A token the URL brings for the first time\n * wins; afterwards the stored token wins, so a renewal received over\n * `postMessage` is not overwritten by the stale token still in the URL.\n */\nexport function readPreviewToken(): string | null {\n const win = browserWindow();\n\n if (win === null) {\n return null;\n }\n\n const urlToken = tokenFromUrl(win.location.href);\n let token: string | null;\n\n if (urlToken !== null && urlToken !== storageGet(URL_TOKEN_STORAGE_KEY)) {\n storageSet(URL_TOKEN_STORAGE_KEY, urlToken);\n storageSet(TOKEN_STORAGE_KEY, urlToken);\n token = urlToken;\n } else {\n token = normalizeToken(storageGet(TOKEN_STORAGE_KEY)) ?? urlToken;\n }\n\n return token !== null && token === storageGet(INVALID_TOKEN_STORAGE_KEY) ? null : token;\n}\n\n/**\n * Forgets a browser token the API reported invalid, so later requests stop\n * sending it (the stale copy in the URL included) until a new token arrives\n * over `postMessage` or a new URL. Explicit server-side tokens are untouched.\n */\nexport function discardPreviewToken(token: string): void {\n const win = browserWindow();\n const normalized = normalizeToken(token);\n\n if (win === null || normalized === null) {\n return;\n }\n\n const isStored = normalizeToken(storageGet(TOKEN_STORAGE_KEY)) === normalized;\n\n if (!isStored && tokenFromUrl(win.location.href) !== normalized) {\n return;\n }\n\n if (isStored) {\n storageRemove(TOKEN_STORAGE_KEY);\n }\n\n storageSet(INVALID_TOKEN_STORAGE_KEY, normalized);\n}\n\nexport function storePreviewToken(token: string): void {\n const normalized = normalizeToken(token);\n\n if (normalized !== null) {\n storageSet(TOKEN_STORAGE_KEY, normalized);\n }\n}\n\nexport function clearPreviewToken(): void {\n storageRemove(TOKEN_STORAGE_KEY);\n storageRemove(URL_TOKEN_STORAGE_KEY);\n storageRemove(INVALID_TOKEN_STORAGE_KEY);\n setPreviewStatus(null);\n}\n\n/** Server-side helper: the preview token of an incoming request, or null. */\nexport function previewFromRequest(request: PreviewRequestLike | null | undefined): string | null {\n if (request === null || request === undefined) {\n return null;\n }\n\n if (typeof request === \"string\" || request instanceof URL) {\n return tokenFromUrl(String(request));\n }\n\n const queryValue = request.query?.[PREVIEW_QUERY_PARAM];\n const fromQuery = normalizeToken(Array.isArray(queryValue) ? queryValue[0] : queryValue);\n\n if (fromQuery !== null) {\n return fromQuery;\n }\n\n return typeof request.url === \"string\" ? tokenFromUrl(request.url) : null;\n}\n\nexport function getPreviewContent(): PreviewContent {\n const win = browserWindow() as (Window & ContentHost) | null;\n const content = win?.[CONTENT_GLOBAL_KEY];\n\n return content ? { page: content.page, entries: [...content.entries] } : { page: null, entries: [] };\n}\n\nexport function recordPreviewContent(\n item: ({ type: \"page\" } & PreviewPage) | ({ type: \"entry\" } & PreviewEntry)\n): void {\n const win = browserWindow() as (Window & ContentHost) | null;\n\n if (win === null) {\n return;\n }\n\n const content = win[CONTENT_GLOBAL_KEY] ?? { page: null, entries: [] };\n win[CONTENT_GLOBAL_KEY] = content;\n\n if (item.type === \"page\") {\n content.page = { id: item.id, slug: item.slug };\n } else if (!content.entries.some((entry) => entry.id === item.id && entry.collection === item.collection)) {\n content.entries.push({ id: item.id, collection: item.collection });\n }\n\n dispatch(PREVIEW_CONTENT_EVENT);\n}\n\nexport function resetPreviewContent(): void {\n const win = browserWindow() as (Window & ContentHost) | null;\n\n if (win !== null) {\n win[CONTENT_GLOBAL_KEY] = undefined;\n }\n}\n\n/**\n * Kept on `window` (like the shown content) so a separately bundled bridge, such\n * as the `<script>` build, sees what the site's own SDK copy recorded.\n */\nexport function getPreviewStatus(): PreviewStatus | null {\n const win = browserWindow() as (Window & Record<string, unknown>) | null;\n const status = win?.[STATUS_GLOBAL_KEY];\n\n return status === \"active\" || status === \"invalid\" ? status : null;\n}\n\nfunction setPreviewStatus(status: PreviewStatus | null): void {\n const win = browserWindow() as (Window & Record<string, unknown>) | null;\n\n if (win !== null) {\n win[STATUS_GLOBAL_KEY] = status ?? undefined;\n }\n}\n\nexport function notifyPreviewActive(): void {\n setPreviewStatus(\"active\");\n dispatch(PREVIEW_ACTIVE_EVENT);\n}\n\nexport function notifyPreviewInvalid(): void {\n setPreviewStatus(\"invalid\");\n dispatch(PREVIEW_INVALID_EVENT);\n}\n\nfunction dispatch(name: string): void {\n const win = browserWindow();\n\n if (win !== null && typeof win.dispatchEvent === \"function\") {\n win.dispatchEvent(new Event(name));\n }\n}\n", "// Generated by scripts/write-version.mjs from package.json. Do not edit.\nexport const SDK_VERSION = \"0.5.1\";\n", "export const PROTOCOL_VERSION = 1;\n\nexport type CraftyTargetType = \"block\" | \"entry\";\nexport type CraftyFieldRef = { type: CraftyTargetType; id: number; field: string };\n/** `hrefField` is the field with the link destination of the same element (same target). */\nexport type CraftyMarkedField = CraftyFieldRef & { label?: string; hrefField?: string; hrefLabel?: string };\nexport type CraftyShownPage = { id: number; slug: string };\nexport type CraftyShownEntry = { id: number; collection: string };\n\nexport type ReadyPayload = {\n sdkVersion: string;\n path: string;\n fields: CraftyMarkedField[];\n page: CraftyShownPage | null;\n entries: CraftyShownEntry[];\n};\n\ntype Version = typeof PROTOCOL_VERSION;\n\n/**\n * Keys forwarded to the admin (`crafty:key`, SDK >= 0.4.1): the admin never\n * sees keydowns while focus is inside the iframe, so Escape could not close\n * its sheets and dialogs. Older admins ignore the message.\n */\nexport type ForwardedKey = \"Escape\";\ntype EmptyPayload = Record<string, never>;\n\n/** iframe -> admin. `crafty:ready` is a snapshot that may be re-sent; the last one wins. */\nexport type OutboundMessage =\n | { v: Version; type: \"crafty:ready\"; payload: ReadyPayload }\n | { v: Version; type: \"crafty:select\"; payload: CraftyMarkedField }\n | { v: Version; type: \"crafty:navigate\"; payload: { path: string } }\n | { v: Version; type: \"crafty:preview-invalid\"; payload: EmptyPayload }\n | { v: Version; type: \"crafty:key\"; payload: { key: ForwardedKey } };\n\n/** admin -> iframe. */\nexport type InboundMessage =\n | { v: Version; type: \"crafty:token\"; payload: { token: string } }\n | { v: Version; type: \"crafty:refresh\"; payload: EmptyPayload }\n | { v: Version; type: \"crafty:highlight\"; payload: CraftyFieldRef }\n | { v: Version; type: \"crafty:preview-field\"; payload: CraftyFieldRef & { value: string } }\n | { v: Version; type: \"crafty:preview-reset\"; payload: CraftyFieldRef };\n\n/** Same limits as the Crafty admin and backend (content_drafts.field / label). */\nconst MAX_FIELD_LENGTH = 255;\nconst MAX_LABEL_LENGTH = 120;\nconst MAX_TOKEN_LENGTH = 4096;\nconst MAX_VALUE_LENGTH = 100_000;\nconst MAX_PATH_LENGTH = 2048;\nconst FIELD_PATTERN = /^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+|\\[\\d+\\])*$/;\nconst TOKEN_PATTERN = /^[\\x21-\\x7E]+$/;\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001F\\u007F]/;\nconst PATH_BASE = \"https://crafty.invalid\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isPositiveInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value > 0;\n}\n\nfunction parseFieldPath(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const trimmed = value.trim();\n\n return trimmed === \"\" || trimmed.length > MAX_FIELD_LENGTH || !FIELD_PATTERN.test(trimmed) ? null : trimmed;\n}\n\nfunction parseLabel(value: unknown): string {\n return typeof value === \"string\" ? value.trim().slice(0, MAX_LABEL_LENGTH).trim() : \"\";\n}\n\nexport function parseFieldRef(value: unknown): CraftyFieldRef | null {\n if (!isRecord(value)) {\n return null;\n }\n\n const { type, id } = value;\n const field = parseFieldPath(value.field);\n\n if ((type !== \"block\" && type !== \"entry\") || !isPositiveInteger(id) || field === null) {\n return null;\n }\n\n return { type, id, field };\n}\n\n/** An invalid `hrefField` is dropped; the text field stays selectable. */\nexport function parseMarkedField(value: unknown): CraftyMarkedField | null {\n const ref = parseFieldRef(value);\n\n if (ref === null || !isRecord(value)) {\n return null;\n }\n\n const marked: CraftyMarkedField = { ...ref };\n const label = parseLabel(value.label);\n const hrefField = parseFieldPath(value.hrefField);\n\n if (label !== \"\") {\n marked.label = label;\n }\n\n if (hrefField !== null) {\n marked.hrefField = hrefField;\n\n const hrefLabel = parseLabel(value.hrefLabel);\n\n if (hrefLabel !== \"\") {\n marked.hrefLabel = hrefLabel;\n }\n }\n\n return marked;\n}\n\nfunction isSameOriginPath(value: string): boolean {\n if (!value.startsWith(\"/\") || value.startsWith(\"//\") || value.startsWith(\"/\\\\\")) {\n return false;\n }\n\n try {\n const url = new URL(value, PATH_BASE);\n\n // Dot segments can still resolve to a protocol-relative path (\"/.//evil.example\").\n return url.origin === PATH_BASE && !url.pathname.startsWith(\"//\") && !url.pathname.startsWith(\"/\\\\\");\n } catch {\n return false;\n }\n}\n\nfunction parsePath(value: unknown): string | null {\n if (typeof value !== \"string\" || value.length > MAX_PATH_LENGTH || CONTROL_CHARACTERS.test(value)) {\n return null;\n }\n\n return isSameOriginPath(value) ? value : null;\n}\n\nfunction parseShownEntry(value: unknown): CraftyShownEntry | null {\n return isRecord(value) && isPositiveInteger(value.id) && typeof value.collection === \"string\"\n ? { id: value.id, collection: value.collection }\n : null;\n}\n\nfunction readEnvelope(data: unknown): { type: string; payload: Record<string, unknown> } | null {\n if (!isRecord(data) || data.v !== PROTOCOL_VERSION || typeof data.type !== \"string\") {\n return null;\n }\n\n const payload = data.payload === undefined ? {} : data.payload;\n\n return isRecord(payload) ? { type: data.type, payload } : null;\n}\n\nexport function parseInboundMessage(data: unknown): InboundMessage | null {\n const message = readEnvelope(data);\n\n if (message === null) {\n return null;\n }\n\n const { payload } = message;\n\n switch (message.type) {\n case \"crafty:token\": {\n const token = typeof payload.token === \"string\" ? payload.token.trim() : \"\";\n\n return token !== \"\" && token.length <= MAX_TOKEN_LENGTH && TOKEN_PATTERN.test(token)\n ? { v: PROTOCOL_VERSION, type: \"crafty:token\", payload: { token } }\n : null;\n }\n case \"crafty:refresh\":\n return { v: PROTOCOL_VERSION, type: \"crafty:refresh\", payload: {} };\n case \"crafty:highlight\": {\n const ref = parseFieldRef(payload);\n\n return ref ? { v: PROTOCOL_VERSION, type: \"crafty:highlight\", payload: ref } : null;\n }\n case \"crafty:preview-field\": {\n const ref = parseFieldRef(payload);\n const value = payload.value;\n\n return ref && typeof value === \"string\" && value.length <= MAX_VALUE_LENGTH\n ? { v: PROTOCOL_VERSION, type: \"crafty:preview-field\", payload: { ...ref, value } }\n : null;\n }\n case \"crafty:preview-reset\": {\n const ref = parseFieldRef(payload);\n\n return ref ? { v: PROTOCOL_VERSION, type: \"crafty:preview-reset\", payload: ref } : null;\n }\n default:\n return null;\n }\n}\n\nexport function parseOutboundMessage(data: unknown): OutboundMessage | null {\n const message = readEnvelope(data);\n\n if (message === null) {\n return null;\n }\n\n const { payload } = message;\n\n switch (message.type) {\n case \"crafty:ready\": {\n const path = parsePath(payload.path);\n const rawPage = payload.page;\n\n if (typeof payload.sdkVersion !== \"string\" || path === null || !Array.isArray(payload.fields) || !Array.isArray(payload.entries)) {\n return null;\n }\n\n return {\n v: PROTOCOL_VERSION,\n type: \"crafty:ready\",\n payload: {\n sdkVersion: payload.sdkVersion,\n path,\n fields: payload.fields\n .map((field: unknown) => parseMarkedField(field))\n .filter((field): field is CraftyMarkedField => field !== null),\n page:\n isRecord(rawPage) && isPositiveInteger(rawPage.id) && typeof rawPage.slug === \"string\"\n ? { id: rawPage.id, slug: rawPage.slug }\n : null,\n entries: payload.entries\n .map((entry: unknown) => parseShownEntry(entry))\n .filter((entry): entry is CraftyShownEntry => entry !== null)\n }\n };\n }\n case \"crafty:select\": {\n const field = parseMarkedField(payload);\n\n return field ? { v: PROTOCOL_VERSION, type: \"crafty:select\", payload: field } : null;\n }\n case \"crafty:navigate\": {\n const path = parsePath(payload.path);\n\n return path ? { v: PROTOCOL_VERSION, type: \"crafty:navigate\", payload: { path } } : null;\n }\n case \"crafty:preview-invalid\":\n return { v: PROTOCOL_VERSION, type: \"crafty:preview-invalid\", payload: {} };\n case \"crafty:key\":\n return payload.key === \"Escape\" ? { v: PROTOCOL_VERSION, type: \"crafty:key\", payload: { key: \"Escape\" } } : null;\n default:\n return null;\n }\n}\n", "import { parseMarkedField, type CraftyFieldRef, type CraftyMarkedField } from \"./protocol.js\";\n\nexport const MARKED_SELECTOR = \"[data-crafty-field]\";\n\nexport type MarkedElement = { element: Element; field: CraftyMarkedField };\n\nexport function readMarkedField(element: Element): CraftyMarkedField | null {\n const blockId = element.getAttribute(\"data-crafty-block\");\n const entryId = element.getAttribute(\"data-crafty-entry\");\n const rawId = blockId ?? entryId;\n\n if (rawId === null) {\n return null;\n }\n\n return parseMarkedField({\n type: blockId !== null ? \"block\" : \"entry\",\n id: rawId.trim() === \"\" ? Number.NaN : Number(rawId),\n field: element.getAttribute(\"data-crafty-field\") ?? \"\",\n label: element.getAttribute(\"data-crafty-label\"),\n hrefField: element.getAttribute(\"data-crafty-href-field\"),\n hrefLabel: element.getAttribute(\"data-crafty-href-label\")\n });\n}\n\nexport function refKey(ref: CraftyFieldRef): string {\n return `${ref.type}:${ref.id}:${ref.field}`;\n}\n\nexport function scanMarked(root: ParentNode): MarkedElement[] {\n const marked: MarkedElement[] = [];\n\n root.querySelectorAll(MARKED_SELECTOR).forEach((element) => {\n const field = readMarkedField(element);\n\n if (field !== null) {\n marked.push({ element, field });\n }\n });\n\n return marked;\n}\n\nexport function uniqueFields(marked: MarkedElement[]): CraftyMarkedField[] {\n const seen = new Set<string>();\n const fields: CraftyMarkedField[] = [];\n\n for (const { field } of marked) {\n const key = refKey(field);\n\n if (!seen.has(key)) {\n seen.add(key);\n fields.push(field);\n }\n }\n\n return fields;\n}\n", "import { MARKED_SELECTOR, readMarkedField, refKey } from \"./markers.js\";\nimport type { CraftyFieldRef } from \"./protocol.js\";\n\nexport type LivePreview = {\n set(ref: CraftyFieldRef, value: string): void;\n reset(ref: CraftyFieldRef): void;\n reapply(): void;\n resetAll(): void;\n readonly size: number;\n};\n\n/**\n * Plain-text live preview. Values are written with `textContent` (never HTML),\n * and each element's own original text is kept so a reset restores exactly what\n * the site rendered, even for elements rendered after the value was set.\n */\nexport function createLivePreview(root: ParentNode): LivePreview {\n const values = new Map<string, string>();\n const originals = new Map<Element, string>();\n\n const matching = (key: string): Element[] =>\n Array.from(root.querySelectorAll(MARKED_SELECTOR)).filter((element) => {\n const field = readMarkedField(element);\n\n return field !== null && refKey(field) === key;\n });\n\n const write = (element: Element, value: string): void => {\n if (!originals.has(element)) {\n originals.set(element, element.textContent ?? \"\");\n }\n\n if (element.textContent !== value) {\n element.textContent = value;\n }\n };\n\n const restore = (key: string | null): void => {\n for (const [element, original] of originals) {\n const field = readMarkedField(element);\n\n if (key === null || (field !== null && refKey(field) === key)) {\n if (element.textContent !== original) {\n element.textContent = original;\n }\n\n originals.delete(element);\n }\n }\n };\n\n return {\n set(ref, value) {\n const key = refKey(ref);\n values.set(key, value);\n matching(key).forEach((element) => write(element, value));\n },\n reset(ref) {\n const key = refKey(ref);\n values.delete(key);\n restore(key);\n },\n reapply() {\n for (const element of [...originals.keys()]) {\n if (!element.isConnected) {\n originals.delete(element);\n }\n }\n\n for (const [key, value] of values) {\n matching(key).forEach((element) => write(element, value));\n }\n },\n resetAll() {\n values.clear();\n restore(null);\n },\n get size() {\n return values.size;\n }\n };\n}\n", "/** Crafty admin panels: https://crafty.do and https://<tenant>.crafty.do. */\nexport const DEFAULT_ADMIN_ORIGINS: ReadonlyArray<string | RegExp> = [/^https:\\/\\/([a-z0-9-]+\\.)*crafty\\.do$/];\n\nfunction originOf(value: string): string | null {\n try {\n return new URL(value).origin;\n } catch {\n return null;\n }\n}\n\nexport function isAllowedAdminOrigin(origin: string, allowlist: ReadonlyArray<string | RegExp>): boolean {\n if (origin === \"\" || origin === \"null\") {\n return false;\n }\n\n return allowlist.some((allowed) => {\n if (typeof allowed === \"string\") {\n return originOf(allowed) === origin;\n }\n\n allowed.lastIndex = 0;\n\n return allowed.test(origin);\n });\n}\n\n/**\n * Origin of the embedding admin. `ancestorOrigins` (Chromium, WebKit) cannot be\n * spoofed by the framed page; Firefox falls back to the referrer the admin sent\n * when it set the iframe `src`.\n */\nexport function resolveParentOrigin(win: Window): string | null {\n const ancestors = win.location.ancestorOrigins as ArrayLike<string> | undefined;\n const first = ancestors && ancestors.length > 0 ? ancestors[0] : undefined;\n\n if (typeof first === \"string\" && first !== \"\") {\n return first;\n }\n\n const referrer = win.document.referrer;\n\n return referrer ? originOf(referrer) : null;\n}\n", "const STYLE_ELEMENT_ID = \"crafty-visual-editing-style\";\nconst ACCENT = \"#4f46e5\";\n\nexport const FLASH_CLASS = \"crafty-ve-flash\";\n\nconst STYLES = [\n \"[data-crafty-field]{cursor:pointer}\",\n `.crafty-ve-box{position:fixed;top:0;left:0;pointer-events:none;z-index:2147483647;box-sizing:border-box;border:2px solid ${ACCENT};border-radius:4px;background:rgba(79,70,229,.06)}`,\n \".crafty-ve-box[hidden]{display:none}\",\n `.crafty-ve-label{position:absolute;left:-2px;bottom:100%;margin-bottom:4px;padding:2px 8px;max-width:320px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border-radius:4px;background:${ACCENT};color:#fff;font:500 12px/1.5 system-ui,-apple-system,sans-serif}`,\n `.${FLASH_CLASS}{outline:2px dashed ${ACCENT} !important;outline-offset:2px !important}`\n].join(\"\\n\");\n\nexport type Overlay = {\n show(element: Element, label: string): void;\n hide(): void;\n /** Re-measures the highlighted element, e.g. after its content changed. */\n reposition(): void;\n flash(elements: Element[], durationMs: number): void;\n ensureAttached(): void;\n contains(node: Node | null): boolean;\n destroy(): void;\n};\n\nexport function createOverlay(doc: Document): Overlay {\n const win = doc.defaultView;\n const style = doc.createElement(\"style\");\n style.id = STYLE_ELEMENT_ID;\n style.textContent = STYLES;\n\n const box = doc.createElement(\"div\");\n box.setAttribute(\"data-crafty-overlay\", \"\");\n box.className = \"crafty-ve-box\";\n box.hidden = true;\n\n const label = doc.createElement(\"span\");\n label.className = \"crafty-ve-label\";\n box.appendChild(label);\n\n let target: Element | null = null;\n let flashed: Element[] = [];\n let flashTimer: number | undefined;\n const Observer = (win as (Window & { ResizeObserver?: typeof ResizeObserver }) | null)?.ResizeObserver;\n\n const place = (): void => {\n if (target === null) {\n return;\n }\n\n const rect = target.getBoundingClientRect();\n box.style.top = `${rect.top}px`;\n box.style.left = `${rect.left}px`;\n box.style.width = `${rect.width}px`;\n box.style.height = `${rect.height}px`;\n };\n\n const resizeObserver = typeof Observer === \"function\" ? new Observer(() => place()) : null;\n\n const track = (element: Element | null): void => {\n if (target === element) {\n return;\n }\n\n if (target !== null) {\n resizeObserver?.unobserve(target);\n }\n\n target = element;\n\n if (target !== null) {\n resizeObserver?.observe(target);\n }\n };\n\n const clearFlash = (): void => {\n flashed.forEach((element) => element.classList.remove(FLASH_CLASS));\n flashed = [];\n\n if (flashTimer !== undefined) {\n win?.clearTimeout(flashTimer);\n flashTimer = undefined;\n }\n };\n\n const ensureAttached = (): void => {\n if (!style.isConnected) {\n (doc.head ?? doc.documentElement).appendChild(style);\n }\n\n if (!box.isConnected) {\n (doc.body ?? doc.documentElement).appendChild(box);\n }\n };\n\n ensureAttached();\n win?.addEventListener(\"scroll\", place, { capture: true, passive: true });\n win?.addEventListener(\"resize\", place, { passive: true });\n\n return {\n show(element, text) {\n ensureAttached();\n track(element);\n\n if (label.textContent !== text) {\n label.textContent = text;\n }\n\n box.hidden = false;\n place();\n },\n hide() {\n track(null);\n box.hidden = true;\n },\n reposition() {\n place();\n },\n flash(elements, durationMs) {\n clearFlash();\n flashed = [...elements];\n flashed.forEach((element) => element.classList.add(FLASH_CLASS));\n flashTimer = win?.setTimeout(clearFlash, durationMs);\n },\n ensureAttached,\n contains(node) {\n return node !== null && (box === node || box.contains(node) || style === node || style.contains(node));\n },\n destroy() {\n clearFlash();\n win?.removeEventListener(\"scroll\", place, { capture: true });\n win?.removeEventListener(\"resize\", place);\n resizeObserver?.disconnect();\n box.remove();\n style.remove();\n target = null;\n }\n };\n}\n", "import type { CraftyClient } from \"../client.js\";\nimport {\n PREVIEW_ACTIVE_EVENT,\n PREVIEW_CONTENT_EVENT,\n PREVIEW_INVALID_EVENT,\n PREVIEW_QUERY_PARAM,\n getPreviewContent,\n getPreviewStatus,\n readPreviewToken,\n storePreviewToken\n} from \"../preview.js\";\nimport { SDK_VERSION } from \"../version.js\";\nimport { createLivePreview } from \"./live-preview.js\";\nimport { MARKED_SELECTOR, readMarkedField, refKey, scanMarked, uniqueFields, type MarkedElement } from \"./markers.js\";\nimport { DEFAULT_ADMIN_ORIGINS, isAllowedAdminOrigin, resolveParentOrigin } from \"./origin.js\";\nimport { createOverlay } from \"./overlay.js\";\nimport {\n PROTOCOL_VERSION,\n parseInboundMessage,\n type CraftyFieldRef,\n type CraftyMarkedField,\n type CraftyShownEntry,\n type CraftyShownPage,\n type InboundMessage,\n type OutboundMessage\n} from \"./protocol.js\";\n\nexport type VisualEditingOptions = {\n /** Allowed admin origins. Replaces the default (`https://*.crafty.do`). */\n adminOrigins?: ReadonlyArray<string | RegExp>;\n /** Re-fetch and re-render instead of a full reload when the admin asks for a refresh. */\n onRefresh?: () => void | Promise<void>;\n /** Page rendered by the server (SSR sites, where the browser did not fetch it). */\n page?: CraftyShownPage | null;\n /** Entries rendered by the server (SSR sites). */\n entries?: CraftyShownEntry[];\n /** How long touch devices highlight every editable after load. Default 1500 ms. */\n touchHighlightMs?: number;\n /**\n * Client used to confirm the preview token when no preview request has been\n * answered yet (one `pages.list({ per_page: 1 })` call). Without it the bridge\n * waits for the site's own first Crafty request to confirm the token.\n */\n client?: Pick<CraftyClient, \"pages\">;\n};\n\nexport type VisualEditingHandle = {\n readonly active: boolean;\n disable(): void;\n};\n\nconst SCROLL_STORAGE_KEY = \"crafty:scroll-y\";\nconst RESCAN_DELAY_MS = 50;\nconst DEFAULT_TOUCH_HIGHLIGHT_MS = 1500;\nconst WATCHED_ATTRIBUTES = [\n \"data-crafty-field\",\n \"data-crafty-block\",\n \"data-crafty-entry\",\n \"data-crafty-label\",\n \"data-crafty-href-field\",\n \"data-crafty-href-label\"\n];\n\nconst inactiveHandle: VisualEditingHandle = { active: false, disable: () => undefined };\nlet activeHandle: VisualEditingHandle | null = null;\n\n/**\n * Connects the page to the Crafty visual editor. No-op unless the page runs in\n * an iframe, carries a preview token, and its parent is an allowed admin origin.\n *\n * The default allowlist (`*.crafty.do`) also covers sites hosted by Crafty, so\n * the bridge stays inert (no overlay, no listeners, no messages) until the API\n * answers a preview request with `X-Crafty-Preview-Status: active`. On `invalid`\n * it only tells the admin `crafty:preview-invalid` and stays inert.\n */\nexport function enableVisualEditing(options: VisualEditingOptions = {}): VisualEditingHandle {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return inactiveHandle;\n }\n\n if (activeHandle !== null) {\n return activeHandle;\n }\n\n const win = window;\n\n if (win.parent === null || win.parent === win || readPreviewToken() === null) {\n return inactiveHandle;\n }\n\n const parentOrigin = resolveParentOrigin(win);\n\n if (parentOrigin === null || !isAllowedAdminOrigin(parentOrigin, options.adminOrigins ?? DEFAULT_ADMIN_ORIGINS)) {\n return inactiveHandle;\n }\n\n const status = getPreviewStatus();\n\n if (status === \"invalid\") {\n postPreviewInvalid(win, parentOrigin);\n\n return inactiveHandle;\n }\n\n activeHandle = status === \"active\" ? startBridge(win, parentOrigin, options) : awaitConfirmation(win, parentOrigin, options);\n\n return activeHandle;\n}\n\nfunction postPreviewInvalid(win: Window, parentOrigin: string): void {\n const message: OutboundMessage = { v: PROTOCOL_VERSION, type: \"crafty:preview-invalid\", payload: {} };\n win.parent.postMessage(message, parentOrigin);\n}\n\n/**\n * Pending handle: waits for the API to confirm the token before starting the\n * bridge, verifying it through `options.client` when one is given.\n */\nfunction awaitConfirmation(win: Window, parentOrigin: string, options: VisualEditingOptions): VisualEditingHandle {\n let bridge: VisualEditingHandle | null = null;\n let settled = false;\n\n const stopWaiting = (): void => {\n settled = true;\n win.removeEventListener(PREVIEW_ACTIVE_EVENT, onActive);\n win.removeEventListener(PREVIEW_INVALID_EVENT, onInvalid);\n };\n\n const release = (): void => {\n if (activeHandle === handle) {\n activeHandle = null;\n }\n };\n\n const onActive = (): void => {\n if (settled) {\n return;\n }\n\n stopWaiting();\n bridge = startBridge(win, parentOrigin, options, release);\n };\n\n const onInvalid = (): void => {\n if (settled) {\n return;\n }\n\n stopWaiting();\n release();\n postPreviewInvalid(win, parentOrigin);\n };\n\n const handle: VisualEditingHandle = {\n get active() {\n return bridge?.active ?? false;\n },\n disable() {\n stopWaiting();\n bridge?.disable();\n release();\n }\n };\n\n win.addEventListener(PREVIEW_ACTIVE_EVENT, onActive);\n win.addEventListener(PREVIEW_INVALID_EVENT, onInvalid);\n\n // The status handlers above settle the outcome; request errors leave the bridge waiting.\n options.client?.pages.list({ per_page: 1 }).catch(() => undefined);\n\n return handle;\n}\n\nfunction startBridge(\n win: Window,\n parentOrigin: string,\n options: VisualEditingOptions,\n onDisable?: () => void\n): VisualEditingHandle {\n const doc = win.document;\n const overlay = createOverlay(doc);\n const livePreview = createLivePreview(doc);\n const pendingScrollY = takeStoredScroll(win);\n\n let marked: MarkedElement[] = [];\n let sentSignature: string | null = null;\n let rescanTimer: number | undefined;\n let forceReady = false;\n let active = true;\n\n const post = (message: OutboundMessage): void => {\n win.parent.postMessage(message, parentOrigin);\n };\n\n const sendReady = (): void => {\n const fields = uniqueFields(marked);\n const content = getPreviewContent();\n sentSignature = signatureOf(fields);\n\n post({\n v: PROTOCOL_VERSION,\n type: \"crafty:ready\",\n payload: {\n sdkVersion: SDK_VERSION,\n path: currentPath(win),\n fields,\n page: content.page ?? options.page ?? null,\n entries: mergeEntries(content.entries, options.entries ?? [])\n }\n });\n };\n\n const rescan = (): void => {\n rescanTimer = undefined;\n\n if (!active) {\n return;\n }\n\n overlay.ensureAttached();\n marked = scanMarked(doc);\n livePreview.reapply();\n\n if (forceReady || signatureOf(uniqueFields(marked)) !== sentSignature) {\n forceReady = false;\n sendReady();\n }\n };\n\n const scheduleRescan = (): void => {\n if (active && rescanTimer === undefined) {\n rescanTimer = win.setTimeout(rescan, RESCAN_DELAY_MS);\n }\n };\n\n const observer = new MutationObserver((records) => {\n if (records.some((record) => !overlay.contains(record.target))) {\n scheduleRescan();\n }\n });\n\n const labelOf = (field: CraftyMarkedField): string => field.label ?? field.field;\n\n const onPointerOver = (event: PointerEvent): void => {\n if (event.pointerType === \"touch\") {\n return;\n }\n\n const hit = hitFrom(event.target);\n\n if (hit !== null) {\n overlay.show(hit.element, labelOf(hit.field));\n } else {\n overlay.hide();\n }\n };\n\n const block = (event: Event): void => {\n event.preventDefault();\n event.stopPropagation();\n };\n\n /**\n * Runs in the capture phase on `window`, before any site listener, so a marked\n * element always selects even when it is (or sits inside) a link or button,\n * and nothing the site renders can take the iframe out of the editor.\n */\n const onClick = (event: MouseEvent): void => {\n const hit = hitFrom(event.target);\n\n if (hit !== null) {\n block(event);\n overlay.show(hit.element, labelOf(hit.field));\n post({ v: PROTOCOL_VERSION, type: \"crafty:select\", payload: hit.field });\n\n return;\n }\n\n const action = linkAction(event, win);\n\n if (action.kind === \"allow\") {\n return;\n }\n\n block(event);\n\n if (action.kind === \"navigate\") {\n post({ v: PROTOCOL_VERSION, type: \"crafty:navigate\", payload: { path: action.path } });\n }\n };\n\n /** Middle clicks open links in a new tab: never let them leave the editor. */\n const onAuxClick = (event: MouseEvent): void => {\n if (hitFrom(event.target) !== null || closestLink(event.target) !== null) {\n block(event);\n }\n };\n\n const onSubmit = (event: Event): void => {\n block(event);\n };\n\n /**\n * Escape pressed while focus is inside the iframe never reaches the admin\n * window: forward it so the admin closes its topmost sheet or dialog. Runs in\n * the bubble phase, after the site, and skips an Escape the site handled\n * (`preventDefault`, e.g. to close its own menu).\n */\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.repeat || event.isComposing || event.defaultPrevented) {\n return;\n }\n\n post({ v: PROTOCOL_VERSION, type: \"crafty:key\", payload: { key: \"Escape\" } });\n };\n\n const highlight = (ref: CraftyFieldRef): void => {\n const key = refKey(ref);\n const match = scanMarked(doc).find((item) => refKey(item.field) === key);\n\n if (match === undefined) {\n return;\n }\n\n const element = match.element as Element & { scrollIntoView?: (options?: ScrollIntoViewOptions) => void };\n element.scrollIntoView?.({ block: \"center\", behavior: \"smooth\" });\n overlay.show(match.element, labelOf(match.field));\n };\n\n const refresh = async (): Promise<void> => {\n if (options.onRefresh) {\n try {\n await options.onRefresh();\n } finally {\n scheduleRescan();\n }\n\n return;\n }\n\n try {\n win.sessionStorage.setItem(SCROLL_STORAGE_KEY, String(win.scrollY));\n } catch {\n // Storage blocked: reload without restoring the scroll position.\n }\n\n win.location.reload();\n };\n\n const handleInbound = (message: InboundMessage): void => {\n switch (message.type) {\n case \"crafty:token\":\n storePreviewToken(message.payload.token);\n return;\n case \"crafty:refresh\":\n refresh().catch((error: unknown) => console.error(\"[crafty] onRefresh failed\", error));\n return;\n case \"crafty:highlight\":\n highlight(message.payload);\n return;\n case \"crafty:preview-field\":\n livePreview.set(message.payload, message.payload.value);\n overlay.reposition();\n return;\n case \"crafty:preview-reset\":\n livePreview.reset(message.payload);\n overlay.reposition();\n return;\n }\n };\n\n const onMessage = (event: MessageEvent): void => {\n if (event.source !== win.parent || event.origin !== parentOrigin) {\n return;\n }\n\n const message = parseInboundMessage(event.data);\n\n if (message !== null) {\n handleInbound(message);\n }\n };\n\n const onPreviewInvalid = (): void => {\n post({ v: PROTOCOL_VERSION, type: \"crafty:preview-invalid\", payload: {} });\n };\n\n const onPreviewContent = (): void => {\n forceReady = true;\n scheduleRescan();\n };\n\n const start = (): void => {\n if (!active) {\n return;\n }\n\n marked = scanMarked(doc);\n sendReady();\n\n if (isTouchDevice(win)) {\n overlay.flash(\n marked.map((item) => item.element),\n options.touchHighlightMs ?? DEFAULT_TOUCH_HIGHLIGHT_MS\n );\n }\n\n restoreScroll(win, pendingScrollY);\n };\n\n win.addEventListener(\"message\", onMessage);\n win.addEventListener(\"click\", onClick, true);\n win.addEventListener(\"auxclick\", onAuxClick, true);\n win.addEventListener(\"submit\", onSubmit, true);\n win.addEventListener(\"keydown\", onKeyDown);\n doc.addEventListener(\"pointerover\", onPointerOver, true);\n win.addEventListener(PREVIEW_INVALID_EVENT, onPreviewInvalid);\n win.addEventListener(PREVIEW_CONTENT_EVENT, onPreviewContent);\n observer.observe(doc.documentElement, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: WATCHED_ATTRIBUTES\n });\n\n if (doc.readyState === \"loading\") {\n doc.addEventListener(\"DOMContentLoaded\", start, { once: true });\n } else {\n start();\n }\n\n const handle: VisualEditingHandle = {\n get active() {\n return active;\n },\n disable() {\n if (!active) {\n return;\n }\n\n active = false;\n win.removeEventListener(\"message\", onMessage);\n win.removeEventListener(\"click\", onClick, true);\n win.removeEventListener(\"auxclick\", onAuxClick, true);\n win.removeEventListener(\"submit\", onSubmit, true);\n win.removeEventListener(\"keydown\", onKeyDown);\n doc.removeEventListener(\"pointerover\", onPointerOver, true);\n doc.removeEventListener(\"DOMContentLoaded\", start);\n win.removeEventListener(PREVIEW_INVALID_EVENT, onPreviewInvalid);\n win.removeEventListener(PREVIEW_CONTENT_EVENT, onPreviewContent);\n observer.disconnect();\n\n if (rescanTimer !== undefined) {\n win.clearTimeout(rescanTimer);\n rescanTimer = undefined;\n }\n\n livePreview.resetAll();\n overlay.destroy();\n\n if (activeHandle === handle) {\n activeHandle = null;\n }\n\n onDisable?.();\n }\n };\n\n return handle;\n}\n\nfunction asElement(target: EventTarget | null): Element | null {\n return target !== null && typeof (target as Element).closest === \"function\" ? (target as Element) : null;\n}\n\nfunction signatureOf(fields: CraftyMarkedField[]): string {\n return fields.map((field) => `${refKey(field)}|${field.label ?? \"\"}|${field.hrefField ?? \"\"}|${field.hrefLabel ?? \"\"}`).join(\"\\n\");\n}\n\nfunction mergeEntries(fetched: CraftyShownEntry[], declared: CraftyShownEntry[]): CraftyShownEntry[] {\n const seen = new Set<string>();\n\n return [...fetched, ...declared].filter((entry) => {\n const key = `${entry.collection}:${entry.id}`;\n\n if (seen.has(key)) {\n return false;\n }\n\n seen.add(key);\n\n return true;\n });\n}\n\nfunction stripPreviewParam(url: URL): string {\n url.searchParams.delete(PREVIEW_QUERY_PARAM);\n\n return `${url.pathname}${url.search}`;\n}\n\nfunction currentPath(win: Window): string {\n return stripPreviewParam(new URL(win.location.href));\n}\n\ntype LinkAction = { kind: \"allow\" } | { kind: \"block\" } | { kind: \"navigate\"; path: string };\n\n/**\n * Only links fall back to their marked descendant: following them would leave\n * the editor. Buttons, `<summary>` and labels keep their own behavior (menus,\n * accordions, tabs) when the click misses the marked element.\n */\nconst LINK_SELECTOR = \"a[href], area[href]\";\n\n/**\n * The marked element a pointer or click target maps to: the innermost valid\n * marked ancestor (or the target itself), else the first marked element inside\n * the link that was clicked, so clicking a link button's padding or icon\n * selects its label.\n */\nfunction hitFrom(target: EventTarget | null): MarkedElement | null {\n const element = asElement(target);\n\n if (element === null) {\n return null;\n }\n\n for (let node = element.closest(MARKED_SELECTOR); node !== null; node = node.parentElement?.closest(MARKED_SELECTOR) ?? null) {\n const field = readMarkedField(node);\n\n if (field !== null) {\n return { element: node, field };\n }\n }\n\n const link = element.closest(LINK_SELECTOR);\n\n return link !== null ? (scanMarked(link)[0] ?? null) : null;\n}\n\nfunction closestLink(target: EventTarget | null): Element | null {\n return asElement(target)?.closest(LINK_SELECTOR) ?? null;\n}\n\n/**\n * What to do with a click that hit no marked element. Only same-page anchors\n * run as usual; same-origin links become `crafty:navigate`; anything that\n * would leave the editor (other origins, `mailto:`/`tel:`, new tabs,\n * downloads, modified clicks) is blocked.\n */\nfunction linkAction(event: MouseEvent, win: Window): LinkAction {\n const anchor = closestLink(event.target);\n\n if (anchor === null) {\n return { kind: \"allow\" };\n }\n\n if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || anchor.hasAttribute(\"download\")) {\n return { kind: \"block\" };\n }\n\n const target = anchor.getAttribute(\"target\");\n\n if (target !== null && target !== \"\" && target !== \"_self\") {\n return { kind: \"block\" };\n }\n\n const href = anchor.getAttribute(\"href\") ?? \"\";\n let url: URL;\n\n try {\n url = new URL(href, win.location.href);\n } catch {\n return { kind: \"block\" };\n }\n\n if (url.origin !== win.location.origin || (url.protocol !== \"http:\" && url.protocol !== \"https:\")) {\n return { kind: \"block\" };\n }\n\n const path = stripPreviewParam(url);\n\n if ((url.hash !== \"\" || href.startsWith(\"#\")) && path === currentPath(win)) {\n return { kind: \"allow\" };\n }\n\n return { kind: \"navigate\", path };\n}\n\nfunction isTouchDevice(win: Window): boolean {\n return typeof win.matchMedia === \"function\" && win.matchMedia(\"(hover: none)\").matches;\n}\n\nfunction takeStoredScroll(win: Window): number | null {\n try {\n const raw = win.sessionStorage.getItem(SCROLL_STORAGE_KEY);\n win.sessionStorage.removeItem(SCROLL_STORAGE_KEY);\n const scrollY = raw === null ? Number.NaN : Number(raw);\n\n return Number.isFinite(scrollY) ? scrollY : null;\n } catch {\n return null;\n }\n}\n\nfunction restoreScroll(win: Window, scrollY: number | null): void {\n if (scrollY === null) {\n return;\n }\n\n const apply = (): void => win.scrollTo(0, scrollY);\n\n if (win.document.readyState === \"complete\") {\n apply();\n } else {\n win.addEventListener(\"load\", apply, { once: true });\n }\n}\n"],
|
|
5
5
|
"mappings": "idAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,sBAAAE,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,IAAM,OAAOA,CAAG,EAEtD,OAAO,OAAO,SAASC,CAAO,EAAIA,EAAU,IAC9C,MAAQ,CACN,OAAO,IACT,CACF,CAEA,SAASpB,GAAcnF,EAAauG,EAA8B,CAChE,GAAIA,IAAY,KACd,OAGF,IAAMC,EAAQ,IAAYxG,EAAI,SAAS,EAAGuG,CAAO,EAE7CvG,EAAI,SAAS,aAAe,WAC9BwG,EAAM,EAENxG,EAAI,iBAAiB,OAAQwG,EAAO,CAAE,KAAM,EAAK,CAAC,CAEtD",
|
|
6
6
|
"names": ["cdn_exports", "__export", "PROTOCOL_VERSION", "attrs", "attrsHtml", "enableVisualEditing", "resolveEditTarget", "target", "record", "id", "attrs", "field", "options", "resolved", "normalizedField", "attributes", "label", "hrefField", "hrefLabel", "attrsHtml", "name", "value", "escapeAttribute", "PREVIEW_QUERY_PARAM", "PREVIEW_INVALID_EVENT", "PREVIEW_CONTENT_EVENT", "PREVIEW_ACTIVE_EVENT", "TOKEN_STORAGE_KEY", "URL_TOKEN_STORAGE_KEY", "INVALID_TOKEN_STORAGE_KEY", "CONTENT_GLOBAL_KEY", "STATUS_GLOBAL_KEY", "browserWindow", "storageGet", "key", "_a", "_b", "storageSet", "value", "normalizeToken", "value", "tokenFromUrl", "url", "PREVIEW_QUERY_PARAM", "readPreviewToken", "_a", "win", "browserWindow", "urlToken", "token", "storageGet", "URL_TOKEN_STORAGE_KEY", "storageSet", "TOKEN_STORAGE_KEY", "INVALID_TOKEN_STORAGE_KEY", "storePreviewToken", "token", "normalized", "normalizeToken", "storageSet", "TOKEN_STORAGE_KEY", "getPreviewContent", "win", "browserWindow", "content", "CONTENT_GLOBAL_KEY", "getPreviewStatus", "win", "browserWindow", "status", "STATUS_GLOBAL_KEY", "SDK_VERSION", "PROTOCOL_VERSION", "FIELD_PATTERN", "TOKEN_PATTERN", "isRecord", "value", "isPositiveInteger", "parseFieldPath", "trimmed", "FIELD_PATTERN", "parseLabel", "parseFieldRef", "type", "id", "field", "parseMarkedField", "ref", "marked", "label", "hrefField", "hrefLabel", "readEnvelope", "data", "isRecord", "payload", "parseInboundMessage", "message", "token", "TOKEN_PATTERN", "ref", "parseFieldRef", "value", "MARKED_SELECTOR", "readMarkedField", "element", "_a", "blockId", "entryId", "rawId", "parseMarkedField", "refKey", "ref", "scanMarked", "root", "marked", "field", "uniqueFields", "seen", "fields", "key", "createLivePreview", "root", "values", "originals", "matching", "key", "MARKED_SELECTOR", "element", "field", "readMarkedField", "refKey", "write", "value", "_a", "restore", "original", "ref", "DEFAULT_ADMIN_ORIGINS", "originOf", "value", "isAllowedAdminOrigin", "origin", "allowlist", "allowed", "resolveParentOrigin", "win", "ancestors", "first", "referrer", "STYLE_ELEMENT_ID", "ACCENT", "FLASH_CLASS", "STYLES", "createOverlay", "doc", "win", "style", "box", "label", "target", "flashed", "flashTimer", "Observer", "place", "rect", "resizeObserver", "track", "element", "clearFlash", "ensureAttached", "_a", "_b", "text", "elements", "durationMs", "node", "SCROLL_STORAGE_KEY", "RESCAN_DELAY_MS", "DEFAULT_TOUCH_HIGHLIGHT_MS", "WATCHED_ATTRIBUTES", "inactiveHandle", "activeHandle", "enableVisualEditing", "options", "_a", "win", "readPreviewToken", "parentOrigin", "resolveParentOrigin", "isAllowedAdminOrigin", "DEFAULT_ADMIN_ORIGINS", "status", "getPreviewStatus", "postPreviewInvalid", "startBridge", "awaitConfirmation", "message", "bridge", "settled", "stopWaiting", "PREVIEW_ACTIVE_EVENT", "onActive", "PREVIEW_INVALID_EVENT", "onInvalid", "release", "handle", "onDisable", "doc", "overlay", "createOverlay", "livePreview", "createLivePreview", "pendingScrollY", "takeStoredScroll", "marked", "sentSignature", "rescanTimer", "forceReady", "active", "post", "sendReady", "_b", "_c", "fields", "uniqueFields", "content", "getPreviewContent", "signatureOf", "SDK_VERSION", "currentPath", "mergeEntries", "rescan", "scanMarked", "scheduleRescan", "observer", "records", "record", "labelOf", "field", "onPointerOver", "event", "hit", "hitFrom", "block", "onClick", "action", "linkAction", "onAuxClick", "closestLink", "onSubmit", "onKeyDown", "highlight", "ref", "key", "refKey", "match", "item", "element", "refresh", "handleInbound", "storePreviewToken", "error", "onMessage", "parseInboundMessage", "onPreviewInvalid", "onPreviewContent", "start", "isTouchDevice", "restoreScroll", "PREVIEW_CONTENT_EVENT", "asElement", "target", "fetched", "declared", "seen", "entry", "stripPreviewParam", "url", "PREVIEW_QUERY_PARAM", "LINK_SELECTOR", "node", "MARKED_SELECTOR", "readMarkedField", "link", "anchor", "href", "path", "raw", "scrollY", "apply"]
|
|
7
7
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export { attrs, attrsHtml } from "./attrs.js";
|
|
|
6
6
|
export type { CraftyAttrsOptions, CraftyEditAttributes, CraftyEditTarget, CraftyEditTargetType } from "./attrs.js";
|
|
7
7
|
export { PREVIEW_HEADER, PREVIEW_INVALID_EVENT, PREVIEW_QUERY_PARAM, PREVIEW_STATUS_HEADER, clearPreviewToken, previewFromRequest, readPreviewToken, storePreviewToken } from "./preview.js";
|
|
8
8
|
export type { PreviewContent, PreviewEntry, PreviewPage, PreviewRequestLike } from "./preview.js";
|
|
9
|
+
export type { LlmsHandlerOptions, LlmsLinkTag } from "./resources/llms.js";
|
|
9
10
|
export type * from "./types/public.js";
|
|
10
11
|
export type * from "./types/blocks.js";
|
|
11
12
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,YAAY,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAA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.js";
|
|
2
|
+
import type { RequestOptions } from "../types/public.js";
|
|
3
|
+
export type LlmsHandlerOptions = {
|
|
4
|
+
full?: boolean;
|
|
5
|
+
maxAge?: number;
|
|
6
|
+
};
|
|
7
|
+
export type LlmsLinkTag = {
|
|
8
|
+
rel: "alternate";
|
|
9
|
+
type: "text/markdown";
|
|
10
|
+
href: string;
|
|
11
|
+
title: string;
|
|
12
|
+
};
|
|
13
|
+
export declare class LlmsResource {
|
|
14
|
+
private readonly http;
|
|
15
|
+
constructor(http: HttpClient);
|
|
16
|
+
index(options?: RequestOptions): Promise<string>;
|
|
17
|
+
full(options?: RequestOptions): Promise<string>;
|
|
18
|
+
/** Route handler that serves the file from your own domain (Next, Astro, Nuxt/h3, Workers). */
|
|
19
|
+
handler(opts?: LlmsHandlerOptions): () => Promise<Response>;
|
|
20
|
+
linkTagAttrs(opts?: {
|
|
21
|
+
full?: boolean;
|
|
22
|
+
}): LlmsLinkTag[];
|
|
23
|
+
linkTags(opts?: {
|
|
24
|
+
full?: boolean;
|
|
25
|
+
}): string;
|
|
26
|
+
private fetchText;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=llms.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llms.d.ts","sourceRoot":"","sources":["../../src/resources/llms.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEzD,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IACxB,GAAG,EAAE,WAAW,CAAC;IACjB,IAAI,EAAE,eAAe,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAKF,qBAAa,YAAY;IACJ,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAAJ,IAAI,EAAE,UAAU;IAE7C,KAAK,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAIhD,IAAI,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAItD,+FAA+F;IACxF,OAAO,CAAC,IAAI,GAAE,kBAAuB,GAAG,MAAM,OAAO,CAAC,QAAQ,CAAC;IAc/D,YAAY,CAAC,IAAI,GAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,WAAW,EAAE;IAU1D,QAAQ,CAAC,IAAI,GAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,MAAM;YAMxC,SAAS;CAexB"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { CraftyError } from "../errors.js";
|
|
2
|
+
const INDEX_PATH = "/llms.txt";
|
|
3
|
+
const FULL_PATH = "/llms-full.txt";
|
|
4
|
+
export class LlmsResource {
|
|
5
|
+
http;
|
|
6
|
+
constructor(http) {
|
|
7
|
+
this.http = http;
|
|
8
|
+
}
|
|
9
|
+
index(options) {
|
|
10
|
+
return this.fetchText(INDEX_PATH, options);
|
|
11
|
+
}
|
|
12
|
+
full(options) {
|
|
13
|
+
return this.fetchText(FULL_PATH, options);
|
|
14
|
+
}
|
|
15
|
+
/** Route handler that serves the file from your own domain (Next, Astro, Nuxt/h3, Workers). */
|
|
16
|
+
handler(opts = {}) {
|
|
17
|
+
return async () => {
|
|
18
|
+
const body = opts.full ? await this.full() : await this.index();
|
|
19
|
+
return new Response(body, {
|
|
20
|
+
status: 200,
|
|
21
|
+
headers: {
|
|
22
|
+
"content-type": "text/markdown; charset=utf-8",
|
|
23
|
+
"cache-control": `public, max-age=${opts.maxAge ?? 300}`
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
linkTagAttrs(opts = {}) {
|
|
29
|
+
const tags = [{ rel: "alternate", type: "text/markdown", href: INDEX_PATH, title: "llms.txt" }];
|
|
30
|
+
if (opts.full) {
|
|
31
|
+
tags.push({ rel: "alternate", type: "text/markdown", href: FULL_PATH, title: "llms-full.txt" });
|
|
32
|
+
}
|
|
33
|
+
return tags;
|
|
34
|
+
}
|
|
35
|
+
linkTags(opts = {}) {
|
|
36
|
+
return this.linkTagAttrs(opts)
|
|
37
|
+
.map((tag) => `<link rel="${tag.rel}" type="${tag.type}" href="${tag.href}" title="${tag.title}">`)
|
|
38
|
+
.join("\n");
|
|
39
|
+
}
|
|
40
|
+
async fetchText(path, options) {
|
|
41
|
+
const headers = new Headers(options?.headers);
|
|
42
|
+
headers.set("Accept", "text/markdown");
|
|
43
|
+
const body = await this.http.get(path, { ...options, headers });
|
|
44
|
+
if (typeof body !== "string") {
|
|
45
|
+
throw new CraftyError({
|
|
46
|
+
code: "SERVER_ERROR",
|
|
47
|
+
message: `Expected a text/markdown body from ${path}.`,
|
|
48
|
+
details: body
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return body;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=llms.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llms.js","sourceRoot":"","sources":["../../src/resources/llms.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAgB3C,MAAM,UAAU,GAAG,WAAW,CAAC;AAC/B,MAAM,SAAS,GAAG,gBAAgB,CAAC;AAEnC,MAAM,OAAO,YAAY;IACa;IAApC,YAAoC,IAAgB;QAAhB,SAAI,GAAJ,IAAI,CAAY;IAAG,CAAC;IAEjD,KAAK,CAAC,OAAwB;QACnC,OAAO,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC;IAEM,IAAI,CAAC,OAAwB;QAClC,OAAO,IAAI,CAAC,S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C,IAAY,EAAE,OAAwB;QAC5D,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,eAAe,CAAC,CAAC;QACvC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAU,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;QAEzE,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,MAAM,IAAI,WAAW,CAAC;gBACpB,IAAI,EAAE,cAAc;gBACpB,OAAO,EAAE,sCAAsC,IAAI,GAAG;gBACtD,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;QACL,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF"}
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const SDK_VERSION = "0.
|
|
1
|
+
export declare const SDK_VERSION = "0.5.1";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
package/dist/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: crafty-cms
|
|
3
|
-
description: "Build on Crafty CMS — configure sites, pages, blocks, collections, entries, forms, and media through the Crafty MCP server, then develop a frontend with the @craftware/crafty-sdk JavaScript SDK. Use when connecting an agent to a Crafty MCP server; calling Crafty MCP tools like list_sites, create_page, publish_form, or
|
|
3
|
+
description: "Build on Crafty CMS — configure sites, pages, blocks, collections, entries, forms, and media through the Crafty MCP server, then develop a frontend with the @craftware/crafty-sdk JavaScript SDK. Use when connecting an agent to a Crafty MCP server; calling Crafty MCP tools like list_sites, create_page, create_block_type, publish_form, upload_media, or request_media_upload; modelling site content with block types (repeater and stringList fields); installing or importing @craftware/crafty-sdk or createCraftyClient; fetching Crafty pages, entries, collections, or media; rendering page blocks; submitting Crafty forms; or preparing a site for the Crafty visual editor (crafty.attrs, enableVisualEditing, preview tokens, configure_visual_editor)."
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
author: craftware
|
|
@@ -33,21 +33,36 @@ The normal flow is **configure with the MCP server → build a frontend with the
|
|
|
33
33
|
|
|
34
34
|
- **Site** — top-level tenant resource. Everything else belongs to a site.
|
|
35
35
|
- **Page** — a web page in a site; `draft` or `published`; composed of ordered **Blocks**.
|
|
36
|
-
- **Block** — a content unit on a page; its **BlockType** defines the data schema.
|
|
36
|
+
- **Block** — a content unit on a page; its **BlockType** defines the data schema. Block types can be created and edited over MCP (`create_block_type`, `update_block_type`).
|
|
37
37
|
- **Collection** — a structured content schema (e.g. "Blog Posts"); defines the fields **Entries** must have.
|
|
38
38
|
- **Entry** — one record in a collection (e.g. a single post). Belongs to a site and a collection.
|
|
39
39
|
- **Form** — a contact/feedback form in a site; `draft` or `published`. Published forms accept **public** submissions without auth.
|
|
40
40
|
- **Form Submission** — visitor-submitted data; read-only after creation.
|
|
41
41
|
- **Media** — files attached to a site via the Spatie Media Library.
|
|
42
42
|
|
|
43
|
+
## Model content with block types first
|
|
44
|
+
|
|
45
|
+
**Default to block types + pages for everything on a site**: hero, stats, about, services, sectors, partners, contact, footer, and any list of items inside a section. Only reach for a collection when block types genuinely do not fit (see the exceptions below).
|
|
46
|
+
|
|
47
|
+
Why: page blocks are validated against their schema on write, show up in the visual editor with proper inputs (no raw JSON), are rendered into `llms-full.txt`, and travel with the page when it is published.
|
|
48
|
+
|
|
49
|
+
How to model it:
|
|
50
|
+
|
|
51
|
+
- **One block type per section** (`hero`, `stats`, `solutions`, `footer`, …); the block type `slug` is what `page.block("hero")` / `page.blocksOf("solutions")` look up in the SDK.
|
|
52
|
+
- **Lists of items → a `repeater` field**, not a `json` field and not a collection: `items: repeater { icon, title, text, tags: stringList }`. One level only (a repeater cannot contain another repeater), subfield types: `string`, `text`, `longText`, `url`, `number`, `boolean`, `reference`, `stringList`. Optional `min` / `max` item limits.
|
|
53
|
+
- **List of plain strings → `stringList`** (`["AI", "Cloud"]`).
|
|
54
|
+
- **Shared data** (address, phone, social links, footer text used in several places): block types have no global blocks. Put it in a dedicated page (e.g. slug `site-settings`) with one `site-settings` block and read it with `crafty.pages.get("site-settings")`.
|
|
55
|
+
- **Languages**: pages have no locale or translation link. Use one page per language with different slugs (`home`, `home-en`) and pick the slug in your router.
|
|
56
|
+
- There is no `json` field type in block types. If you catch yourself wanting one, model it as a repeater or `stringList`.
|
|
57
|
+
|
|
58
|
+
Use a **collection** only when the content is a large set of independent records that you list, filter, sort or paginate through the API (`entries.list`) — for example blog posts or a product catalogue — or when many different pages reference the same record. A handful of cards, team members or FAQs inside a page is a repeater, not a collection.
|
|
59
|
+
|
|
43
60
|
## Phase 1 — Configure content via the MCP server
|
|
44
61
|
|
|
45
62
|
Connect once, then drive the tools. Minimal connect with a Personal Access Token (Claude Code shown):
|
|
46
63
|
|
|
47
64
|
```bash
|
|
48
|
-
claude mcp add crafty \
|
|
49
|
-
--transport http \
|
|
50
|
-
--url https://<your-tenant-domain>/mcp \
|
|
65
|
+
claude mcp add --transport http crafty https://<your-tenant-domain>/mcp \
|
|
51
66
|
--header "Authorization: Bearer YOUR_PERSONAL_ACCESS_TOKEN"
|
|
52
67
|
```
|
|
53
68
|
|
|
@@ -56,17 +71,19 @@ The server URL is **per-tenant**: `https://<your-tenant-domain>/mcp`. Tokens car
|
|
|
56
71
|
Canonical authoring workflow (exact tool names):
|
|
57
72
|
|
|
58
73
|
1. `list_sites` → pick a `site_id` (or `create_site`).
|
|
59
|
-
2. `list_block_types` → learn the available block types
|
|
60
|
-
3. `create_page` with `site_id`, `title`, and optional `blocks: [{ block_type_id, data }]`.
|
|
74
|
+
2. `list_block_types` → learn the available block types (it lists every site's types; use `get_block_type` with `site_id` for one site's full schema). Missing one? `create_block_type` (`site_id`, `name`, `fields`).
|
|
75
|
+
3. `create_page` with `site_id`, `title`, and optional `blocks: [{ block_type_id, data }]`. Block `data` is validated against the block type schema; undeclared keys are dropped and reported in a `warnings` array in the response.
|
|
61
76
|
4. `publish_page`.
|
|
62
77
|
|
|
78
|
+
Block types: `get_block_type` (`site_id` + `block_type_id` or `slug`) → `create_block_type` → `update_block_type` (`fields` replaces ALL fields; removing or retyping a field that blocks already fill needs `force: true`, and existing block data is never rewritten) → `delete_block_type` (`confirm: true`, refused while blocks use it).
|
|
79
|
+
|
|
63
80
|
Collections/entries: `list_collections` → `create_entry` (`collection_slug`, `site_id`, `slug`, `data`) → `update_entry` (snapshots a revision).
|
|
64
81
|
Forms: `create_form` (`site_id`, `name`, `slug`, `fields`) → `publish_form` → `list_form_submissions`.
|
|
65
|
-
Media: `upload_media` (`url`, `site_id`, optional `collection_name`).
|
|
82
|
+
Media: `upload_media` (`url`, `site_id`, optional `collection_name`, `sha256`) takes an http(s) URL or a small base64 data URI (256 KB decoded). For a **local binary file** call `request_media_upload` (`site_id`, `file_name`, `sha256`, optional `collection_name`) and run the returned `curl -T` command from your shell; the bytes never pass through the model and the upload is verified against the sha256. Files land on a public disk only if the `collection_name` repository is public — create or change it with `manage_media_collection` (`site_id`, `key`, `is_public`) BEFORE uploading.
|
|
66
83
|
Cache: `set_api_cache_status` (`site_id`, `enabled`) to toggle per-site; `flush_api_cache` (`site_id`, optional `resource`) to invalidate cached responses after bulk edits.
|
|
67
84
|
Visual editor: `configure_visual_editor` (`site_id`, optional `environment`, `frontend_url`, `routes`, `render_mode`, `upload_media_collection`) — see `references/visual-editor.md`.
|
|
68
85
|
|
|
69
|
-
> `update_page` **replaces all blocks** when `blocks` is supplied. `update_entry` creates a revision. `create_page` always starts as `draft`.
|
|
86
|
+
> `update_page` **replaces all blocks** when `blocks` is supplied (send every block again with its `id` to keep it). `update_entry` creates a revision. `create_page` always starts as `draft`.
|
|
70
87
|
|
|
71
88
|
## Phase 2 — Build a frontend with the SDK
|
|
72
89
|
|
|
@@ -93,6 +110,8 @@ const posts = await crafty.entries.list("posts", { per_page: 15 });
|
|
|
93
110
|
|
|
94
111
|
`pages.get()` returns the page enriched with block helpers (`page.block(type)`, `page.blocksOf(type)`, `page.byType`, …). **Full client config, every resource and return shape, block helpers, errors, and an end-to-end example: read `references/sdk-development.md`.**
|
|
95
112
|
|
|
113
|
+
Serving `llms.txt` / `llms-full.txt` for AI agents and crawlers: `crafty.llms.handler()` as a route (Next/Astro/Nuxt), or `crafty.llms.index()` / `full()` written into `dist/` for a static build. Title, summary, language, and routeless collections are configured on the "llms.txt" admin screen or the `configure_llms` MCP tool. **Full API, per-framework wiring, and error handling: `references/sdk-development.md`.**
|
|
114
|
+
|
|
96
115
|
## Phase 3 — Deploy a static site with the CLI
|
|
97
116
|
|
|
98
117
|
```bash
|
|
@@ -145,6 +164,9 @@ These are two different credentials — do not mix them:
|
|
|
145
164
|
- **A tool is missing or fails with "Insufficient OAuth scope"** → the token lacks that tool's scope; re-issue it with `crafty:write` / `crafty:publish` / `crafty:submissions` as needed.
|
|
146
165
|
- **`forms.submit()` throws `BAD_REQUEST`** → `siteSlug` was not set in `createCraftyClient()`. Submissions hit the public endpoint and deliberately omit the API key.
|
|
147
166
|
- **`update_entry` / `update_page` wipe fields you don't send** → both MCP tools do a **full replace**, not a merge. If you send only the new fields, all existing fields are deleted in that revision. Always fetch the current entry first (`get_entry`), merge your changes into the full field map, then call `update_entry` with the complete merged object.
|
|
167
|
+
- **`create_page` / `update_page` reject block data** → block data is validated against the block type (`blocks.2.data.items.1.title: …`), `number` fields are integers, `string` fields max 255 characters, and `block_type_id` must belong to the same site. Read the schema with `get_block_type` first.
|
|
168
|
+
- **Data silently missing from a block** → keys not declared in the block type are dropped; check the `warnings` array in the response.
|
|
169
|
+
- **Modelled a list as a collection or a `json` field** → use a block type with a `repeater` (or `stringList`) instead; see "Model content with block types first".
|
|
148
170
|
- **Content not visible via the SDK** → it isn't published. Pages/forms must be published (`publish_page` / `publish_form`).
|
|
149
171
|
- **Confusing the two tokens** → the SDK `apiKey` (X-API-Key) is not an MCP Bearer token.
|
|
150
172
|
- **Stale skill copy** → a project copy of this skill (e.g. `.claude/skills/crafty-cms`) does not update with the SDK. After upgrading `@craftware/crafty-sdk`, copy `node_modules/@craftware/crafty-sdk/skills/crafty-cms` over it.
|
|
@@ -24,12 +24,12 @@ Generate a long-lived Personal Access Token from your Crafty profile, choosing t
|
|
|
24
24
|
|
|
25
25
|
Create an "MCP client" in your Crafty profile and pick a grant type:
|
|
26
26
|
|
|
27
|
-
- **Authorization Code** — standard browser-redirect flow for tools that open a browser (Claude.ai, Cursor, VS Code). Select the redirect URI matching your tool.
|
|
28
|
-
- **Device Code (RFC 8628)** — for
|
|
27
|
+
- **Authorization Code** — standard browser-redirect flow for tools that open a browser (Claude.ai, Claude Code, Codex, Cursor, VS Code, ChatGPT). Select the redirect URI matching your tool. Most of these register themselves (see below), so a manual client is only needed when the tool asks for a `client_id`.
|
|
28
|
+
- **Device Code (RFC 8628)** — for clients that can't open a browser and support this grant; the client shows a code that you approve in the browser.
|
|
29
29
|
|
|
30
|
-
When you create the client manually in your profile you are shown the `client_id` and a **one-time** `client_secret` — copy it immediately (PATs likewise show the token once). Clients that **auto-register** through discovery (e.g. Claude.ai, Cursor) are registered as public clients and receive no client secret.
|
|
30
|
+
When you create the client manually in your profile you are shown the `client_id` and a **one-time** `client_secret` — copy it immediately (PATs likewise show the token once). Clients that **auto-register** through discovery (e.g. Claude.ai, Claude Code, Codex, Cursor, ChatGPT) are registered as public clients and receive no client secret.
|
|
31
31
|
|
|
32
|
-
OAuth clients that support MCP auto-discovery (Claude.ai, Cursor) can find everything from the server URL alone: discovery is published at `/.well-known/oauth-protected-resource` and `/.well-known/oauth-authorization-server`, with `authorization_endpoint` `/oauth/authorize`, `token_endpoint` `/oauth/token`, dynamic `registration_endpoint` `/oauth/register`, PKCE (`S256`), and grants `authorization_code` + `refresh_token`. These OAuth endpoints live at the tenant **root**, not under `/mcp`.
|
|
32
|
+
OAuth clients that support MCP auto-discovery (Claude.ai, Claude Code, Codex, Cursor, ChatGPT) can find everything from the server URL alone: discovery is published at `/.well-known/oauth-protected-resource` and `/.well-known/oauth-authorization-server`, with `authorization_endpoint` `/oauth/authorize`, `token_endpoint` `/oauth/token`, dynamic `registration_endpoint` `/oauth/register`, PKCE (`S256`), and grants `authorization_code` + `refresh_token`. Registered redirect URIs must be `https`, a custom app scheme, or `http` on a loopback address (so local CLI callbacks work). These OAuth endpoints live at the tenant **root**, not under `/mcp`.
|
|
33
33
|
|
|
34
34
|
## Scopes
|
|
35
35
|
|
|
@@ -38,7 +38,7 @@ When you create a token (PAT or OAuth client) you grant one or more scopes. Scop
|
|
|
38
38
|
| Scope | Unlocks | Tools |
|
|
39
39
|
|---|---|---|
|
|
40
40
|
| `crafty:read` | Read sites, pages, block types, collections, entries, media, and form definitions | all `list_*` / `get_*` except form submissions |
|
|
41
|
-
| `crafty:write` | Create and
|
|
41
|
+
| `crafty:write` | Create, update and delete sites, pages, collections, entries, media, and forms; configure the visual editor, `llms.txt`, and the API cache | all `create_*` / `update_*` / `delete_*`, `upload_media`, `configure_visual_editor`, `configure_llms`, `flush_api_cache`, `set_api_cache_status` |
|
|
42
42
|
| `crafty:publish` | Publish and unpublish pages and forms | `publish_page`, `unpublish_page`, `publish_form`, `unpublish_form` |
|
|
43
43
|
| `crafty:submissions` | Read form submissions (may contain personal data) | `list_form_submissions`, `get_form_submission` |
|
|
44
44
|
|
|
@@ -48,25 +48,21 @@ Request all four for full authoring plus submission access. Scopes are also adve
|
|
|
48
48
|
|
|
49
49
|
Replace `https://<tenant>/mcp` with your tenant URL and `YOUR_PAT` with a Personal Access Token.
|
|
50
50
|
|
|
51
|
-
**Claude.ai (Authorization Code):** create an Authorization Code MCP client with redirect URI `https://claude.ai/api/mcp/auth_callback
|
|
51
|
+
**Claude.ai (Authorization Code):** go to **Customize → Connectors → + → Add custom connector**, enter the server URL, click **Connect** and approve in the browser (on Team/Enterprise an Owner adds it first under **Organization settings → Connectors**). It auto-registers; to use your own client instead, create an Authorization Code MCP client with redirect URI `https://claude.ai/api/mcp/auth_callback` and paste its `client_id`/`client_secret` in the connector's **Advanced settings**.
|
|
52
52
|
|
|
53
53
|
**Claude Code (CLI):**
|
|
54
54
|
|
|
55
55
|
```bash
|
|
56
56
|
# Option A — PAT
|
|
57
|
-
claude mcp add
|
|
58
|
-
--url https://<tenant>/mcp \
|
|
57
|
+
claude mcp add --transport http crafty https://<tenant>/mcp \
|
|
59
58
|
--header "Authorization: Bearer YOUR_PAT"
|
|
60
59
|
|
|
61
|
-
# Option B —
|
|
62
|
-
claude mcp add
|
|
63
|
-
|
|
64
|
-
--oauth2 device_code \
|
|
65
|
-
--client-id YOUR_CLIENT_ID \
|
|
66
|
-
--client-secret YOUR_CLIENT_SECRET
|
|
60
|
+
# Option B — OAuth in the browser (auto-registers)
|
|
61
|
+
claude mcp add --transport http crafty https://<tenant>/mcp
|
|
62
|
+
# then, inside Claude Code: /mcp → crafty → Authenticate
|
|
67
63
|
```
|
|
68
64
|
|
|
69
|
-
**Cursor (Authorization Code):**
|
|
65
|
+
**Cursor (Authorization Code):** add to `~/.cursor/mcp.json` and authorize when prompted (it auto-registers; for your own client use redirect URI `cursor://anysphere.cursor-deeplink/mcp/auth_callback`):
|
|
70
66
|
|
|
71
67
|
```json
|
|
72
68
|
{ "mcpServers": { "crafty": { "url": "https://<tenant>/mcp" } } }
|
|
@@ -79,23 +75,19 @@ claude mcp add crafty --transport http \
|
|
|
79
75
|
"headers": { "Authorization": "Bearer YOUR_PAT" } } } }
|
|
80
76
|
```
|
|
81
77
|
|
|
82
|
-
**Codex CLI (`~/.codex/config.
|
|
78
|
+
**Codex CLI** (writes `~/.codex/config.toml`):
|
|
83
79
|
|
|
84
|
-
```
|
|
85
|
-
# Option A — PAT
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
# Option B — Device Code: add
|
|
93
|
-
# auth: { type: device_code, client_id: ..., client_secret: ...,
|
|
94
|
-
# token_url: https://<tenant>/oauth/token,
|
|
95
|
-
# device_authorization_url: https://<tenant>/oauth/device/code }
|
|
80
|
+
```bash
|
|
81
|
+
# Option A — PAT, read from an environment variable
|
|
82
|
+
export CRAFTY_MCP_TOKEN="YOUR_PAT"
|
|
83
|
+
codex mcp add crafty --url https://<tenant>/mcp --bearer-token-env-var CRAFTY_MCP_TOKEN
|
|
84
|
+
|
|
85
|
+
# Option B — OAuth in the browser (auto-registers)
|
|
86
|
+
codex mcp add crafty --url https://<tenant>/mcp
|
|
87
|
+
codex mcp login crafty
|
|
96
88
|
```
|
|
97
89
|
|
|
98
|
-
**ChatGPT (Authorization Code,
|
|
90
|
+
**ChatGPT (Authorization Code; Plus, Pro, Business, Enterprise, Education, web):** turn on **Developer mode** in **Settings → Apps & Connectors → Advanced settings**, click **Create**, paste the server URL, choose **OAuth**, and approve in the Crafty login. It auto-registers.
|
|
99
91
|
|
|
100
92
|
## Tool catalog
|
|
101
93
|
|
|
@@ -109,8 +101,9 @@ All tools return a JSON text response. IDs are integers; slugs are strings. Pagi
|
|
|
109
101
|
| `get_site` | `site_id` | — | one site |
|
|
110
102
|
| `list_pages` | `site_id` | `status` (`draft`/`published`) | paginated pages, ordered by title |
|
|
111
103
|
| `get_page` | `page_id` | — | page with its blocks (incl. block types) |
|
|
112
|
-
| `list_block_types` | — | — |
|
|
113
|
-
| `
|
|
104
|
+
| `list_block_types` | — | — | block types and their schemas (not filtered by site) |
|
|
105
|
+
| `get_block_type` | `site_id`, and `block_type_id` or `slug` | — | one block type of the site with its full schema (`field_definitions`) |
|
|
106
|
+
| `list_collections` | — | `site_id` | active collections (with their `id`, used by `update_collection` / `delete_collection`) |
|
|
114
107
|
| `list_entries` | `collection_slug` | `site_id`, `per_page` | paginated entries (newest id first) |
|
|
115
108
|
| `get_entry` | `entry_id` | — | one entry with its collection |
|
|
116
109
|
| `list_media` | `site_id` | `collection`, `per_page` | paginated media for the site |
|
|
@@ -133,14 +126,24 @@ Form submissions may contain personal data, so they require their own scope.
|
|
|
133
126
|
| `flush_api_cache` | `site_id` | `resource` | flushes cached public API responses for the site; `resource` = `pages`, `entries`, `collections`, `media`, or `all` (default `all`) |
|
|
134
127
|
| `set_api_cache_status` | `site_id`, `enabled` | — | enables (`true`) or disables (`false`) the public API response cache for the site; per-site override, preserves other cache config (TTLs, bypass rules) |
|
|
135
128
|
| `create_site` | `name` | `slug` | slug auto-generated from name; returns the site (with a generated `api_token`) |
|
|
136
|
-
| `
|
|
137
|
-
| `
|
|
129
|
+
| `create_block_type` | `site_id`, `name`, `fields` | `slug`, `description` | `fields: [{ key, type, label?, required? }]`; types `string`, `text`, `longText`, `url`, `number` (integer), `boolean`, `datetime`, `reference`, `multiReference`, `stringList`, `repeater`. A `repeater` takes `fields: [...]` (subtypes `string`, `text`, `longText`, `url`, `number`, `boolean`, `reference`, `stringList`; no nested repeater) and optional `min`/`max`. Slug auto-generated from name, unique per site |
|
|
130
|
+
| `update_block_type` | `site_id`, `block_type_id` | `name`, `slug`, `description`, `fields`, `force` | `fields` **replaces all fields**. Removing or retyping a field (or repeater subfield) that existing blocks fill is rejected unless `force: true`; block data is never rewritten |
|
|
131
|
+
| `delete_block_type` | `site_id`, `block_type_id`, `confirm: true` | — | refused while blocks use the type |
|
|
132
|
+
| `create_page` | `site_id`, `title` | `slug`, `blocks` | starts as `draft`; `blocks: [{ block_type_id, data }]` created in order; `data` is validated against the block type (errors like `blocks.2.data.items.1.title`), undeclared keys are dropped and listed in `warnings` |
|
|
133
|
+
| `update_page` | `page_id` | `title`, `slug`, `blocks` | **if `blocks` is supplied, ALL existing blocks are replaced** (send each block with its `id` to keep it); same validation and `warnings` as `create_page` |
|
|
134
|
+
| `create_collection` | `site_id`, `name` | `slug`, `description`, `fields` | slug auto-generated from name; `fields: [{ key, type, label, required? }]` |
|
|
135
|
+
| `update_collection` | `collection_id` | `name`, `description`, `is_active`, `fields` | `fields` is a **full replacement** list in display order; each field `{ key, type, label?, required?, model?, repository?, collection?, relation?, slug_source?, title_source? }` (media reference: `{ key: "image", type: "reference", model: "Media", repository: "library" }`) |
|
|
136
|
+
| `delete_collection` | `collection_id`, `confirm: true` | — | **permanently** deletes the collection and all its entries |
|
|
138
137
|
| `create_entry` | `collection_slug`, `site_id`, `slug` | `data` | `data` = field key/value pairs |
|
|
139
138
|
| `update_entry` | `entry_id`, `data` | `slug` | snapshots the prior data into a new revision |
|
|
140
|
-
| `upload_media` | `url`, `site_id` | `collection_name` (default `library`), `file_name` |
|
|
139
|
+
| `upload_media` | `url`, `site_id` | `collection_name` (default `library`), `file_name`, `sha256` | http(s) URL or base64 data URI (max 256 KB decoded); `sha256` rejects and discards the upload on mismatch; the response returns the stored `sha256`, `visibility` and a `warning` when the file is private |
|
|
140
|
+
| `request_media_upload` | `site_id`, `file_name`, `sha256` | `collection_name` (default `library`), `size` | returns a 15-minute single-use signed URL and a ready `curl -T` command for uploading a **local binary file** without sending its bytes through the model; max 25 MB; verified against `sha256` |
|
|
141
|
+
| `manage_media_collection` | `site_id`, `key` | `name`, `description`, `is_public` | creates or updates a media repository; `is_public: true` gives permanent public URLs (existing files are moved in the background); new repositories are private |
|
|
142
|
+
| `delete_media` | `site_id`, `media_id`, `confirm: true` | — | **permanently** deletes one media file (ids from `list_media`) |
|
|
141
143
|
| `create_form` | `site_id`, `name`, `slug` | `description`, `fields` | `fields: [{ key, type, label, required? }]`; starts as `draft` |
|
|
142
144
|
| `update_form` | `form_id` | `name`, `slug`, `description`, `fields`, `notification_emails` | only supplied fields change; `fields`/`notification_emails` replace |
|
|
143
|
-
| `configure_visual_editor` | `site_id` | `environment` (default `production`), `frontend_url`, `routes` (`page_pattern`, `home_slug`, `collections`, `fixed`), `render_mode` (`ssr`/`hybrid`/`static`/`unknown`), `upload_media_collection` | visual editor settings of one environment; only sent keys change, `null` resets to the fallback; with only `site_id` it just reads; returns the effective settings |
|
|
145
|
+
| `configure_visual_editor` | `site_id` | `environment` (default `production`), `frontend_url`, `routes` (`page_pattern`, `home_slug`, `collections`, `fixed`), `render_mode` (`ssr`/`hybrid`/`static`/`unknown`), `upload_media_collection` | visual editor settings of one environment; only sent keys change, `null` resets to the fallback; with only `site_id` it just reads; returns the effective settings plus `llms_warnings` (the `llms.txt` generator's warnings, since routes affect it too) |
|
|
146
|
+
| `configure_llms` | `site_id` | `environment` (default `production`), `title`, `summary`, `language`, `excluded_collections` (routed collections to drop), `included_collections` (routeless collections to opt in), `collection_languages` | admins only; same read/partial-update semantics as `configure_visual_editor`; only sent keys change, `null` resets to the fallback; with only `site_id` it just reads; returns the effective settings, the configuration warnings, and the first 40 lines of the generated `llms.txt` |
|
|
144
147
|
|
|
145
148
|
### Publish (`crafty:publish`)
|
|
146
149
|
|
|
@@ -153,16 +156,24 @@ Form submissions may contain personal data, so they require their own scope.
|
|
|
153
156
|
|
|
154
157
|
## Canonical workflows
|
|
155
158
|
|
|
159
|
+
**Model content with block types (preferred)**
|
|
160
|
+
|
|
161
|
+
1. `list_sites` → choose a `site_id` (or `create_site`).
|
|
162
|
+
2. For each section of the design, `create_block_type` (or `get_block_type` if it exists). Use a `repeater` for lists of items and `stringList` for lists of plain strings; only use a collection for large independent record sets.
|
|
163
|
+
3. `create_page` (one page per language, e.g. `home` and `home-en`) with `blocks: [{ block_type_id, data }, …]`; fix any `blocks.N.data.…` errors and check `warnings`.
|
|
164
|
+
4. `publish_page`.
|
|
165
|
+
5. To change a schema later, `update_block_type` with the FULL field list (use `force: true` only if you accept orphaning data that blocks already hold).
|
|
166
|
+
|
|
156
167
|
**Build and publish a page**
|
|
157
168
|
|
|
158
169
|
1. `list_sites` → choose a `site_id` (or `create_site`).
|
|
159
|
-
2. `list_block_types` → note each `id` and its data schema.
|
|
170
|
+
2. `get_block_type` / `list_block_types` → note each `id` and its data schema.
|
|
160
171
|
3. `create_page` with `site_id`, `title`, and `blocks: [{ block_type_id, data }, …]`.
|
|
161
172
|
4. `publish_page` with the returned `page_id`.
|
|
162
173
|
|
|
163
174
|
**Structured content**
|
|
164
175
|
|
|
165
|
-
1. `list_collections` (optionally `site_id`) → pick a `collection_slug
|
|
176
|
+
1. `list_collections` (optionally `site_id`) → pick a `collection_slug`, or `create_collection` with its `fields` (`update_collection` changes them later).
|
|
166
177
|
2. `create_entry` with `collection_slug`, `site_id`, `slug`, and `data`.
|
|
167
178
|
3. `update_entry` to edit (each edit stores a revision).
|
|
168
179
|
|
|
@@ -174,8 +185,10 @@ Form submissions may contain personal data, so they require their own scope.
|
|
|
174
185
|
|
|
175
186
|
**Media**
|
|
176
187
|
|
|
177
|
-
1. `
|
|
178
|
-
2. `
|
|
188
|
+
1. Need permanent public URLs? `manage_media_collection` with `site_id`, `key`, `is_public: true` first (otherwise files get expiring signed URLs).
|
|
189
|
+
2. From a URL or a tiny file: `upload_media` with `url` and `site_id` (optionally `collection_name`, `sha256`).
|
|
190
|
+
From a local file: compute `shasum -a 256 <file>`, call `request_media_upload`, then run the returned `curl -T` command.
|
|
191
|
+
3. `list_media` to confirm and retrieve URLs.
|
|
179
192
|
|
|
180
193
|
**Visual editor**
|
|
181
194
|
|
|
@@ -202,5 +215,5 @@ The public API has a tag-based response cache (enabled per environment). Per-sit
|
|
|
202
215
|
- **401 / authentication error** — the Bearer token is missing, invalid, or expired; reconnect or regenerate it. Every `/mcp` request must carry a valid token.
|
|
203
216
|
- **A tool is missing, or fails with `Insufficient OAuth scope`** — the token lacks that tool's scope. Tools are only advertised when the token carries the matching scope (`crafty:write` to create/edit, `crafty:publish` to publish, `crafty:submissions` to read form submissions). Re-issue the token with the scopes you need.
|
|
204
217
|
- **Tenant not found** — wrong host; use the exact tenant domain. OAuth token endpoints are at the tenant root (`/oauth/...`), not under `/mcp`.
|
|
205
|
-
- **
|
|
218
|
+
- **OAuth fails with a manually created client** — its type must match the flow (Authorization Code or Device Code), its redirect URI must be exactly the one the tool uses, and `client_id`/`client_secret` must match. Tools that auto-register need no manual client.
|
|
206
219
|
- **Token/secret lost** — `client_secret` and PATs are shown only once at creation; regenerate if lost.
|
|
@@ -101,6 +101,28 @@ const features = landing.blocksOf("feature"); // CraftyBlock[]
|
|
|
101
101
|
const cta = landing.requireBlock("cta"); // throws plain Error if absent
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
+
### Block data shapes (block types)
|
|
105
|
+
|
|
106
|
+
`block.data` is keyed by the block type's field keys. Field values by type:
|
|
107
|
+
|
|
108
|
+
| Field type | `block.data[key]` |
|
|
109
|
+
|---|---|
|
|
110
|
+
| `string`, `text`, `url` | string |
|
|
111
|
+
| `longText` | sanitized HTML string |
|
|
112
|
+
| `number` | integer |
|
|
113
|
+
| `boolean` | boolean |
|
|
114
|
+
| `stringList` | `string[]` (e.g. `["AI", "Cloud"]`) |
|
|
115
|
+
| `repeater` | array of objects; every declared subfield is present, `null` when empty (e.g. `[{ icon, title, text, tags: string[] }]`) |
|
|
116
|
+
| `reference` | collection reference: entry summary `{ id, slug, label }` or `null`; media reference: the media id (look it up with `mediaFiles`) |
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
const solutions = home.block("solutions"); // block type slug "solutions"
|
|
120
|
+
const items = solutions?.data.items ?? [];
|
|
121
|
+
items.map((item) => `${item.title}: ${item.tags.join(", ")}`);
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Prefer modelling lists as `repeater` / `stringList` fields on a block type over collections or `json` fields; see the `crafty-cms` skill.
|
|
125
|
+
|
|
104
126
|
### `forms`
|
|
105
127
|
|
|
106
128
|
```ts
|
|
@@ -143,6 +165,49 @@ crafty.mediaFiles.list(query?, options?) // => { data: CraftyMediaFile[], links
|
|
|
143
165
|
|
|
144
166
|
`query`: `collection`, `directory_id`, `ttl_minutes` (signed-URL lifetime), `per_page`, `page`.
|
|
145
167
|
|
|
168
|
+
## `llms.txt`
|
|
169
|
+
|
|
170
|
+
`crafty.llms` fetches and serves the `llms.txt` (index) / `llms-full.txt` (full content) files Crafty generates from the site's published pages and opted-in collection entries.
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
crafty.llms.index(options?) // => string (the llms.txt body)
|
|
174
|
+
crafty.llms.full(options?) // => string (the llms-full.txt body)
|
|
175
|
+
crafty.llms.handler({ full?, maxAge? }) // => () => Promise<Response> (a route handler)
|
|
176
|
+
crafty.llms.linkTags({ full? }) // => string of <link> tags, ready to inline in <head>
|
|
177
|
+
crafty.llms.linkTagAttrs({ full? }) // => LlmsLinkTag[] (objects, for useHead / <Head>)
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`handler(opts)` returns a zero-argument function you can assign directly to a framework's route export; it fetches `full()` when `opts.full` is `true` (otherwise `index()`) and responds with `content-type: text/markdown; charset=utf-8` and `cache-control: public, max-age=${opts.maxAge ?? 300}`.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
// Next.js — app/llms.txt/route.ts
|
|
184
|
+
export const GET = crafty.llms.handler();
|
|
185
|
+
|
|
186
|
+
// Next.js — app/llms-full.txt/route.ts
|
|
187
|
+
export const GET = crafty.llms.handler({ full: true, maxAge: 3600 });
|
|
188
|
+
|
|
189
|
+
// Astro — src/pages/llms.txt.ts
|
|
190
|
+
export const GET = crafty.llms.handler();
|
|
191
|
+
|
|
192
|
+
// Nuxt (h3) — server/routes/llms.txt.ts
|
|
193
|
+
export default defineEventHandler(() => crafty.llms.handler()());
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
For a static build, call `index()` / `full()` directly and write the result into `dist/` at build time instead of serving a route:
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
import { writeFile } from "node:fs/promises";
|
|
200
|
+
|
|
201
|
+
await writeFile("dist/llms.txt", await crafty.llms.index());
|
|
202
|
+
await writeFile("dist/llms-full.txt", await crafty.llms.full());
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`linkTags()` / `linkTagAttrs()` advertise the files in `<head>` (`rel="alternate"`, `type="text/markdown"`); pass `{ full: true }` to also include the `llms-full.txt` link.
|
|
206
|
+
|
|
207
|
+
**Content and URLs**: title, summary, language, and which collections without a route are opted in are configured on the "llms.txt" settings screen in the admin, or via the `configure_llms` MCP tool. URLs are resolved from the visual editor routes — a collection without a route pattern is excluded by default. Sites hosted by Crafty get both files injected at the site root on their **next deploy** (a deploy already made before you started using this feature is not retroactively updated); a file the site's own build already ships wins over the injected one.
|
|
208
|
+
|
|
209
|
+
**Errors**: `index()` / `full()` (and therefore `handler()`) throw `CraftyError` with code `SERVER_ERROR` if the response body is not text.
|
|
210
|
+
|
|
146
211
|
## Error handling
|
|
147
212
|
|
|
148
213
|
The SDK throws `CraftyError` for HTTP, timeout, abort, network, and config failures.
|
|
@@ -195,7 +260,7 @@ try {
|
|
|
195
260
|
|
|
196
261
|
## Visual editor helpers
|
|
197
262
|
|
|
198
|
-
- `attrs(target, field, { label? })` / `crafty.attrs(...)` → `{ "data-crafty-block" | "data-crafty-entry", "data-crafty-field", "data-crafty-label"? }` to spread on the element that renders the value; `{}` when the target has no valid id. `field` is a field key or a JSON
|
|
263
|
+
- `attrs(target, field, { label? })` / `crafty.attrs(...)` → `{ "data-crafty-block" | "data-crafty-entry", "data-crafty-field", "data-crafty-label"? }` to spread on the element that renders the value; `{}` when the target has no valid id. `field` is a field key or a path into a list or JSON value (`sections[3].title`, `items[2].title` for a block-type `repeater`, `tags[1]` for a `stringList`, `items[0].tags[1]` for a stringList inside a repeater item). The index is the item's position in the stored data.
|
|
199
264
|
- `attrsHtml(target, field, { label? })` → the same attributes as an escaped HTML string.
|
|
200
265
|
- `previewFromRequest(req)` → preview token of an incoming request (URL string, `URL`, Web `Request`, Node `req.url`, Express `req.query`) or `null`.
|
|
201
266
|
- `readPreviewToken()` → token in the browser, or `null`.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Preparing a site for the Crafty visual editor
|
|
2
2
|
|
|
3
|
-
The visual editor lets a non-technical user open their real site inside the Crafty admin, click (or tap) a text or image, edit it in a side panel, watch the change live, and publish. It only works when the frontend is prepared with `@craftware/crafty-sdk` **0.3.0 or later**; use **0.4.
|
|
3
|
+
The visual editor lets a non-technical user open their real site inside the Crafty admin, click (or tap) a text or image, edit it in a side panel, watch the change live, and publish. It only works when the frontend is prepared with `@craftware/crafty-sdk` **0.3.0 or later**; use **0.4.1 or later** so buttons and links select instead of navigating, `hrefField` is available and Escape inside the site closes the admin's panels. This guide is the complete checklist.
|
|
4
4
|
|
|
5
5
|
## The mandatory question
|
|
6
6
|
|
|
@@ -34,10 +34,10 @@ Do every step. Keep changes minimal and in the site's existing style.
|
|
|
34
34
|
### 2. Upgrade the SDK
|
|
35
35
|
|
|
36
36
|
```bash
|
|
37
|
-
npm install @craftware/crafty-sdk@^0.4.
|
|
37
|
+
npm install @craftware/crafty-sdk@^0.4.1
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
Right after an SDK release npm may still hold stale registry metadata and fail with `ETARGET` (no matching version). Retry with `npm install @craftware/crafty-sdk@^0.4.
|
|
40
|
+
Right after an SDK release npm may still hold stale registry metadata and fail with `ETARGET` (no matching version). Retry with `npm install @craftware/crafty-sdk@^0.4.1 --prefer-online`, which re-checks the registry instead of trusting the cache.
|
|
41
41
|
|
|
42
42
|
The package ships this skill. If the project keeps its own copy (for example `.claude/skills/crafty-cms`), refresh it after every SDK upgrade so it matches the installed version:
|
|
43
43
|
|
|
@@ -98,6 +98,7 @@ export function editable(target, base = "") {
|
|
|
98
98
|
return edit;
|
|
99
99
|
}
|
|
100
100
|
```
|
|
101
|
+
- Block-type lists are editable per item: for a `repeater` use `items[${i}].title` (the stored index, same rule as `json` arrays) and for a `stringList` `tags[${i}]` or `items[${i}].tags[${j}]`. Only subfields of type `string`, `text`, `longText`, `url` or `number` are editable, and the item must already exist in the stored data. Mark the individual values, not the whole item.
|
|
101
102
|
- Editable types: `string`, `text`, `longText`, `url`, `number`, media `reference`, and string/number values inside `json`. Do not mark booleans, dates, selects, multi-references, or array items that are objects.
|
|
102
103
|
- `label` is a short Spanish name the client understands ("Título principal", "Texto del botón"). Without it the editor shows the field key.
|
|
103
104
|
- Pass blocks and entries as the API returns them. If an entry has fields named `order`, `data` and `type` at once, pass `{ kind: "entry", id: entry.id }` instead.
|
|
@@ -223,7 +224,7 @@ export const refreshCrafty = () => Promise.all([...cache.keys()].map(loadCollect
|
|
|
223
224
|
<script>CraftyVisualEditing.enableVisualEditing();</script>
|
|
224
225
|
```
|
|
225
226
|
|
|
226
|
-
Pin an exact version (`@0.4.
|
|
227
|
+
Pin an exact version (`@0.4.1`) with an `integrity="sha384-…" crossorigin="anonymous"` attribute (jsDelivr shows the hash) when the site uses Subresource Integrity.
|
|
227
228
|
|
|
228
229
|
### 6. Allow the admin to frame the site
|
|
229
230
|
|