@weatherboard/cms 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/next/reader.d.cts +2 -0
- package/dist/adapters/next/reader.d.mts +2 -0
- package/dist/adapters/next/reader.d.ts +2 -0
- package/dist/adapters/sanity/adapter.d.cts +15 -0
- package/dist/adapters/sanity/adapter.d.mts +15 -0
- package/dist/adapters/sanity/adapter.d.ts +15 -0
- package/dist/contracts/query.d.cts +19 -0
- package/dist/contracts/query.d.mts +19 -0
- package/dist/contracts/query.d.ts +19 -0
- package/dist/contracts/text.d.cts +40 -0
- package/dist/contracts/text.d.mts +40 -0
- package/dist/contracts/text.d.ts +40 -0
- package/dist/guard.cjs +3 -0
- package/dist/guard.cjs.map +7 -0
- package/dist/guard.d.cts +2 -0
- package/dist/guard.d.mts +2 -0
- package/dist/guard.d.ts +2 -0
- package/dist/guard.mjs +3 -0
- package/dist/guard.mjs.map +7 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +7 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +7 -0
- package/dist/invalidation/route.d.cts +12 -0
- package/dist/invalidation/route.d.mts +12 -0
- package/dist/invalidation/route.d.ts +12 -0
- package/dist/next.cjs +2 -0
- package/dist/next.cjs.map +7 -0
- package/dist/next.d.cts +4 -0
- package/dist/next.d.mts +4 -0
- package/dist/next.d.ts +4 -0
- package/dist/next.mjs +2 -0
- package/dist/next.mjs.map +7 -0
- package/dist/portable/array.d.cts +2 -0
- package/dist/portable/array.d.mts +2 -0
- package/dist/portable/array.d.ts +2 -0
- package/dist/portable/fallback.d.cts +4 -0
- package/dist/portable/fallback.d.mts +4 -0
- package/dist/portable/fallback.d.ts +4 -0
- package/dist/portable/site-content.d.cts +220 -0
- package/dist/portable/site-content.d.mts +220 -0
- package/dist/portable/site-content.d.ts +220 -0
- package/dist/portable/webhook.d.cts +133 -0
- package/dist/portable/webhook.d.mts +133 -0
- package/dist/portable/webhook.d.ts +133 -0
- package/dist/runtime/reader.d.cts +49 -0
- package/dist/runtime/reader.d.mts +49 -0
- package/dist/runtime/reader.d.ts +49 -0
- package/dist/sanity.cjs +2 -0
- package/dist/sanity.cjs.map +7 -0
- package/dist/sanity.d.cts +3 -0
- package/dist/sanity.d.mts +3 -0
- package/dist/sanity.d.ts +3 -0
- package/dist/sanity.mjs +2 -0
- package/dist/sanity.mjs.map +7 -0
- package/dist/server.cjs +2 -0
- package/dist/server.cjs.map +7 -0
- package/dist/server.d.cts +3 -0
- package/dist/server.d.mts +3 -0
- package/dist/server.d.ts +3 -0
- package/dist/server.mjs +2 -0
- package/dist/server.mjs.map +7 -0
- package/dist/site-content.cjs +7 -0
- package/dist/site-content.cjs.map +7 -0
- package/dist/site-content.d.cts +2 -0
- package/dist/site-content.d.mts +2 -0
- package/dist/site-content.d.ts +2 -0
- package/dist/site-content.mjs +7 -0
- package/dist/site-content.mjs.map +7 -0
- package/dist/testing.cjs +2 -0
- package/dist/testing.cjs.map +7 -0
- package/dist/testing.d.cts +2 -0
- package/dist/testing.d.mts +2 -0
- package/dist/testing.d.ts +2 -0
- package/dist/testing.mjs +2 -0
- package/dist/testing.mjs.map +7 -0
- package/dist/tooling/guard.d.cts +13 -0
- package/dist/tooling/guard.d.mts +13 -0
- package/dist/tooling/guard.d.ts +13 -0
- package/dist/tooling/test-fixtures/break-proof.d.cts +1 -0
- package/dist/tooling/test-fixtures/break-proof.d.mts +1 -0
- package/dist/tooling/test-fixtures/break-proof.d.ts +1 -0
- package/dist/tooling/test-fixtures/consumer.d.cts +9 -0
- package/dist/tooling/test-fixtures/consumer.d.mts +9 -0
- package/dist/tooling/test-fixtures/consumer.d.ts +9 -0
- package/dist/tooling/testing.d.cts +10 -0
- package/dist/tooling/testing.d.mts +10 -0
- package/dist/tooling/testing.d.ts +10 -0
- package/dist/webhook.cjs +2 -0
- package/dist/webhook.cjs.map +7 -0
- package/dist/webhook.d.cts +2 -0
- package/dist/webhook.d.mts +2 -0
- package/dist/webhook.d.ts +2 -0
- package/dist/webhook.mjs +2 -0
- package/dist/webhook.mjs.map +7 -0
- package/package.json +113 -3
- package/README.md +0 -3
package/dist/next.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var R=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var F=(e,r)=>{for(var t in r)R(e,t,{get:r[t],enumerable:!0})},$=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of z(r))!N.call(e,o)&&o!==t&&R(e,o,{get:()=>r[o],enumerable:!(n=j(r,o))||n.enumerable});return e};var U=e=>$(R({},"__esModule",{value:!0}),e);var K={};F(K,{createNextCmsReader:()=>O,createRevalidateRoute:()=>D});module.exports=U(K);var de=require("server-only");var L=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,H=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Z=/^[a-z0-9]{6,12}\.[a-z][a-z0-9_-]{0,63}$/;function E(e){if(!e||!Array.isArray(e.types)||e.types.length===0)throw new TypeError("CMS dependencies require document types");let r=[...e.types];for(let n of r)if(typeof n!="string"||!L.test(n))throw new TypeError("Invalid CMS document type");if(e.ids!==void 0&&!Array.isArray(e.ids))throw new TypeError("Invalid CMS document IDs");let t=e.ids===void 0?void 0:[...e.ids];for(let n of t??[])if(typeof n!="string"||!H.test(n)||/^(drafts|versions)\./.test(n))throw new TypeError("Invalid CMS document ID");if(new Set(r).size+new Set(t).size>128)throw new TypeError("Too many CMS tags");return Object.freeze({types:Object.freeze(r),...t===void 0?{}:{ids:Object.freeze(t)}})}function k(e){if(!e||typeof e.name!="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(e.name)||typeof e.query!="string"||e.query.trim()===""||typeof e.resolve!="function")throw new TypeError("Invalid CMS query configuration");let r=e.params;if(!r||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null)throw new TypeError("CMS params must be plain JSON scalars");let t={};for(let n of Reflect.ownKeys(r)){let o=Object.getOwnPropertyDescriptor(r,n);if(typeof n!="string"||!o||!Object.hasOwn(o,"value")||!o.enumerable)throw new TypeError("CMS params must be plain JSON scalars");let a=o.value;if(!(a===null||typeof a=="string"||typeof a=="boolean"||typeof a=="number"&&Number.isFinite(a)))throw new TypeError("CMS params must be plain JSON scalars");Object.defineProperty(t,n,{value:a,enumerable:!0})}return Object.freeze({name:e.name,query:e.query,params:Object.freeze(t),dependencies:E(e.dependencies),resolve:e.resolve})}function b(e,r){if(typeof e!="string"||e.length>77||!Z.test(e))throw new TypeError("Invalid CMS scope");let t=E(r),n=[...[...new Set(t.types)].sort().map(o=>`cms:${e}:type:${o}`),...[...new Set(t.ids??[])].sort().map(o=>`cms:${e}:id:${o}`)];return Object.freeze(n)}function A(e){if(!e||!Object.hasOwn(e,"data")||!Array.isArray(e.fallbackFields)||![...e.fallbackFields].every(r=>typeof r=="string"&&(r==="$"||/^[A-Za-z][A-Za-z0-9_.[\]-]{0,127}$/.test(r))))throw new TypeError("Invalid CMS resolution");return{data:e.data,fallbackFields:Object.freeze([...new Set(e.fallbackFields)])}}function S(e){let r=e?.revalidateSeconds??3600;if(!Number.isSafeInteger(r)||r<3600||!e?.adapter||typeof e.adapter.read!="function"||e.onDiagnostic!==void 0&&typeof e.onDiagnostic!="function")throw new TypeError("Invalid CMS reader configuration");let t=e.adapter;b(t.scope,{types:["ScopeValidation"]});let n=o=>{try{e.onDiagnostic?e.onDiagnostic(o):console.warn(JSON.stringify(o))}catch{}};return{async read(o,a){let s,l,d;try{if(s=k(o),d=b(t.scope,s.dependencies),!a||!Object.hasOwn(a,"fallback"))throw new TypeError;l=A(s.resolve(null,a.fallback))}catch{throw new TypeError("Invalid CMS query or fallback configuration")}let m=(f,c)=>(n({event:"cms.fallback",query:s.name,reason:f,fields:["$"],...c===void 0?{}:{status:c}}),{data:l.data,source:"fallback",fallbackFields:["$"],reason:f}),i;try{i=await t.read({name:s.name,query:s.query,params:s.params},{tags:d,revalidateSeconds:r})}catch{return m("network")}if(!i.ok){let c=["configuration","network","timeout","rate-limit","upstream","plan-limit","permission","malformed"].includes(i.reason)?i.reason:"malformed",T=Number.isInteger(i.status)&&(i.status??0)>=100&&(i.status??0)<=599?i.status:void 0;return m(c,T)}if(i.value===null||i.value===void 0)return m("missing");let y;try{y=A(s.resolve(i.value,a.fallback))}catch{return m("malformed")}return y.fallbackFields.includes("$")?m("invalid-field"):y.fallbackFields.length>0?(n({event:"cms.partial-fallback",query:s.name,reason:"invalid-field",fields:y.fallbackFields}),{...y,source:"mixed",reason:"invalid-field"}):{...y,source:"cms"}}}}var O=S;var _=require("next/cache.js");var h="sanity-webhook-signature",Q=/^t=(\d+)[, ]+v1=([^, ]+)$/;var I=new TextEncoder;function V(e){return crypto.subtle.importKey("raw",I.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}function B(e){if(!/^[A-Za-z0-9_-]+={0,2}$/.test(e))return null;let r=e.replace(/-/g,"+").replace(/_/g,"/");try{let t=atob(r),n=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)n[o]=t.charCodeAt(o);return n}catch{return null}}async function x(e){let{secret:r,rawBody:t,headers:n}=e,o=e.now??Date.now(),a=e.toleranceMs??3e5;if(!r||r.length===0)return{ok:!1,reason:"no-secret"};let s=n.get(h);if(!s)return{ok:!1,reason:"no-signature"};let l=Q.exec(s.trim());if(l===null)return{ok:!1,reason:"malformed-signature"};let d=Number(l[1]),m=l[2]??"";if(!Number.isSafeInteger(d))return{ok:!1,reason:"malformed-signature"};if(d<16094592e5)return{ok:!1,reason:"stale-timestamp"};if(Math.abs(o-d)>a)return{ok:!1,reason:"stale-timestamp"};let i=B(m);if(i===null)return{ok:!1,reason:"malformed-signature"};let y=await V(r);return await crypto.subtle.verify("HMAC",y,i,I.encode(`${d}.${t}`))?{ok:!0}:{ok:!1,reason:"bad-signature"}}var q=16*1024,W=1500,Y=new TextEncoder;function u(e,r,t={},n=!1){return new Response(n?null:JSON.stringify(r),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...t}})}function J(e,r){if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length===0)throw new TypeError("Invalid CMS invalidation mapping");let t=Object.create(null);for(let n of Reflect.ownKeys(r)){let o=Object.getOwnPropertyDescriptor(r,n);if(typeof n!="string"||!o?.enumerable||!Object.hasOwn(o,"value"))throw new TypeError("Invalid CMS invalidation mapping");let a=o.value;if(!Array.isArray(a)||!a.includes(n))throw new TypeError("Invalid CMS invalidation mapping");b(e,{types:a,ids:["validation"]}),t[n]=Object.freeze([...a])}for(let n of Object.values(t))if(n.some(o=>!Object.hasOwn(t,o)))throw new TypeError("Invalid CMS invalidation mapping");return Object.freeze(t)}function M(e){return typeof e=="string"&&e.trim()!==""&&Y.encode(e).byteLength>=32}var w=class extends Error{constructor(t){super("Invalid CMS webhook body");this.status=t}status};async function G(e){let r=e.body?.getReader();if(!r)return"";let t=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),n,o=new Promise((a,s)=>{n=setTimeout(()=>s(new w(400)),W)});try{let a=0,s="";for(;;){let{done:l,value:d}=await Promise.race([r.read(),o]);if(l)return s+t.decode();if(a+=d.byteLength,a>q)throw new w(413);s+=t.decode(d,{stream:!0})}}catch(a){throw r.cancel().catch(()=>{}),a}finally{clearTimeout(n),r.releaseLock()}}function D(e){let r=e.scope,t=J(r,e.typeToTags),n=e.secretEnv??"SANITY_REVALIDATE_SECRET",o=e.previousSecretEnv??"SANITY_REVALIDATE_SECRET_PREVIOUS",a=e.env??(()=>process.env),s=e.now??Date.now,l=async d=>{if(d.method!=="POST")return u(405,{error:"Method not allowed"},{Allow:"POST"},d.method==="HEAD");let m,i;try{let p=a(),C=p[n],g=p[o];if(!M(C)||g!==void 0&&!M(g))throw new Error;m=C,i=g}catch{return u(503,{error:"COULD NOT ANSWER: revalidation configuration unavailable"})}let y=d.headers.get(h);if(!y||y.length>512||!/^t=\d+[, ]+v1=[A-Za-z0-9_-]+={0,2}$/.test(y.trim()))return u(401,{error:"Unauthorized"});let f;try{f=await G(d)}catch(p){return p instanceof w&&p.status===413?u(413,{error:"Payload too large"}):u(400,{error:"Invalid body"})}try{let p=s();if(!Number.isFinite(p))throw new Error;if(!(await Promise.all([m,...i===void 0?[]:[i]].map(g=>x({secret:g,rawBody:f,headers:d.headers,now:p})))).some(g=>g.ok))return u(401,{error:"Unauthorized"})}catch{return u(401,{error:"Unauthorized"})}let c;try{c=JSON.parse(f)}catch{return u(400,{error:"Invalid payload"})}if(!c||typeof c!="object"||Array.isArray(c)||Object.keys(c).length!==2||!Object.hasOwn(c,"_type")||!Object.hasOwn(c,"_id"))return u(400,{error:"Invalid payload"});let{_type:T,_id:v}=c;if(typeof T!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(T)||typeof v!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(v))return u(400,{error:"Invalid payload"});if(!Object.hasOwn(t,T)||/^(drafts|versions)\./.test(v))return u(400,{error:"Unsupported document"});let P=b(r,{types:t[T],ids:[v]});try{for(let p of P)(0,_.revalidateTag)(p,{expire:0})}catch{return u(500,{error:"Could not revalidate"})}return u(200,{revalidated:!0})};return Object.freeze({POST:l,GET:l,HEAD:l,PUT:l,PATCH:l,DELETE:l,OPTIONS:l})}0&&(module.exports={createNextCmsReader,createRevalidateRoute});
|
|
2
|
+
//# sourceMappingURL=next.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/next.ts", "../src/contracts/query.ts", "../src/runtime/reader.ts", "../src/adapters/next/reader.ts", "../src/invalidation/route.ts", "../src/portable/webhook.ts"],
|
|
4
|
+
"sourcesContent": ["import \"server-only\";\nexport { createNextCmsReader } from \"./adapters/next/reader.js\";\nexport { createRevalidateRoute } from \"./invalidation/route.js\";\nexport type {\n TypeToTags, RevalidateRouteOptions, CmsRouteHandler, CmsRevalidateRoute,\n} from \"./invalidation/route.js\";\n", "/** A-1822 S1 owns this implementation. S0 registers the public signatures. */\nexport type CmsParams = Readonly<Record<string, string | number | boolean | null>>;\nexport type CmsDependencies = {\n readonly types: readonly string[];\n readonly ids?: readonly string[];\n};\nexport type CmsResolution<T> = {\n readonly data: T;\n readonly fallbackFields: readonly string[];\n};\nexport type CmsQuery<T> = {\n readonly name: string;\n readonly query: string;\n readonly params: CmsParams;\n readonly dependencies: CmsDependencies;\n readonly resolve: (raw: unknown, fallback: T) => CmsResolution<T>;\n};\n\nconst TYPE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;\nconst ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\nconst SCOPE = /^[a-z0-9]{6,12}\\.[a-z][a-z0-9_-]{0,63}$/;\n\nfunction dependenciesCopy(dependencies: CmsDependencies): CmsDependencies {\n if (!dependencies || !Array.isArray(dependencies.types) || dependencies.types.length === 0) {\n throw new TypeError(\"CMS dependencies require document types\");\n }\n const types = [...dependencies.types];\n for (const type of types) {\n if (typeof type !== \"string\" || !TYPE.test(type)) throw new TypeError(\"Invalid CMS document type\");\n }\n if (dependencies.ids !== undefined && !Array.isArray(dependencies.ids)) throw new TypeError(\"Invalid CMS document IDs\");\n const ids = dependencies.ids === undefined ? undefined : [...dependencies.ids];\n for (const id of ids ?? []) {\n if (typeof id !== \"string\" || !ID.test(id) || /^(drafts|versions)\\./.test(id)) {\n throw new TypeError(\"Invalid CMS document ID\");\n }\n }\n if (new Set(types).size + new Set(ids).size > 128) throw new TypeError(\"Too many CMS tags\");\n return Object.freeze({ types: Object.freeze(types), ...(ids === undefined ? {} : { ids: Object.freeze(ids) }) });\n}\n\nexport function defineCmsQuery<T>(query: CmsQuery<T>): CmsQuery<T> {\n if (!query || typeof query.name !== \"string\" || !/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(query.name)\n || typeof query.query !== \"string\" || query.query.trim() === \"\" || typeof query.resolve !== \"function\") {\n throw new TypeError(\"Invalid CMS query configuration\");\n }\n const params = query.params;\n if (!params || typeof params !== \"object\" || (Object.getPrototypeOf(params) !== Object.prototype && Object.getPrototypeOf(params) !== null)) {\n throw new TypeError(\"CMS params must be plain JSON scalars\");\n }\n const copied: Record<string, string | number | boolean | null> = {};\n for (const key of Reflect.ownKeys(params)) {\n const descriptor = Object.getOwnPropertyDescriptor(params, key);\n if (typeof key !== \"string\" || !descriptor || !Object.hasOwn(descriptor, \"value\") || !descriptor.enumerable) {\n throw new TypeError(\"CMS params must be plain JSON scalars\");\n }\n const value: unknown = descriptor.value;\n if (!(value === null || typeof value === \"string\" || typeof value === \"boolean\" || (typeof value === \"number\" && Number.isFinite(value)))) {\n throw new TypeError(\"CMS params must be plain JSON scalars\");\n }\n Object.defineProperty(copied, key, { value, enumerable: true });\n }\n return Object.freeze({ name: query.name, query: query.query, params: Object.freeze(copied), dependencies: dependenciesCopy(query.dependencies), resolve: query.resolve });\n}\n\nexport function cmsTags(scope: string, dependencies: CmsDependencies): readonly string[] {\n if (typeof scope !== \"string\" || scope.length > 77 || !SCOPE.test(scope)) throw new TypeError(\"Invalid CMS scope\");\n const copied = dependenciesCopy(dependencies);\n const tags = [\n ...[...new Set(copied.types)].sort().map((type) => `cms:${scope}:type:${type}`),\n ...[...new Set(copied.ids ?? [])].sort().map((id) => `cms:${scope}:id:${id}`),\n ];\n return Object.freeze(tags);\n}\n", "import { cmsTags, defineCmsQuery, type CmsQuery, type CmsResolution } from \"../contracts/query.js\";\n\nexport type CmsFailure = \"configuration\" | \"network\" | \"timeout\" | \"rate-limit\"\n | \"upstream\" | \"plan-limit\" | \"permission\" | \"malformed\";\nexport type CmsDiagnostic = {\n readonly event: \"cms.fallback\" | \"cms.partial-fallback\" | \"cms.refused\";\n readonly query: string;\n readonly reason: CmsFailure | \"missing\" | \"invalid-field\";\n readonly status?: number;\n readonly fields: readonly string[];\n};\nexport type CmsFetch = (url: string, init: RequestInit & {\n next?: { revalidate: number; tags: string[] };\n}) => Promise<Response>;\nexport type CmsReadPolicy = {\n readonly tags: readonly string[];\n readonly revalidateSeconds: number;\n};\nexport type CmsAdapterResult =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly reason: CmsFailure; readonly status?: number };\nexport type CmsAdapter = {\n readonly scope: string;\n read(query: Pick<CmsQuery<unknown>, \"name\" | \"query\" | \"params\">,\n policy: CmsReadPolicy): Promise<CmsAdapterResult>;\n};\nexport type CmsReadResult<T> = {\n readonly data: T;\n readonly source: \"cms\" | \"mixed\" | \"fallback\";\n readonly fallbackFields: readonly string[];\n readonly reason?: CmsFailure | \"missing\" | \"invalid-field\";\n};\nexport type CmsReaderOptions = {\n readonly adapter: CmsAdapter;\n readonly revalidateSeconds?: number;\n readonly onDiagnostic?: (event: CmsDiagnostic) => void;\n};\nexport type CmsReader = {\n read<T>(query: CmsQuery<T>, options: { readonly fallback: T }): Promise<CmsReadResult<T>>;\n};\n\nfunction resolution<T>(value: CmsResolution<T>): CmsResolution<T> {\n if (!value || !Object.hasOwn(value, \"data\") || !Array.isArray(value.fallbackFields)\n || ![...value.fallbackFields].every((field: unknown) => typeof field === \"string\"\n && (field === \"$\" || /^[A-Za-z][A-Za-z0-9_.[\\]-]{0,127}$/.test(field)))) {\n throw new TypeError(\"Invalid CMS resolution\");\n }\n return { data: value.data, fallbackFields: Object.freeze([...new Set(value.fallbackFields)]) };\n}\n\n/** Forwards cache policy; persistence and rendered-output invalidation belong to the host. */\nexport function createCmsReader(options: CmsReaderOptions): CmsReader {\n const seconds = options?.revalidateSeconds ?? 3600;\n if (!Number.isSafeInteger(seconds) || seconds < 3600 || !options?.adapter\n || typeof options.adapter.read !== \"function\"\n || (options.onDiagnostic !== undefined && typeof options.onDiagnostic !== \"function\")) {\n throw new TypeError(\"Invalid CMS reader configuration\");\n }\n const adapter = options.adapter;\n // Validate the scope without assuming any particular shared content types.\n cmsTags(adapter.scope, { types: [\"ScopeValidation\"] });\n const notify = (event: CmsDiagnostic): void => {\n try {\n if (options.onDiagnostic) options.onDiagnostic(event);\n else console.warn(JSON.stringify(event));\n } catch { /* Reporting must not break visitor rendering. */ }\n };\n return {\n async read<T>(input: CmsQuery<T>, readOptions: { readonly fallback: T }): Promise<CmsReadResult<T>> {\n let query: CmsQuery<T>;\n let local: CmsResolution<T>;\n let tags: readonly string[];\n try {\n query = defineCmsQuery(input);\n tags = cmsTags(adapter.scope, query.dependencies);\n if (!readOptions || !Object.hasOwn(readOptions, \"fallback\")) throw new TypeError();\n // Built-in resolvers validate fallback here, before any I/O.\n local = resolution(query.resolve(null, readOptions.fallback));\n } catch {\n throw new TypeError(\"Invalid CMS query or fallback configuration\");\n }\n const fallback = (reason: CmsFailure | \"missing\" | \"invalid-field\", status?: number): CmsReadResult<T> => {\n notify({ event: \"cms.fallback\", query: query.name, reason, fields: [\"$\"],\n ...(status === undefined ? {} : { status }) });\n return { data: local.data, source: \"fallback\", fallbackFields: [\"$\"], reason };\n };\n let result: CmsAdapterResult;\n try {\n result = await adapter.read({ name: query.name, query: query.query, params: query.params },\n { tags, revalidateSeconds: seconds });\n } catch { return fallback(\"network\"); }\n if (!result.ok) {\n const reasons: readonly CmsFailure[] = [\"configuration\", \"network\", \"timeout\", \"rate-limit\", \"upstream\", \"plan-limit\", \"permission\", \"malformed\"];\n const reason = reasons.includes(result.reason) ? result.reason : \"malformed\";\n const status = Number.isInteger(result.status) && (result.status ?? 0) >= 100 && (result.status ?? 0) <= 599 ? result.status : undefined;\n return fallback(reason, status);\n }\n if (result.value === null || result.value === undefined) return fallback(\"missing\");\n let resolved: CmsResolution<T>;\n try { resolved = resolution(query.resolve(result.value, readOptions.fallback)); }\n catch { return fallback(\"malformed\"); }\n if (resolved.fallbackFields.includes(\"$\")) return fallback(\"invalid-field\");\n if (resolved.fallbackFields.length > 0) {\n notify({ event: \"cms.partial-fallback\", query: query.name, reason: \"invalid-field\", fields: resolved.fallbackFields });\n return { ...resolved, source: \"mixed\", reason: \"invalid-field\" };\n }\n return { ...resolved, source: \"cms\" };\n },\n };\n}\n", "import { createCmsReader } from \"../../runtime/reader.js\";\n\n// Keep the adapter's patched global fetch and policy intact. No second cache.\nexport const createNextCmsReader = createCmsReader;\n", "import { revalidateTag } from \"next/cache.js\";\nimport { cmsTags } from \"../contracts/query.js\";\nimport { SANITY_SIGNATURE_HEADER, verifySanityWebhook } from \"../portable/webhook.js\";\n\nexport type TypeToTags = Readonly<Record<string, readonly string[]>>;\nexport type RevalidateRouteOptions = {\n readonly scope: string;\n readonly secretEnv?: string;\n readonly previousSecretEnv?: string;\n readonly typeToTags: TypeToTags;\n readonly env?: () => Readonly<Record<string, string | undefined>>;\n readonly now?: () => number;\n};\nexport type CmsRouteHandler = (request: Request) => Promise<Response>;\nexport type CmsRevalidateRoute = Readonly<Record<\n \"POST\" | \"GET\" | \"HEAD\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\", CmsRouteHandler\n>>;\n\nconst BODY_LIMIT = 16 * 1024;\nconst BODY_DEADLINE_MS = 1500;\nconst encoder = new TextEncoder();\n\nfunction response(status: number, value: unknown, headers: Record<string, string> = {}, head = false): Response {\n return new Response(head ? null : JSON.stringify(value), {\n status, headers: { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\", ...headers },\n });\n}\n\nfunction copyMapping(scope: string, mapping: TypeToTags): TypeToTags {\n if (!mapping || typeof mapping !== \"object\" || Array.isArray(mapping) || Object.keys(mapping).length === 0) {\n throw new TypeError(\"Invalid CMS invalidation mapping\");\n }\n const copied: Record<string, readonly string[]> = Object.create(null);\n for (const key of Reflect.ownKeys(mapping)) {\n const descriptor = Object.getOwnPropertyDescriptor(mapping, key);\n if (typeof key !== \"string\" || !descriptor?.enumerable || !Object.hasOwn(descriptor, \"value\")) {\n throw new TypeError(\"Invalid CMS invalidation mapping\");\n }\n const types: unknown = descriptor.value;\n if (!Array.isArray(types) || !types.includes(key)) throw new TypeError(\"Invalid CMS invalidation mapping\");\n // Reserve the document ID tag as well as validating every local type.\n cmsTags(scope, { types, ids: [\"validation\"] });\n copied[key] = Object.freeze([...types] as string[]);\n }\n for (const types of Object.values(copied)) {\n if (types.some((type) => !Object.hasOwn(copied, type))) throw new TypeError(\"Invalid CMS invalidation mapping\");\n }\n return Object.freeze(copied);\n}\n\nfunction validSecret(value: unknown): value is string {\n return typeof value === \"string\" && value.trim() !== \"\" && encoder.encode(value).byteLength >= 32;\n}\n\nclass BodyFailure extends Error {\n constructor(readonly status: 400 | 413) { super(\"Invalid CMS webhook body\"); }\n}\n\nasync function rawBody(request: Request): Promise<string> {\n const reader = request.body?.getReader();\n if (!reader) return \"\";\n const decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new BodyFailure(400)), BODY_DEADLINE_MS);\n });\n try {\n let bytes = 0;\n let text = \"\";\n while (true) {\n const { done, value } = await Promise.race([reader.read(), deadline]);\n if (done) return text + decoder.decode();\n bytes += value.byteLength;\n if (bytes > BODY_LIMIT) throw new BodyFailure(413);\n text += decoder.decode(value, { stream: true });\n }\n } catch (error) {\n // Cancellation must not extend the deadline, including a stalled source.\n void reader.cancel().catch(() => {});\n throw error;\n } finally {\n clearTimeout(timer);\n reader.releaseLock();\n }\n}\n\nexport function createRevalidateRoute(options: RevalidateRouteOptions): CmsRevalidateRoute {\n const scope = options.scope;\n const mapping = copyMapping(scope, options.typeToTags);\n const secretEnv = options.secretEnv ?? \"SANITY_REVALIDATE_SECRET\";\n const previousSecretEnv = options.previousSecretEnv ?? \"SANITY_REVALIDATE_SECRET_PREVIOUS\";\n const env = options.env ?? (() => process.env);\n const now = options.now ?? Date.now;\n\n const handler: CmsRouteHandler = async (request) => {\n if (request.method !== \"POST\") {\n return response(405, { error: \"Method not allowed\" }, { Allow: \"POST\" }, request.method === \"HEAD\");\n }\n let active: string;\n let previous: string | undefined;\n try {\n const values = env();\n const activeValue = values[secretEnv];\n const previousValue = values[previousSecretEnv];\n if (!validSecret(activeValue) || (previousValue !== undefined && !validSecret(previousValue))) throw new Error();\n active = activeValue;\n previous = previousValue;\n } catch {\n return response(503, { error: \"COULD NOT ANSWER: revalidation configuration unavailable\" });\n }\n const signature = request.headers.get(SANITY_SIGNATURE_HEADER);\n if (!signature || signature.length > 512 || !/^t=\\d+[, ]+v1=[A-Za-z0-9_-]+={0,2}$/.test(signature.trim())) {\n return response(401, { error: \"Unauthorized\" });\n }\n let body: string;\n try { body = await rawBody(request); }\n catch (error) {\n return error instanceof BodyFailure && error.status === 413\n ? response(413, { error: \"Payload too large\" }) : response(400, { error: \"Invalid body\" });\n }\n try {\n const clock = now();\n if (!Number.isFinite(clock)) throw new Error();\n const results = await Promise.all([active, ...(previous === undefined ? [] : [previous])].map((secret) =>\n verifySanityWebhook({ secret, rawBody: body, headers: request.headers, now: clock })));\n if (!results.some((result) => result.ok)) return response(401, { error: \"Unauthorized\" });\n } catch { return response(401, { error: \"Unauthorized\" }); }\n\n let payload: unknown;\n try { payload = JSON.parse(body); }\n catch { return response(400, { error: \"Invalid payload\" }); }\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)\n || Object.keys(payload).length !== 2 || !Object.hasOwn(payload, \"_type\") || !Object.hasOwn(payload, \"_id\")) {\n return response(400, { error: \"Invalid payload\" });\n }\n const { _type: type, _id: id } = payload as { _type: unknown; _id: unknown };\n if (typeof type !== \"string\" || !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(type)\n || typeof id !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(id)) {\n return response(400, { error: \"Invalid payload\" });\n }\n if (!Object.hasOwn(mapping, type) || /^(drafts|versions)\\./.test(id)) {\n return response(400, { error: \"Unsupported document\" });\n }\n const tags = cmsTags(scope, { types: mapping[type]!, ids: [id] });\n try {\n for (const tag of tags) revalidateTag(tag, { expire: 0 });\n } catch { return response(500, { error: \"Could not revalidate\" }); }\n return response(200, { revalidated: true });\n };\n return Object.freeze({ POST: handler, GET: handler, HEAD: handler, PUT: handler, PATCH: handler, DELETE: handler, OPTIONS: handler });\n}\n", "/**\n * Verifying a Sanity webhook (A-590 step 1, A-592's `SANITY_WEBHOOK_SECRET`).\n *\n * -------------------------------------------------------------------------\n * WHY THIS ENDPOINT NEEDS A SIGNATURE AT ALL\n * -------------------------------------------------------------------------\n *\n * `/revalidate` throws away cache entries. A-590: \"An unauthenticated\n * revalidation endpoint is a free cache-purge and rebuild trigger for anyone\n * who finds the URL.\" On a plan whose API request allowance is a HARD cap that\n * returns 402 rather than a bill, an attacker who can empty the cache at will\n * can take a client's site content-offline for the rest of the month. So the\n * signature is not hygiene here; it is the availability control.\n *\n * -------------------------------------------------------------------------\n * THE WIRE FORMAT IS MEASURED, NOT REMEMBERED\n * -------------------------------------------------------------------------\n *\n * Read on 2026-09-16 from Sanity's own toolkit,\n * `https://raw.githubusercontent.com/sanity-io/webhook-toolkit/main/src/signature.ts`:\n *\n * header `sanity-webhook-signature`\n * value `t=<millis>,v1=<signature>` (regex `/^t=(\\d+)[, ]+v1=([^, ]+)$/`)\n * signed payload `` `${timestamp}.${body}` ``\n * algorithm HMAC-SHA256\n * digest encoding base64url \u2014 standard base64 with `+`\u2192`-`, `/`\u2192`_`, padding stripped\n * MINIMUM_TIMESTAMP 1609459200000 (2021-01-01Z), below which a value is nonsense\n *\n * `signature.test.ts` does not take that paragraph's word for it either: it\n * signs a payload with `@sanity/webhook`'s own `encodeSignatureHeader` and\n * asserts this verifier accepts it. If Sanity changes the format, that test\n * goes red rather than production quietly rejecting every webhook.\n *\n * -------------------------------------------------------------------------\n * WHAT THIS ADDS TO THE TOOLKIT, AND WHY IT IS NOT JUST IMPORTED\n * -------------------------------------------------------------------------\n *\n * Two things, both of which are `CLAUDE.md`'s \"take the safer construction\".\n *\n * First, a REPLAY WINDOW. The toolkit enforces only that the timestamp is after\n * 2021; a captured webhook is otherwise replayable forever. A replayed purge is\n * the attack in the first paragraph, executed with a request somebody was\n * legitimately sent. `verifySanityWebhook` takes a symmetric tolerance \u2014 the\n * window is symmetric for A-44's reason, since a far-future timestamp is\n * precisely how you mint a request that stays replayable for a year.\n *\n * Second, a MISSING SECRET IS A REJECTION, never a bypass. A-590 says it in as\n * many words: \"reject on absence rather than skipping the check when the secret\n * is unset.\" The degraded mode of \"no secret configured, so allow it\" is\n * produced by a deploy that forgot `wrangler secret put`, announces itself\n * nowhere, and grants strangers the purge endpoint.\n *\n * The comparison is `crypto.subtle.verify`, which compares raw digests in\n * constant time. A `===` on the base64 strings short-circuits at the first\n * differing character, which turns one 2^256 search into a few dozen sequential\n * 64-way ones against an endpoint that answers in milliseconds.\n *\n * -------------------------------------------------------------------------\n * `encodeSignatureHeader` IS ASYNC. AWAIT IT. (A-651)\n * -------------------------------------------------------------------------\n *\n * `@sanity/webhook@4.0.4` declares\n *\n * encodeSignatureHeader(payload: string, timestamp: number, secret: string):\n * Promise<string>\n *\n * and nothing forces you to await it. Drop the `await` and the Promise is\n * stringified into the header as the literal `[object Promise]`, which arrives\n * here, fails `SIGNATURE_VALUE`, and is rejected as `malformed-signature`. The\n * rejection is correct and the message is about the wire format, so it sends\n * you to read Sanity's header spec \u2014 the one place the bug is not. TypeScript\n * does not save you either: the value usually lands in a `Record<string,\n * string>` built by a helper, or inside a template literal, both of which take\n * a Promise without complaint.\n *\n * The rule: every call to `encodeSignatureHeader` is awaited, and the helper\n * that wraps it is `async` rather than returning the Promise for someone else\n * to forget. The content-client compatibility tests and CMS signer tests await every\n * encoder call; this note exists so the next one\n * is too, because the symptom will not tell you.\n */\n\n/** Sanity's header. Lower-cased; `Headers.get` is case-insensitive either way. */\nexport const SANITY_SIGNATURE_HEADER = \"sanity-webhook-signature\";\n\n/** Sanity's own parser, character for character. See the header. */\nconst SIGNATURE_VALUE = /^t=(\\d+)[, ]+v1=([^, ]+)$/;\n\n/** 2021-01-01T00:00:00.000Z. Sanity's `MINIMUM_TIMESTAMP`; anything earlier is not a timestamp. */\nexport const MINIMUM_TIMESTAMP = 1_609_459_200_000;\n\n/**\n * How far from `now` a webhook timestamp may be, in milliseconds.\n *\n * Five minutes rather than A-44's sixty seconds: this one crosses Sanity's\n * delivery queue rather than two NTP-synced clouds, and a retried delivery is a\n * normal event. It is still a window rather than \"forever\", which is the whole\n * difference from the toolkit.\n */\nexport const DEFAULT_TOLERANCE_MS = 300_000;\n\nexport type WebhookRejection =\n /** `SANITY_WEBHOOK_SECRET` is unset or empty. Fail closed. */\n | \"no-secret\"\n /** No `sanity-webhook-signature` header. */\n | \"no-signature\"\n /** Header present but not `t=\u2026,v1=\u2026`, or `v1` is not decodable base64url. */\n | \"malformed-signature\"\n /** Before 2021, or outside the tolerance in either direction. */\n | \"stale-timestamp\"\n /** Well-formed, in window, wrong. */\n | \"bad-signature\";\n\nexport type WebhookVerification = { ok: true } | { ok: false; reason: WebhookRejection };\n\nconst encoder = new TextEncoder();\n\nfunction hmacKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\", \"verify\"],\n );\n}\n\n/**\n * base64url \u2192 bytes, without `Buffer`.\n *\n * `atob` rather than `node:crypto` or `Buffer` because this file is imported by\n * the Worker, and workerd has neither by default. Returns null rather than\n * throwing on rubbish, so a malformed header is a 401 and not a 500 \u2014 a\n * verifier that crashes on bad input is a verifier an attacker can use as a\n * denial of service.\n */\nfunction base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> | null {\n if (!/^[A-Za-z0-9_-]+={0,2}$/.test(value)) return null;\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n try {\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n } catch {\n return null;\n }\n}\n\n/**\n * Verify a Sanity webhook delivery.\n *\n * `rawBody` must be the bytes as received \u2014 `await request.text()`, never\n * `JSON.stringify(await request.json())`. A parse-and-restringify is not a\n * byte-for-byte round trip (key order, number formatting, whitespace) and one\n * byte changes the whole digest, so the symptom is every webhook failing after\n * a refactor that looked like tidying.\n *\n * The `reason` is for our logs and our tests. It is never returned to the\n * caller: \"your signature was fine but your clock is stale\" is the next step in\n * an attack, handed over free.\n */\nexport async function verifySanityWebhook(options: {\n secret: string | undefined;\n rawBody: string;\n headers: { get(name: string): string | null };\n now?: number;\n toleranceMs?: number;\n}): Promise<WebhookVerification> {\n const { secret, rawBody, headers } = options;\n const now = options.now ?? Date.now();\n const toleranceMs = options.toleranceMs ?? DEFAULT_TOLERANCE_MS;\n\n if (!secret || secret.length === 0) return { ok: false, reason: \"no-secret\" };\n\n const header = headers.get(SANITY_SIGNATURE_HEADER);\n if (!header) return { ok: false, reason: \"no-signature\" };\n\n const match = SIGNATURE_VALUE.exec(header.trim());\n if (match === null) return { ok: false, reason: \"malformed-signature\" };\n\n const timestamp = Number(match[1]);\n const provided = match[2] ?? \"\";\n if (!Number.isSafeInteger(timestamp)) return { ok: false, reason: \"malformed-signature\" };\n if (timestamp < MINIMUM_TIMESTAMP) return { ok: false, reason: \"stale-timestamp\" };\n if (Math.abs(now - timestamp) > toleranceMs) return { ok: false, reason: \"stale-timestamp\" };\n\n const signature = base64UrlToBytes(provided);\n if (signature === null) return { ok: false, reason: \"malformed-signature\" };\n\n const key = await hmacKey(secret);\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n key,\n signature,\n encoder.encode(`${timestamp}.${rawBody}`),\n );\n return valid ? { ok: true } : { ok: false, reason: \"bad-signature\" };\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,yBAAAE,EAAA,0BAAAC,IAAA,eAAAC,EAAAJ,GAAA,IA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kB,CAAC,EAEnD,GAAI,CAAC,OAAO,OAAOO,EAASM,CAAI,GAAK,uBAAuB,KAAKmC,CAAE,EACjE,OAAOhD,EAAS,IAAK,CAAE,MAAO,sBAAuB,CAAC,EAExD,IAAMiD,EAAOrC,EAAQN,EAAO,CAAE,MAAOC,EAAQM,CAAI,EAAI,IAAK,CAACmC,CAAE,CAAE,CAAC,EAChE,GAAI,CACF,QAAWE,KAAOD,KAAM,iBAAcC,EAAK,CAAE,OAAQ,CAAE,CAAC,CAC1D,MAAQ,CAAE,OAAOlD,EAAS,IAAK,CAAE,MAAO,sBAAuB,CAAC,CAAG,CACnE,OAAOA,EAAS,IAAK,CAAE,YAAa,EAAK,CAAC,CAC5C,EACA,OAAO,OAAO,OAAO,CAAE,KAAMkC,EAAS,IAAKA,EAAS,KAAMA,EAAS,IAAKA,EAAS,MAAOA,EAAS,OAAQA,EAAS,QAASA,CAAQ,CAAC,CACtI",
|
|
6
|
+
"names": ["next_exports", "__export", "createNextCmsReader", "createRevalidateRoute", "__toCommonJS", "import_server_only", "TYPE", "ID", "SCOPE", "dependenciesCopy", "dependencies", "types", "type", "ids", "id", "defineCmsQuery", "query", "params", "copied", "key", "descriptor", "value", "cmsTags", "scope", "tags", "resolution", "value", "field", "createCmsReader", "options", "seconds", "adapter", "cmsTags", "notify", "event", "input", "readOptions", "query", "local", "tags", "defineCmsQuery", "fallback", "reason", "status", "result", "resolved", "createNextCmsReader", "createCmsReader", "import_cache", "SANITY_SIGNATURE_HEADER", "SIGNATURE_VALUE", "encoder", "hmacKey", "secret", "base64UrlToBytes", "value", "padded", "binary", "bytes", "i", "verifySanityWebhook", "options", "rawBody", "headers", "now", "toleranceMs", "header", "SANITY_SIGNATURE_HEADER", "match", "SIGNATURE_VALUE", "timestamp", "provided", "signature", "key", "BODY_LIMIT", "BODY_DEADLINE_MS", "encoder", "response", "status", "value", "headers", "head", "copyMapping", "scope", "mapping", "copied", "key", "descriptor", "types", "cmsTags", "type", "validSecret", "BodyFailure", "rawBody", "request", "reader", "decoder", "timer", "deadline", "_resolve", "reject", "bytes", "text", "done", "error", "createRevalidateRoute", "options", "secretEnv", "previousSecretEnv", "env", "now", "handler", "active", "previous", "values", "activeValue", "previousValue", "signature", "SANITY_SIGNATURE_HEADER", "body", "clock", "secret", "verifySanityWebhook", "result", "payload", "id", "tags", "tag"]
|
|
7
|
+
}
|
package/dist/next.d.cts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
export { createNextCmsReader } from "./adapters/next/reader.cjs";
|
|
3
|
+
export { createRevalidateRoute } from "./invalidation/route.cjs";
|
|
4
|
+
export type { TypeToTags, RevalidateRouteOptions, CmsRouteHandler, CmsRevalidateRoute, } from "./invalidation/route.cjs";
|
package/dist/next.d.mts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
export { createNextCmsReader } from "./adapters/next/reader.mjs";
|
|
3
|
+
export { createRevalidateRoute } from "./invalidation/route.mjs";
|
|
4
|
+
export type { TypeToTags, RevalidateRouteOptions, CmsRouteHandler, CmsRevalidateRoute, } from "./invalidation/route.mjs";
|
package/dist/next.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
export { createNextCmsReader } from "./adapters/next/reader.js";
|
|
3
|
+
export { createRevalidateRoute } from "./invalidation/route.js";
|
|
4
|
+
export type { TypeToTags, RevalidateRouteOptions, CmsRouteHandler, CmsRevalidateRoute, } from "./invalidation/route.js";
|
package/dist/next.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"server-only";var M=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,_=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,D=/^[a-z0-9]{6,12}\.[a-z][a-z0-9_-]{0,63}$/;function h(e){if(!e||!Array.isArray(e.types)||e.types.length===0)throw new TypeError("CMS dependencies require document types");let r=[...e.types];for(let n of r)if(typeof n!="string"||!M.test(n))throw new TypeError("Invalid CMS document type");if(e.ids!==void 0&&!Array.isArray(e.ids))throw new TypeError("Invalid CMS document IDs");let t=e.ids===void 0?void 0:[...e.ids];for(let n of t??[])if(typeof n!="string"||!_.test(n)||/^(drafts|versions)\./.test(n))throw new TypeError("Invalid CMS document ID");if(new Set(r).size+new Set(t).size>128)throw new TypeError("Too many CMS tags");return Object.freeze({types:Object.freeze(r),...t===void 0?{}:{ids:Object.freeze(t)}})}function E(e){if(!e||typeof e.name!="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(e.name)||typeof e.query!="string"||e.query.trim()===""||typeof e.resolve!="function")throw new TypeError("Invalid CMS query configuration");let r=e.params;if(!r||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null)throw new TypeError("CMS params must be plain JSON scalars");let t={};for(let n of Reflect.ownKeys(r)){let o=Object.getOwnPropertyDescriptor(r,n);if(typeof n!="string"||!o||!Object.hasOwn(o,"value")||!o.enumerable)throw new TypeError("CMS params must be plain JSON scalars");let a=o.value;if(!(a===null||typeof a=="string"||typeof a=="boolean"||typeof a=="number"&&Number.isFinite(a)))throw new TypeError("CMS params must be plain JSON scalars");Object.defineProperty(t,n,{value:a,enumerable:!0})}return Object.freeze({name:e.name,query:e.query,params:Object.freeze(t),dependencies:h(e.dependencies),resolve:e.resolve})}function b(e,r){if(typeof e!="string"||e.length>77||!D.test(e))throw new TypeError("Invalid CMS scope");let t=h(r),n=[...[...new Set(t.types)].sort().map(o=>`cms:${e}:type:${o}`),...[...new Set(t.ids??[])].sort().map(o=>`cms:${e}:id:${o}`)];return Object.freeze(n)}function k(e){if(!e||!Object.hasOwn(e,"data")||!Array.isArray(e.fallbackFields)||![...e.fallbackFields].every(r=>typeof r=="string"&&(r==="$"||/^[A-Za-z][A-Za-z0-9_.[\]-]{0,127}$/.test(r))))throw new TypeError("Invalid CMS resolution");return{data:e.data,fallbackFields:Object.freeze([...new Set(e.fallbackFields)])}}function A(e){let r=e?.revalidateSeconds??3600;if(!Number.isSafeInteger(r)||r<3600||!e?.adapter||typeof e.adapter.read!="function"||e.onDiagnostic!==void 0&&typeof e.onDiagnostic!="function")throw new TypeError("Invalid CMS reader configuration");let t=e.adapter;b(t.scope,{types:["ScopeValidation"]});let n=o=>{try{e.onDiagnostic?e.onDiagnostic(o):console.warn(JSON.stringify(o))}catch{}};return{async read(o,a){let s,l,d;try{if(s=E(o),d=b(t.scope,s.dependencies),!a||!Object.hasOwn(a,"fallback"))throw new TypeError;l=k(s.resolve(null,a.fallback))}catch{throw new TypeError("Invalid CMS query or fallback configuration")}let m=(f,c)=>(n({event:"cms.fallback",query:s.name,reason:f,fields:["$"],...c===void 0?{}:{status:c}}),{data:l.data,source:"fallback",fallbackFields:["$"],reason:f}),i;try{i=await t.read({name:s.name,query:s.query,params:s.params},{tags:d,revalidateSeconds:r})}catch{return m("network")}if(!i.ok){let c=["configuration","network","timeout","rate-limit","upstream","plan-limit","permission","malformed"].includes(i.reason)?i.reason:"malformed",T=Number.isInteger(i.status)&&(i.status??0)>=100&&(i.status??0)<=599?i.status:void 0;return m(c,T)}if(i.value===null||i.value===void 0)return m("missing");let y;try{y=k(s.resolve(i.value,a.fallback))}catch{return m("malformed")}return y.fallbackFields.includes("$")?m("invalid-field"):y.fallbackFields.length>0?(n({event:"cms.partial-fallback",query:s.name,reason:"invalid-field",fields:y.fallbackFields}),{...y,source:"mixed",reason:"invalid-field"}):{...y,source:"cms"}}}}var P=A;import{revalidateTag as F}from"next/cache.js";var R="sanity-webhook-signature",j=/^t=(\d+)[, ]+v1=([^, ]+)$/;var S=new TextEncoder;function z(e){return crypto.subtle.importKey("raw",S.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}function N(e){if(!/^[A-Za-z0-9_-]+={0,2}$/.test(e))return null;let r=e.replace(/-/g,"+").replace(/_/g,"/");try{let t=atob(r),n=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)n[o]=t.charCodeAt(o);return n}catch{return null}}async function O(e){let{secret:r,rawBody:t,headers:n}=e,o=e.now??Date.now(),a=e.toleranceMs??3e5;if(!r||r.length===0)return{ok:!1,reason:"no-secret"};let s=n.get(R);if(!s)return{ok:!1,reason:"no-signature"};let l=j.exec(s.trim());if(l===null)return{ok:!1,reason:"malformed-signature"};let d=Number(l[1]),m=l[2]??"";if(!Number.isSafeInteger(d))return{ok:!1,reason:"malformed-signature"};if(d<16094592e5)return{ok:!1,reason:"stale-timestamp"};if(Math.abs(o-d)>a)return{ok:!1,reason:"stale-timestamp"};let i=N(m);if(i===null)return{ok:!1,reason:"malformed-signature"};let y=await z(r);return await crypto.subtle.verify("HMAC",y,i,S.encode(`${d}.${t}`))?{ok:!0}:{ok:!1,reason:"bad-signature"}}var $=16*1024,U=1500,L=new TextEncoder;function u(e,r,t={},n=!1){return new Response(n?null:JSON.stringify(r),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...t}})}function H(e,r){if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length===0)throw new TypeError("Invalid CMS invalidation mapping");let t=Object.create(null);for(let n of Reflect.ownKeys(r)){let o=Object.getOwnPropertyDescriptor(r,n);if(typeof n!="string"||!o?.enumerable||!Object.hasOwn(o,"value"))throw new TypeError("Invalid CMS invalidation mapping");let a=o.value;if(!Array.isArray(a)||!a.includes(n))throw new TypeError("Invalid CMS invalidation mapping");b(e,{types:a,ids:["validation"]}),t[n]=Object.freeze([...a])}for(let n of Object.values(t))if(n.some(o=>!Object.hasOwn(t,o)))throw new TypeError("Invalid CMS invalidation mapping");return Object.freeze(t)}function I(e){return typeof e=="string"&&e.trim()!==""&&L.encode(e).byteLength>=32}var w=class extends Error{constructor(t){super("Invalid CMS webhook body");this.status=t}status};async function Z(e){let r=e.body?.getReader();if(!r)return"";let t=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),n,o=new Promise((a,s)=>{n=setTimeout(()=>s(new w(400)),U)});try{let a=0,s="";for(;;){let{done:l,value:d}=await Promise.race([r.read(),o]);if(l)return s+t.decode();if(a+=d.byteLength,a>$)throw new w(413);s+=t.decode(d,{stream:!0})}}catch(a){throw r.cancel().catch(()=>{}),a}finally{clearTimeout(n),r.releaseLock()}}function Q(e){let r=e.scope,t=H(r,e.typeToTags),n=e.secretEnv??"SANITY_REVALIDATE_SECRET",o=e.previousSecretEnv??"SANITY_REVALIDATE_SECRET_PREVIOUS",a=e.env??(()=>process.env),s=e.now??Date.now,l=async d=>{if(d.method!=="POST")return u(405,{error:"Method not allowed"},{Allow:"POST"},d.method==="HEAD");let m,i;try{let p=a(),C=p[n],g=p[o];if(!I(C)||g!==void 0&&!I(g))throw new Error;m=C,i=g}catch{return u(503,{error:"COULD NOT ANSWER: revalidation configuration unavailable"})}let y=d.headers.get(R);if(!y||y.length>512||!/^t=\d+[, ]+v1=[A-Za-z0-9_-]+={0,2}$/.test(y.trim()))return u(401,{error:"Unauthorized"});let f;try{f=await Z(d)}catch(p){return p instanceof w&&p.status===413?u(413,{error:"Payload too large"}):u(400,{error:"Invalid body"})}try{let p=s();if(!Number.isFinite(p))throw new Error;if(!(await Promise.all([m,...i===void 0?[]:[i]].map(g=>O({secret:g,rawBody:f,headers:d.headers,now:p})))).some(g=>g.ok))return u(401,{error:"Unauthorized"})}catch{return u(401,{error:"Unauthorized"})}let c;try{c=JSON.parse(f)}catch{return u(400,{error:"Invalid payload"})}if(!c||typeof c!="object"||Array.isArray(c)||Object.keys(c).length!==2||!Object.hasOwn(c,"_type")||!Object.hasOwn(c,"_id"))return u(400,{error:"Invalid payload"});let{_type:T,_id:v}=c;if(typeof T!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(T)||typeof v!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(v))return u(400,{error:"Invalid payload"});if(!Object.hasOwn(t,T)||/^(drafts|versions)\./.test(v))return u(400,{error:"Unsupported document"});let x=b(r,{types:t[T],ids:[v]});try{for(let p of x)F(p,{expire:0})}catch{return u(500,{error:"Could not revalidate"})}return u(200,{revalidated:!0})};return Object.freeze({POST:l,GET:l,HEAD:l,PUT:l,PATCH:l,DELETE:l,OPTIONS:l})}export{P as createNextCmsReader,Q as createRevalidateRoute};
|
|
2
|
+
//# sourceMappingURL=next.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/next.ts", "../src/contracts/query.ts", "../src/runtime/reader.ts", "../src/adapters/next/reader.ts", "../src/invalidation/route.ts", "../src/portable/webhook.ts"],
|
|
4
|
+
"sourcesContent": ["import \"server-only\";\nexport { createNextCmsReader } from \"./adapters/next/reader.js\";\nexport { createRevalidateRoute } from \"./invalidation/route.js\";\nexport type {\n TypeToTags, RevalidateRouteOptions, CmsRouteHandler, CmsRevalidateRoute,\n} from \"./invalidation/route.js\";\n", "/** A-1822 S1 owns this implementation. S0 registers the public signatures. */\nexport type CmsParams = Readonly<Record<string, string | number | boolean | null>>;\nexport type CmsDependencies = {\n readonly types: readonly string[];\n readonly ids?: readonly string[];\n};\nexport type CmsResolution<T> = {\n readonly data: T;\n readonly fallbackFields: readonly string[];\n};\nexport type CmsQuery<T> = {\n readonly name: string;\n readonly query: string;\n readonly params: CmsParams;\n readonly dependencies: CmsDependencies;\n readonly resolve: (raw: unknown, fallback: T) => CmsResolution<T>;\n};\n\nconst TYPE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;\nconst ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\nconst SCOPE = /^[a-z0-9]{6,12}\\.[a-z][a-z0-9_-]{0,63}$/;\n\nfunction dependenciesCopy(dependencies: CmsDependencies): CmsDependencies {\n if (!dependencies || !Array.isArray(dependencies.types) || dependencies.types.length === 0) {\n throw new TypeError(\"CMS dependencies require document types\");\n }\n const types = [...dependencies.types];\n for (const type of types) {\n if (typeof type !== \"string\" || !TYPE.test(type)) throw new TypeError(\"Invalid CMS document type\");\n }\n if (dependencies.ids !== undefined && !Array.isArray(dependencies.ids)) throw new TypeError(\"Invalid CMS document IDs\");\n const ids = dependencies.ids === undefined ? undefined : [...dependencies.ids];\n for (const id of ids ?? []) {\n if (typeof id !== \"string\" || !ID.test(id) || /^(drafts|versions)\\./.test(id)) {\n throw new TypeError(\"Invalid CMS document ID\");\n }\n }\n if (new Set(types).size + new Set(ids).size > 128) throw new TypeError(\"Too many CMS tags\");\n return Object.freeze({ types: Object.freeze(types), ...(ids === undefined ? {} : { ids: Object.freeze(ids) }) });\n}\n\nexport function defineCmsQuery<T>(query: CmsQuery<T>): CmsQuery<T> {\n if (!query || typeof query.name !== \"string\" || !/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(query.name)\n || typeof query.query !== \"string\" || query.query.trim() === \"\" || typeof query.resolve !== \"function\") {\n throw new TypeError(\"Invalid CMS query configuration\");\n }\n const params = query.params;\n if (!params || typeof params !== \"object\" || (Object.getPrototypeOf(params) !== Object.prototype && Object.getPrototypeOf(params) !== null)) {\n throw new TypeError(\"CMS params must be plain JSON scalars\");\n }\n const copied: Record<string, string | number | boolean | null> = {};\n for (const key of Reflect.ownKeys(params)) {\n const descriptor = Object.getOwnPropertyDescriptor(params, key);\n if (typeof key !== \"string\" || !descriptor || !Object.hasOwn(descriptor, \"value\") || !descriptor.enumerable) {\n throw new TypeError(\"CMS params must be plain JSON scalars\");\n }\n const value: unknown = descriptor.value;\n if (!(value === null || typeof value === \"string\" || typeof value === \"boolean\" || (typeof value === \"number\" && Number.isFinite(value)))) {\n throw new TypeError(\"CMS params must be plain JSON scalars\");\n }\n Object.defineProperty(copied, key, { value, enumerable: true });\n }\n return Object.freeze({ name: query.name, query: query.query, params: Object.freeze(copied), dependencies: dependenciesCopy(query.dependencies), resolve: query.resolve });\n}\n\nexport function cmsTags(scope: string, dependencies: CmsDependencies): readonly string[] {\n if (typeof scope !== \"string\" || scope.length > 77 || !SCOPE.test(scope)) throw new TypeError(\"Invalid CMS scope\");\n const copied = dependenciesCopy(dependencies);\n const tags = [\n ...[...new Set(copied.types)].sort().map((type) => `cms:${scope}:type:${type}`),\n ...[...new Set(copied.ids ?? [])].sort().map((id) => `cms:${scope}:id:${id}`),\n ];\n return Object.freeze(tags);\n}\n", "import { cmsTags, defineCmsQuery, type CmsQuery, type CmsResolution } from \"../contracts/query.js\";\n\nexport type CmsFailure = \"configuration\" | \"network\" | \"timeout\" | \"rate-limit\"\n | \"upstream\" | \"plan-limit\" | \"permission\" | \"malformed\";\nexport type CmsDiagnostic = {\n readonly event: \"cms.fallback\" | \"cms.partial-fallback\" | \"cms.refused\";\n readonly query: string;\n readonly reason: CmsFailure | \"missing\" | \"invalid-field\";\n readonly status?: number;\n readonly fields: readonly string[];\n};\nexport type CmsFetch = (url: string, init: RequestInit & {\n next?: { revalidate: number; tags: string[] };\n}) => Promise<Response>;\nexport type CmsReadPolicy = {\n readonly tags: readonly string[];\n readonly revalidateSeconds: number;\n};\nexport type CmsAdapterResult =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly reason: CmsFailure; readonly status?: number };\nexport type CmsAdapter = {\n readonly scope: string;\n read(query: Pick<CmsQuery<unknown>, \"name\" | \"query\" | \"params\">,\n policy: CmsReadPolicy): Promise<CmsAdapterResult>;\n};\nexport type CmsReadResult<T> = {\n readonly data: T;\n readonly source: \"cms\" | \"mixed\" | \"fallback\";\n readonly fallbackFields: readonly string[];\n readonly reason?: CmsFailure | \"missing\" | \"invalid-field\";\n};\nexport type CmsReaderOptions = {\n readonly adapter: CmsAdapter;\n readonly revalidateSeconds?: number;\n readonly onDiagnostic?: (event: CmsDiagnostic) => void;\n};\nexport type CmsReader = {\n read<T>(query: CmsQuery<T>, options: { readonly fallback: T }): Promise<CmsReadResult<T>>;\n};\n\nfunction resolution<T>(value: CmsResolution<T>): CmsResolution<T> {\n if (!value || !Object.hasOwn(value, \"data\") || !Array.isArray(value.fallbackFields)\n || ![...value.fallbackFields].every((field: unknown) => typeof field === \"string\"\n && (field === \"$\" || /^[A-Za-z][A-Za-z0-9_.[\\]-]{0,127}$/.test(field)))) {\n throw new TypeError(\"Invalid CMS resolution\");\n }\n return { data: value.data, fallbackFields: Object.freeze([...new Set(value.fallbackFields)]) };\n}\n\n/** Forwards cache policy; persistence and rendered-output invalidation belong to the host. */\nexport function createCmsReader(options: CmsReaderOptions): CmsReader {\n const seconds = options?.revalidateSeconds ?? 3600;\n if (!Number.isSafeInteger(seconds) || seconds < 3600 || !options?.adapter\n || typeof options.adapter.read !== \"function\"\n || (options.onDiagnostic !== undefined && typeof options.onDiagnostic !== \"function\")) {\n throw new TypeError(\"Invalid CMS reader configuration\");\n }\n const adapter = options.adapter;\n // Validate the scope without assuming any particular shared content types.\n cmsTags(adapter.scope, { types: [\"ScopeValidation\"] });\n const notify = (event: CmsDiagnostic): void => {\n try {\n if (options.onDiagnostic) options.onDiagnostic(event);\n else console.warn(JSON.stringify(event));\n } catch { /* Reporting must not break visitor rendering. */ }\n };\n return {\n async read<T>(input: CmsQuery<T>, readOptions: { readonly fallback: T }): Promise<CmsReadResult<T>> {\n let query: CmsQuery<T>;\n let local: CmsResolution<T>;\n let tags: readonly string[];\n try {\n query = defineCmsQuery(input);\n tags = cmsTags(adapter.scope, query.dependencies);\n if (!readOptions || !Object.hasOwn(readOptions, \"fallback\")) throw new TypeError();\n // Built-in resolvers validate fallback here, before any I/O.\n local = resolution(query.resolve(null, readOptions.fallback));\n } catch {\n throw new TypeError(\"Invalid CMS query or fallback configuration\");\n }\n const fallback = (reason: CmsFailure | \"missing\" | \"invalid-field\", status?: number): CmsReadResult<T> => {\n notify({ event: \"cms.fallback\", query: query.name, reason, fields: [\"$\"],\n ...(status === undefined ? {} : { status }) });\n return { data: local.data, source: \"fallback\", fallbackFields: [\"$\"], reason };\n };\n let result: CmsAdapterResult;\n try {\n result = await adapter.read({ name: query.name, query: query.query, params: query.params },\n { tags, revalidateSeconds: seconds });\n } catch { return fallback(\"network\"); }\n if (!result.ok) {\n const reasons: readonly CmsFailure[] = [\"configuration\", \"network\", \"timeout\", \"rate-limit\", \"upstream\", \"plan-limit\", \"permission\", \"malformed\"];\n const reason = reasons.includes(result.reason) ? result.reason : \"malformed\";\n const status = Number.isInteger(result.status) && (result.status ?? 0) >= 100 && (result.status ?? 0) <= 599 ? result.status : undefined;\n return fallback(reason, status);\n }\n if (result.value === null || result.value === undefined) return fallback(\"missing\");\n let resolved: CmsResolution<T>;\n try { resolved = resolution(query.resolve(result.value, readOptions.fallback)); }\n catch { return fallback(\"malformed\"); }\n if (resolved.fallbackFields.includes(\"$\")) return fallback(\"invalid-field\");\n if (resolved.fallbackFields.length > 0) {\n notify({ event: \"cms.partial-fallback\", query: query.name, reason: \"invalid-field\", fields: resolved.fallbackFields });\n return { ...resolved, source: \"mixed\", reason: \"invalid-field\" };\n }\n return { ...resolved, source: \"cms\" };\n },\n };\n}\n", "import { createCmsReader } from \"../../runtime/reader.js\";\n\n// Keep the adapter's patched global fetch and policy intact. No second cache.\nexport const createNextCmsReader = createCmsReader;\n", "import { revalidateTag } from \"next/cache.js\";\nimport { cmsTags } from \"../contracts/query.js\";\nimport { SANITY_SIGNATURE_HEADER, verifySanityWebhook } from \"../portable/webhook.js\";\n\nexport type TypeToTags = Readonly<Record<string, readonly string[]>>;\nexport type RevalidateRouteOptions = {\n readonly scope: string;\n readonly secretEnv?: string;\n readonly previousSecretEnv?: string;\n readonly typeToTags: TypeToTags;\n readonly env?: () => Readonly<Record<string, string | undefined>>;\n readonly now?: () => number;\n};\nexport type CmsRouteHandler = (request: Request) => Promise<Response>;\nexport type CmsRevalidateRoute = Readonly<Record<\n \"POST\" | \"GET\" | \"HEAD\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\", CmsRouteHandler\n>>;\n\nconst BODY_LIMIT = 16 * 1024;\nconst BODY_DEADLINE_MS = 1500;\nconst encoder = new TextEncoder();\n\nfunction response(status: number, value: unknown, headers: Record<string, string> = {}, head = false): Response {\n return new Response(head ? null : JSON.stringify(value), {\n status, headers: { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\", ...headers },\n });\n}\n\nfunction copyMapping(scope: string, mapping: TypeToTags): TypeToTags {\n if (!mapping || typeof mapping !== \"object\" || Array.isArray(mapping) || Object.keys(mapping).length === 0) {\n throw new TypeError(\"Invalid CMS invalidation mapping\");\n }\n const copied: Record<string, readonly string[]> = Object.create(null);\n for (const key of Reflect.ownKeys(mapping)) {\n const descriptor = Object.getOwnPropertyDescriptor(mapping, key);\n if (typeof key !== \"string\" || !descriptor?.enumerable || !Object.hasOwn(descriptor, \"value\")) {\n throw new TypeError(\"Invalid CMS invalidation mapping\");\n }\n const types: unknown = descriptor.value;\n if (!Array.isArray(types) || !types.includes(key)) throw new TypeError(\"Invalid CMS invalidation mapping\");\n // Reserve the document ID tag as well as validating every local type.\n cmsTags(scope, { types, ids: [\"validation\"] });\n copied[key] = Object.freeze([...types] as string[]);\n }\n for (const types of Object.values(copied)) {\n if (types.some((type) => !Object.hasOwn(copied, type))) throw new TypeError(\"Invalid CMS invalidation mapping\");\n }\n return Object.freeze(copied);\n}\n\nfunction validSecret(value: unknown): value is string {\n return typeof value === \"string\" && value.trim() !== \"\" && encoder.encode(value).byteLength >= 32;\n}\n\nclass BodyFailure extends Error {\n constructor(readonly status: 400 | 413) { super(\"Invalid CMS webhook body\"); }\n}\n\nasync function rawBody(request: Request): Promise<string> {\n const reader = request.body?.getReader();\n if (!reader) return \"\";\n const decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new BodyFailure(400)), BODY_DEADLINE_MS);\n });\n try {\n let bytes = 0;\n let text = \"\";\n while (true) {\n const { done, value } = await Promise.race([reader.read(), deadline]);\n if (done) return text + decoder.decode();\n bytes += value.byteLength;\n if (bytes > BODY_LIMIT) throw new BodyFailure(413);\n text += decoder.decode(value, { stream: true });\n }\n } catch (error) {\n // Cancellation must not extend the deadline, including a stalled source.\n void reader.cancel().catch(() => {});\n throw error;\n } finally {\n clearTimeout(timer);\n reader.releaseLock();\n }\n}\n\nexport function createRevalidateRoute(options: RevalidateRouteOptions): CmsRevalidateRoute {\n const scope = options.scope;\n const mapping = copyMapping(scope, options.typeToTags);\n const secretEnv = options.secretEnv ?? \"SANITY_REVALIDATE_SECRET\";\n const previousSecretEnv = options.previousSecretEnv ?? \"SANITY_REVALIDATE_SECRET_PREVIOUS\";\n const env = options.env ?? (() => process.env);\n const now = options.now ?? Date.now;\n\n const handler: CmsRouteHandler = async (request) => {\n if (request.method !== \"POST\") {\n return response(405, { error: \"Method not allowed\" }, { Allow: \"POST\" }, request.method === \"HEAD\");\n }\n let active: string;\n let previous: string | undefined;\n try {\n const values = env();\n const activeValue = values[secretEnv];\n const previousValue = values[previousSecretEnv];\n if (!validSecret(activeValue) || (previousValue !== undefined && !validSecret(previousValue))) throw new Error();\n active = activeValue;\n previous = previousValue;\n } catch {\n return response(503, { error: \"COULD NOT ANSWER: revalidation configuration unavailable\" });\n }\n const signature = request.headers.get(SANITY_SIGNATURE_HEADER);\n if (!signature || signature.length > 512 || !/^t=\\d+[, ]+v1=[A-Za-z0-9_-]+={0,2}$/.test(signature.trim())) {\n return response(401, { error: \"Unauthorized\" });\n }\n let body: string;\n try { body = await rawBody(request); }\n catch (error) {\n return error instanceof BodyFailure && error.status === 413\n ? response(413, { error: \"Payload too large\" }) : response(400, { error: \"Invalid body\" });\n }\n try {\n const clock = now();\n if (!Number.isFinite(clock)) throw new Error();\n const results = await Promise.all([active, ...(previous === undefined ? [] : [previous])].map((secret) =>\n verifySanityWebhook({ secret, rawBody: body, headers: request.headers, now: clock })));\n if (!results.some((result) => result.ok)) return response(401, { error: \"Unauthorized\" });\n } catch { return response(401, { error: \"Unauthorized\" }); }\n\n let payload: unknown;\n try { payload = JSON.parse(body); }\n catch { return response(400, { error: \"Invalid payload\" }); }\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)\n || Object.keys(payload).length !== 2 || !Object.hasOwn(payload, \"_type\") || !Object.hasOwn(payload, \"_id\")) {\n return response(400, { error: \"Invalid payload\" });\n }\n const { _type: type, _id: id } = payload as { _type: unknown; _id: unknown };\n if (typeof type !== \"string\" || !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(type)\n || typeof id !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(id)) {\n return response(400, { error: \"Invalid payload\" });\n }\n if (!Object.hasOwn(mapping, type) || /^(drafts|versions)\\./.test(id)) {\n return response(400, { error: \"Unsupported document\" });\n }\n const tags = cmsTags(scope, { types: mapping[type]!, ids: [id] });\n try {\n for (const tag of tags) revalidateTag(tag, { expire: 0 });\n } catch { return response(500, { error: \"Could not revalidate\" }); }\n return response(200, { revalidated: true });\n };\n return Object.freeze({ POST: handler, GET: handler, HEAD: handler, PUT: handler, PATCH: handler, DELETE: handler, OPTIONS: handler });\n}\n", "/**\n * Verifying a Sanity webhook (A-590 step 1, A-592's `SANITY_WEBHOOK_SECRET`).\n *\n * -------------------------------------------------------------------------\n * WHY THIS ENDPOINT NEEDS A SIGNATURE AT ALL\n * -------------------------------------------------------------------------\n *\n * `/revalidate` throws away cache entries. A-590: \"An unauthenticated\n * revalidation endpoint is a free cache-purge and rebuild trigger for anyone\n * who finds the URL.\" On a plan whose API request allowance is a HARD cap that\n * returns 402 rather than a bill, an attacker who can empty the cache at will\n * can take a client's site content-offline for the rest of the month. So the\n * signature is not hygiene here; it is the availability control.\n *\n * -------------------------------------------------------------------------\n * THE WIRE FORMAT IS MEASURED, NOT REMEMBERED\n * -------------------------------------------------------------------------\n *\n * Read on 2026-09-16 from Sanity's own toolkit,\n * `https://raw.githubusercontent.com/sanity-io/webhook-toolkit/main/src/signature.ts`:\n *\n * header `sanity-webhook-signature`\n * value `t=<millis>,v1=<signature>` (regex `/^t=(\\d+)[, ]+v1=([^, ]+)$/`)\n * signed payload `` `${timestamp}.${body}` ``\n * algorithm HMAC-SHA256\n * digest encoding base64url \u2014 standard base64 with `+`\u2192`-`, `/`\u2192`_`, padding stripped\n * MINIMUM_TIMESTAMP 1609459200000 (2021-01-01Z), below which a value is nonsense\n *\n * `signature.test.ts` does not take that paragraph's word for it either: it\n * signs a payload with `@sanity/webhook`'s own `encodeSignatureHeader` and\n * asserts this verifier accepts it. If Sanity changes the format, that test\n * goes red rather than production quietly rejecting every webhook.\n *\n * -------------------------------------------------------------------------\n * WHAT THIS ADDS TO THE TOOLKIT, AND WHY IT IS NOT JUST IMPORTED\n * -------------------------------------------------------------------------\n *\n * Two things, both of which are `CLAUDE.md`'s \"take the safer construction\".\n *\n * First, a REPLAY WINDOW. The toolkit enforces only that the timestamp is after\n * 2021; a captured webhook is otherwise replayable forever. A replayed purge is\n * the attack in the first paragraph, executed with a request somebody was\n * legitimately sent. `verifySanityWebhook` takes a symmetric tolerance \u2014 the\n * window is symmetric for A-44's reason, since a far-future timestamp is\n * precisely how you mint a request that stays replayable for a year.\n *\n * Second, a MISSING SECRET IS A REJECTION, never a bypass. A-590 says it in as\n * many words: \"reject on absence rather than skipping the check when the secret\n * is unset.\" The degraded mode of \"no secret configured, so allow it\" is\n * produced by a deploy that forgot `wrangler secret put`, announces itself\n * nowhere, and grants strangers the purge endpoint.\n *\n * The comparison is `crypto.subtle.verify`, which compares raw digests in\n * constant time. A `===` on the base64 strings short-circuits at the first\n * differing character, which turns one 2^256 search into a few dozen sequential\n * 64-way ones against an endpoint that answers in milliseconds.\n *\n * -------------------------------------------------------------------------\n * `encodeSignatureHeader` IS ASYNC. AWAIT IT. (A-651)\n * -------------------------------------------------------------------------\n *\n * `@sanity/webhook@4.0.4` declares\n *\n * encodeSignatureHeader(payload: string, timestamp: number, secret: string):\n * Promise<string>\n *\n * and nothing forces you to await it. Drop the `await` and the Promise is\n * stringified into the header as the literal `[object Promise]`, which arrives\n * here, fails `SIGNATURE_VALUE`, and is rejected as `malformed-signature`. The\n * rejection is correct and the message is about the wire format, so it sends\n * you to read Sanity's header spec \u2014 the one place the bug is not. TypeScript\n * does not save you either: the value usually lands in a `Record<string,\n * string>` built by a helper, or inside a template literal, both of which take\n * a Promise without complaint.\n *\n * The rule: every call to `encodeSignatureHeader` is awaited, and the helper\n * that wraps it is `async` rather than returning the Promise for someone else\n * to forget. The content-client compatibility tests and CMS signer tests await every\n * encoder call; this note exists so the next one\n * is too, because the symptom will not tell you.\n */\n\n/** Sanity's header. Lower-cased; `Headers.get` is case-insensitive either way. */\nexport const SANITY_SIGNATURE_HEADER = \"sanity-webhook-signature\";\n\n/** Sanity's own parser, character for character. See the header. */\nconst SIGNATURE_VALUE = /^t=(\\d+)[, ]+v1=([^, ]+)$/;\n\n/** 2021-01-01T00:00:00.000Z. Sanity's `MINIMUM_TIMESTAMP`; anything earlier is not a timestamp. */\nexport const MINIMUM_TIMESTAMP = 1_609_459_200_000;\n\n/**\n * How far from `now` a webhook timestamp may be, in milliseconds.\n *\n * Five minutes rather than A-44's sixty seconds: this one crosses Sanity's\n * delivery queue rather than two NTP-synced clouds, and a retried delivery is a\n * normal event. It is still a window rather than \"forever\", which is the whole\n * difference from the toolkit.\n */\nexport const DEFAULT_TOLERANCE_MS = 300_000;\n\nexport type WebhookRejection =\n /** `SANITY_WEBHOOK_SECRET` is unset or empty. Fail closed. */\n | \"no-secret\"\n /** No `sanity-webhook-signature` header. */\n | \"no-signature\"\n /** Header present but not `t=\u2026,v1=\u2026`, or `v1` is not decodable base64url. */\n | \"malformed-signature\"\n /** Before 2021, or outside the tolerance in either direction. */\n | \"stale-timestamp\"\n /** Well-formed, in window, wrong. */\n | \"bad-signature\";\n\nexport type WebhookVerification = { ok: true } | { ok: false; reason: WebhookRejection };\n\nconst encoder = new TextEncoder();\n\nfunction hmacKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\", \"verify\"],\n );\n}\n\n/**\n * base64url \u2192 bytes, without `Buffer`.\n *\n * `atob` rather than `node:crypto` or `Buffer` because this file is imported by\n * the Worker, and workerd has neither by default. Returns null rather than\n * throwing on rubbish, so a malformed header is a 401 and not a 500 \u2014 a\n * verifier that crashes on bad input is a verifier an attacker can use as a\n * denial of service.\n */\nfunction base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> | null {\n if (!/^[A-Za-z0-9_-]+={0,2}$/.test(value)) return null;\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n try {\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n } catch {\n return null;\n }\n}\n\n/**\n * Verify a Sanity webhook delivery.\n *\n * `rawBody` must be the bytes as received \u2014 `await request.text()`, never\n * `JSON.stringify(await request.json())`. A parse-and-restringify is not a\n * byte-for-byte round trip (key order, number formatting, whitespace) and one\n * byte changes the whole digest, so the symptom is every webhook failing after\n * a refactor that looked like tidying.\n *\n * The `reason` is for our logs and our tests. It is never returned to the\n * caller: \"your signature was fine but your clock is stale\" is the next step in\n * an attack, handed over free.\n */\nexport async function verifySanityWebhook(options: {\n secret: string | undefined;\n rawBody: string;\n headers: { get(name: string): string | null };\n now?: number;\n toleranceMs?: number;\n}): Promise<WebhookVerification> {\n const { secret, rawBody, headers } = options;\n const now = options.now ?? Date.now();\n const toleranceMs = options.toleranceMs ?? DEFAULT_TOLERANCE_MS;\n\n if (!secret || secret.length === 0) return { ok: false, reason: \"no-secret\" };\n\n const header = headers.get(SANITY_SIGNATURE_HEADER);\n if (!header) return { ok: false, reason: \"no-signature\" };\n\n const match = SIGNATURE_VALUE.exec(header.trim());\n if (match === null) return { ok: false, reason: \"malformed-signature\" };\n\n const timestamp = Number(match[1]);\n const provided = match[2] ?? \"\";\n if (!Number.isSafeInteger(timestamp)) return { ok: false, reason: \"malformed-signature\" };\n if (timestamp < MINIMUM_TIMESTAMP) return { ok: false, reason: \"stale-timestamp\" };\n if (Math.abs(now - timestamp) > toleranceMs) return { ok: false, reason: \"stale-timestamp\" };\n\n const signature = base64UrlToBytes(provided);\n if (signature === null) return { ok: false, reason: \"malformed-signature\" };\n\n const key = await hmacKey(secret);\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n key,\n signature,\n encoder.encode(`${timestamp}.${rawBody}`),\n );\n return valid ? { ok: true } : { ok: false, reason: \"bad-signature\" };\n}\n"],
|
|
5
|
+
"mappings": "AAAA,MAAO,cCkBP,IAAMA,EAAO,+BACPC,EAAK,qCACLC,EAAQ,0CAEd,SAASC,EAAiBC,EAAgD,CACxE,GAAI,CAACA,GAAgB,CAAC,MAAM,QAAQA,EAAa,KAAK,GAAKA,EAAa,MAAM,SAAW,EACvF,MAAM,IAAI,UAAU,yCAAyC,EAE/D,IAAMC,EAAQ,CAAC,GAAGD,EAAa,KAAK,EACpC,QAAWE,KAAQD,EACjB,GAAI,OAAOC,GAAS,UAAY,CAACN,EAAK,KAAKM,CAAI,EAAG,MAAM,IAAI,UAAU,2BAA2B,EAEnG,GAAIF,EAAa,MAAQ,QAAa,CAAC,MAAM,QAAQA,EAAa,GAAG,EAAG,MAAM,IAAI,UAAU,0BAA0B,EACtH,IAAMG,EAAMH,EAAa,MAAQ,OAAY,OAAY,CAAC,GAAGA,EAAa,GAAG,EAC7E,QAAWI,KAAMD,GAAO,CAAC,EACvB,GAAI,OAAOC,GAAO,UAAY,CAACP,EAAG,KAAKO,CAAE,GAAK,uBAAuB,KAAKA,CAAE,EAC1E,MAAM,IAAI,UAAU,yBAAyB,EAGjD,GAAI,IAAI,IAAIH,CAAK,EAAE,KAAO,IAAI,IAAIE,CAAG,EAAE,KAAO,IAAK,MAAM,IAAI,UAAU,mBAAmB,EAC1F,OAAO,OAAO,OAAO,CAAE,MAAO,OAAO,OAAOF,CAAK,EAAG,GAAIE,IAAQ,OAAY,CAAC,EAAI,CAAE,IAAK,OAAO,OAAOA,CAAG,CAAE,CAAG,C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AS,OAAO,GAAK,CAAC,OAAO,OAAOA,EAAS,KAAK,EACzG,OAAO/C,EAAS,IAAK,CAAE,MAAO,iBAAkB,CAAC,EAEnD,GAAM,CAAE,MAAOa,EAAM,IAAKmC,CAAG,EAAID,EACjC,GAAI,OAAOlC,GAAS,UAAY,CAAC,+BAA+B,KAAKA,CAAI,GACpE,OAAOmC,GAAO,UAAY,CAAC,qCAAqC,KAAKA,CAAE,EAC1E,OAAOhD,EAAS,IAAK,CAAE,MAAO,iBAAkB,CAAC,EAEnD,GAAI,CAAC,OAAO,OAAOO,EAASM,CAAI,GAAK,uBAAuB,KAAKmC,CAAE,EACjE,OAAOhD,EAAS,IAAK,CAAE,MAAO,sBAAuB,CAAC,EAExD,IAAMiD,EAAOrC,EAAQN,EAAO,CAAE,MAAOC,EAAQM,CAAI,EAAI,IAAK,CAACmC,CAAE,CAAE,CAAC,EAChE,GAAI,CACF,QAAWE,KAAOD,EAAME,EAAcD,EAAK,CAAE,OAAQ,CAAE,CAAC,CAC1D,MAAQ,CAAE,OAAOlD,EAAS,IAAK,CAAE,MAAO,sBAAuB,CAAC,CAAG,CACnE,OAAOA,EAAS,IAAK,CAAE,YAAa,EAAK,CAAC,CAC5C,EACA,OAAO,OAAO,OAAO,CAAE,KAAMkC,EAAS,IAAKA,EAAS,KAAMA,EAAS,IAAKA,EAAS,MAAOA,EAAS,OAAQA,EAAS,QAASA,CAAQ,CAAC,CACtI",
|
|
6
|
+
"names": ["TYPE", "ID", "SCOPE", "dependenciesCopy", "dependencies", "types", "type", "ids", "id", "defineCmsQuery", "query", "params", "copied", "key", "descriptor", "value", "cmsTags", "scope", "tags", "resolution", "value", "field", "createCmsReader", "options", "seconds", "adapter", "cmsTags", "notify", "event", "input", "readOptions", "query", "local", "tags", "defineCmsQuery", "fallback", "reason", "status", "result", "resolved", "createNextCmsReader", "createCmsReader", "revalidateTag", "SANITY_SIGNATURE_HEADER", "SIGNATURE_VALUE", "encoder", "hmacKey", "secret", "base64UrlToBytes", "value", "padded", "binary", "bytes", "i", "verifySanityWebhook", "options", "rawBody", "headers", "now", "toleranceMs", "header", "SANITY_SIGNATURE_HEADER", "match", "SIGNATURE_VALUE", "timestamp", "provided", "signature", "key", "BODY_LIMIT", "BODY_DEADLINE_MS", "encoder", "response", "status", "value", "headers", "head", "copyMapping", "scope", "mapping", "copied", "key", "descriptor", "types", "cmsTags", "type", "validSecret", "BodyFailure", "rawBody", "request", "reader", "decoder", "timer", "deadline", "_resolve", "reject", "bytes", "text", "done", "error", "createRevalidateRoute", "options", "secretEnv", "previousSecretEnv", "env", "now", "handler", "active", "previous", "values", "activeValue", "previousValue", "signature", "SANITY_SIGNATURE_HEADER", "body", "clock", "secret", "verifySanityWebhook", "result", "payload", "id", "tags", "tag", "revalidateTag"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type HomeContent, type PageContent, type SiteSettingsContent } from "./site-content.cjs";
|
|
2
|
+
export declare function validHomeFallback(value: unknown): value is HomeContent | null;
|
|
3
|
+
export declare function validPageFallback(value: unknown): value is PageContent | null;
|
|
4
|
+
export declare function validSettingsFallback(value: unknown): value is SiteSettingsContent | null;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type HomeContent, type PageContent, type SiteSettingsContent } from "./site-content.mjs";
|
|
2
|
+
export declare function validHomeFallback(value: unknown): value is HomeContent | null;
|
|
3
|
+
export declare function validPageFallback(value: unknown): value is PageContent | null;
|
|
4
|
+
export declare function validSettingsFallback(value: unknown): value is SiteSettingsContent | null;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type HomeContent, type PageContent, type SiteSettingsContent } from "./site-content.js";
|
|
2
|
+
export declare function validHomeFallback(value: unknown): value is HomeContent | null;
|
|
3
|
+
export declare function validPageFallback(value: unknown): value is PageContent | null;
|
|
4
|
+
export declare function validSettingsFallback(value: unknown): value is SiteSettingsContent | null;
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A-1713. The site content model, read: the home page, content pages and site
|
|
3
|
+
* settings, validated on read and returned in the shape a site's page
|
|
4
|
+
* composition consumes.
|
|
5
|
+
*
|
|
6
|
+
* ===========================================================================
|
|
7
|
+
* READ ONLY, BY CONSTRUCTION
|
|
8
|
+
* ===========================================================================
|
|
9
|
+
*
|
|
10
|
+
* A client site reads its content with a read-only token. All editing goes
|
|
11
|
+
* through the studio's dashboard, which writes to Sanity; nothing on a client
|
|
12
|
+
* site writes, and this module has no write path to call. It is handed a
|
|
13
|
+
* `ContentClient` (a `query` function) and nothing else.
|
|
14
|
+
*
|
|
15
|
+
* ===========================================================================
|
|
16
|
+
* VALIDATED ON READ, BECAUSE SANITY VALIDATION ONLY ADVISES
|
|
17
|
+
* ===========================================================================
|
|
18
|
+
*
|
|
19
|
+
* The schema's rules warn an editor; they do not refuse a publish, and
|
|
20
|
+
* anything writing over the API skips them entirely. So every document is
|
|
21
|
+
* checked here again, and a malformed one is refused BY NAME
|
|
22
|
+
* (`MalformedContentError`, code `malformed-content`) listing every problem
|
|
23
|
+
* with its path, rather than rendered half-empty. A page that renders with a
|
|
24
|
+
* missing headline and a page whose content is broken look identical to a
|
|
25
|
+
* visitor; a build that fails naming `hero.headline` does not.
|
|
26
|
+
*
|
|
27
|
+
* Absent is not malformed: `null` from `home()` means nobody has created the
|
|
28
|
+
* home page yet, and a site decides what to do about that.
|
|
29
|
+
*
|
|
30
|
+
* ===========================================================================
|
|
31
|
+
* THE SHAPE IT RETURNS
|
|
32
|
+
* ===========================================================================
|
|
33
|
+
*
|
|
34
|
+
* The INPUT shape of a site's composition schema (the reference build's
|
|
35
|
+
* frontmatter): a copy value is a plain string for the client's own words
|
|
36
|
+
* with no claim about their source, `{ text, copySource: "captured" }` for
|
|
37
|
+
* words claimed verbatim from the capture (the site checks every such claim
|
|
38
|
+
* against its capture evidence, so the claim must survive Sanity), and
|
|
39
|
+
* `{ text, copySource: "proposed" }` for studio-written words awaiting
|
|
40
|
+
* approval. All three round-trip exactly; a photo is its library slug; every key a block declares is
|
|
41
|
+
* present, `null` where there is nothing. So a site validates this with the
|
|
42
|
+
* same schema it validates its Markdown frontmatter with, and its components
|
|
43
|
+
* never know where the content came from.
|
|
44
|
+
*
|
|
45
|
+
* Mapping from the generic model to the composition's names:
|
|
46
|
+
*
|
|
47
|
+
* hero.headline / subline / lead hero.heading / subline / intro
|
|
48
|
+
* hero.photos[0], [1] hero.image, hero.inset
|
|
49
|
+
* hero.primaryAction / secondary... hero.cta / secondaryCta
|
|
50
|
+
* campaign (when shown) the FIRST block, kind `campaign`, and
|
|
51
|
+
* the page body (`# title` + its text)
|
|
52
|
+
* featureStoriesBlock kind `feature_stories`
|
|
53
|
+
* surfaceCardBlock kind `cta`
|
|
54
|
+
* accentBandBlock kind `accent_band`
|
|
55
|
+
* locationsBlock kind `locations` (jumpLink → anchor)
|
|
56
|
+
*
|
|
57
|
+
* Two places the composition cannot carry a proposed marker: a `cta` block's
|
|
58
|
+
* plain strings, and the campaign's title and body (which travel as Markdown).
|
|
59
|
+
* There the text is returned plain and the line is still listed in
|
|
60
|
+
* `proposedCopy`, which is the list a dashboard and a site both read for
|
|
61
|
+
* approval. Nothing is dropped silently.
|
|
62
|
+
*/
|
|
63
|
+
import { type CmsQuery } from "../contracts/query.cjs";
|
|
64
|
+
export type CopyInput = string | {
|
|
65
|
+
readonly text: string;
|
|
66
|
+
readonly copySource: "captured" | "proposed";
|
|
67
|
+
};
|
|
68
|
+
export type ActionInput = {
|
|
69
|
+
readonly label: CopyInput;
|
|
70
|
+
readonly href: string;
|
|
71
|
+
};
|
|
72
|
+
export type HeroInput = {
|
|
73
|
+
readonly heading: CopyInput;
|
|
74
|
+
readonly subline: CopyInput | null;
|
|
75
|
+
readonly intro: CopyInput | null;
|
|
76
|
+
readonly image: string | null;
|
|
77
|
+
readonly inset: string | null;
|
|
78
|
+
readonly cta: ActionInput | null;
|
|
79
|
+
readonly secondaryCta: ActionInput | null;
|
|
80
|
+
};
|
|
81
|
+
export type StoryInput = {
|
|
82
|
+
readonly heading: CopyInput;
|
|
83
|
+
readonly body: CopyInput;
|
|
84
|
+
readonly action: ActionInput;
|
|
85
|
+
readonly image: string | null;
|
|
86
|
+
readonly shape: "wide" | "tall" | "round" | "free";
|
|
87
|
+
readonly card: boolean;
|
|
88
|
+
};
|
|
89
|
+
export type CompositionBlockInput = {
|
|
90
|
+
readonly kind: "campaign";
|
|
91
|
+
readonly action: ActionInput | null;
|
|
92
|
+
readonly images: readonly string[];
|
|
93
|
+
} | {
|
|
94
|
+
readonly kind: "locations";
|
|
95
|
+
readonly anchor: string | null;
|
|
96
|
+
readonly heading: CopyInput;
|
|
97
|
+
readonly tail: CopyInput | null;
|
|
98
|
+
readonly image: string | null;
|
|
99
|
+
} | {
|
|
100
|
+
readonly kind: "feature_stories";
|
|
101
|
+
readonly heading: CopyInput;
|
|
102
|
+
readonly tail: CopyInput | null;
|
|
103
|
+
readonly items: readonly StoryInput[];
|
|
104
|
+
} | {
|
|
105
|
+
readonly kind: "accent_band";
|
|
106
|
+
readonly heading: CopyInput;
|
|
107
|
+
readonly body: CopyInput;
|
|
108
|
+
readonly action: ActionInput | null;
|
|
109
|
+
readonly image: string | null;
|
|
110
|
+
} | {
|
|
111
|
+
readonly kind: "cta";
|
|
112
|
+
readonly heading: string;
|
|
113
|
+
readonly body: string | null;
|
|
114
|
+
readonly link: {
|
|
115
|
+
readonly label: string;
|
|
116
|
+
readonly href: string;
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
export type CompositionInput = {
|
|
120
|
+
readonly intro: string | null;
|
|
121
|
+
readonly photo: string | null;
|
|
122
|
+
readonly hero: HeroInput | null;
|
|
123
|
+
readonly blocks: readonly CompositionBlockInput[];
|
|
124
|
+
};
|
|
125
|
+
/** One line of studio-written copy awaiting approval, and where it is in the document. */
|
|
126
|
+
export type ProposedCopy = {
|
|
127
|
+
readonly where: string;
|
|
128
|
+
readonly text: string;
|
|
129
|
+
};
|
|
130
|
+
export type CampaignState = "shown" | "off" | "not-started" | "ended" | "none";
|
|
131
|
+
export type HomeContent = {
|
|
132
|
+
readonly composition: CompositionInput;
|
|
133
|
+
/** The page body as Markdown: the campaign's title and text when it is shown, otherwise empty. */
|
|
134
|
+
readonly body: string;
|
|
135
|
+
readonly campaign: CampaignState;
|
|
136
|
+
readonly proposedCopy: readonly ProposedCopy[];
|
|
137
|
+
};
|
|
138
|
+
export type PageContent = {
|
|
139
|
+
readonly slug: string;
|
|
140
|
+
readonly title: string;
|
|
141
|
+
readonly composition: CompositionInput;
|
|
142
|
+
readonly body: string;
|
|
143
|
+
readonly migrated: boolean;
|
|
144
|
+
readonly proposedCopy: readonly ProposedCopy[];
|
|
145
|
+
};
|
|
146
|
+
export type SiteSettingsContent = {
|
|
147
|
+
readonly name: string;
|
|
148
|
+
readonly description: string | null;
|
|
149
|
+
readonly contact: {
|
|
150
|
+
readonly email: string | null;
|
|
151
|
+
readonly phone: string | null;
|
|
152
|
+
};
|
|
153
|
+
readonly social: readonly {
|
|
154
|
+
readonly network: string;
|
|
155
|
+
readonly url: string;
|
|
156
|
+
}[];
|
|
157
|
+
};
|
|
158
|
+
export declare const MALFORMED_CONTENT = "malformed-content";
|
|
159
|
+
export declare class MalformedContentError extends Error {
|
|
160
|
+
readonly code = "malformed-content";
|
|
161
|
+
readonly documentId: string;
|
|
162
|
+
readonly problems: readonly string[];
|
|
163
|
+
constructor(documentId: string, problems: readonly string[]);
|
|
164
|
+
}
|
|
165
|
+
export declare const READER_PHOTO_SLUG: RegExp;
|
|
166
|
+
export declare const READER_ACTION_HREF: RegExp;
|
|
167
|
+
export declare const READER_JUMP_LINK: RegExp;
|
|
168
|
+
export declare const READER_STORY_LAYOUTS: readonly ["wide", "tall", "round", "free"];
|
|
169
|
+
export declare const READER_HOME_PAGE_ID = "homePage";
|
|
170
|
+
export declare const READER_SITE_SETTINGS_ID = "siteSettings";
|
|
171
|
+
/**
|
|
172
|
+
* The narrow Portable Text `portableText` declares, back to Markdown: normal,
|
|
173
|
+
* h2, h3 and quote blocks, bullet and numbered lists, bold, italic, code and
|
|
174
|
+
* links. It is the inverse of the seed package's Markdown mapper, and the
|
|
175
|
+
* round-trip test holds the two to each other.
|
|
176
|
+
*
|
|
177
|
+
* An uploaded image inside rich text is REFUSED, not dropped: nothing can
|
|
178
|
+
* upload one yet (the dashboard slice decides how), so one arriving means
|
|
179
|
+
* something wrote the document by hand, and a page silently missing a picture
|
|
180
|
+
* is the failure this reader exists to prevent.
|
|
181
|
+
*/
|
|
182
|
+
export declare function portableTextToMarkdown(value: unknown): string;
|
|
183
|
+
/** Whether a campaign is shown at `now`, and if not, why not. */
|
|
184
|
+
export declare function campaignState(campaign: unknown, now: Date): CampaignState;
|
|
185
|
+
/**
|
|
186
|
+
* A stored home page document, validated and mapped. Throws
|
|
187
|
+
* `MalformedContentError` naming every problem. `now` decides whether a
|
|
188
|
+
* scheduled campaign is shown, and is a parameter so a build, a preview and a
|
|
189
|
+
* test each say which moment they mean.
|
|
190
|
+
*/
|
|
191
|
+
export declare function parseHomePage(document: unknown, options: {
|
|
192
|
+
readonly now: Date;
|
|
193
|
+
}): HomeContent;
|
|
194
|
+
export declare function parseContentPage(document: unknown): PageContent;
|
|
195
|
+
export declare function parseSiteSettings(document: unknown): SiteSettingsContent;
|
|
196
|
+
/** By fixed id: a second home page at a random id is never read. */
|
|
197
|
+
export declare const HOME_PAGE_DOCUMENT_QUERY = "*[_id == $id][0]";
|
|
198
|
+
export declare const CONTENT_PAGES_QUERY = "*[_type == \"page\" && defined(slug.current)]|order(slug.current asc)";
|
|
199
|
+
export declare const CONTENT_PAGE_BY_SLUG_QUERY = "*[_type == \"page\" && slug.current == $slug][0]";
|
|
200
|
+
export interface SiteContentReader {
|
|
201
|
+
/** `null` when no home page document exists yet. */
|
|
202
|
+
home: (options: {
|
|
203
|
+
readonly now: Date;
|
|
204
|
+
}) => Promise<HomeContent | null>;
|
|
205
|
+
pages: () => Promise<PageContent[]>;
|
|
206
|
+
/** `null` when no page has that slug. */
|
|
207
|
+
pageBySlug: (slug: string) => Promise<PageContent | null>;
|
|
208
|
+
/** `null` before anyone has filled in the site's details. */
|
|
209
|
+
siteSettings: () => Promise<SiteSettingsContent | null>;
|
|
210
|
+
}
|
|
211
|
+
export declare function createSiteContentReader(client: {
|
|
212
|
+
query: <T>(groq: string, options?: {
|
|
213
|
+
params?: Record<string, unknown>;
|
|
214
|
+
tags?: readonly string[];
|
|
215
|
+
}) => Promise<T>;
|
|
216
|
+
}): SiteContentReader;
|
|
217
|
+
export declare function homeContentQuery(now: Date): CmsQuery<HomeContent | null>;
|
|
218
|
+
export declare function contentPageQuery(slug: string): CmsQuery<PageContent | null>;
|
|
219
|
+
export declare function contentPagesQuery(): CmsQuery<readonly PageContent[]>;
|
|
220
|
+
export declare function siteSettingsQuery(): CmsQuery<SiteSettingsContent | null>;
|