1 import { sanityClient } from "./sanity-client"
2 import {
3 Block,
4 FeatureTableFields,
5 HeroPricingFields,
6 PricingQueryResult,
7 } from "./types"
8
9 type PricingButtonLink =
10 HeroPricingFields["options"][number]["buttons"][number]["link"]
11
12 type PricingData = {
13 heroPricing: HeroPricingFields
14 featureTable: FeatureTableFields
15 }
16
17 export const featureLinks: Record<string, string> = {
18 orders: "/resources/commerce-modules/order",
19 products: "/resources/commerce-modules/product",
20 "sales channels": "/resources/commerce-modules/sales-channels",
21 "regions & currencies": "/resources/commerce-modules/region",
22 "github integration":
23 "/cloud/projects#2-create-project-from-an-existing-application",
24 "push-to-deploy flow": "/cloud/deployments#how-are-deployments-created",
25 previews: "/cloud/environments/preview",
26 "auto configuration:":
27 "/cloud/projects#prerequisite-medusa-application-configurations",
28 postgres: "/cloud/database",
29 redis: "/cloud/redis",
30 s3: "/cloud/s3",
31 "environment variables": "/cloud/environments/environment-variables",
32 "data import/export": "/cloud/database#importexport-database-dumps",
33 "advanced logs": "/cloud/logs",
34 "unlimited long-lived environments": "/cloud/environments/long-lived",
35 "long-lived environments (lle)": "/cloud/environments/long-lived",
36 "preview environments (pe)": "/cloud/environments/preview",
37 "cloud seats": "/cloud/organizations#view-organization-members",
38 "object storage": "/cloud/s3",
39 "database storage": "/cloud/database",
40 "key value store": "/cloud/redis",
41 "admin dashboard users": "/user-guide/settings/users",
42 "unlimited deployments": "/cloud/deployments",
43 "traffic load balancing": "/cloud/comparison#auto-scaling",
44 "log retention": "/cloud/logs",
45 "real-time 24/7 monitoring": "/cloud/comparison#high-availability",
46 "zero-downtime deployment": "/cloud/deployments",
47 backups: "/cloud/database#cloud-database-backups",
48 "performance tuning": "/cloud/comparison#performance",
49 "sla-backed uptime": "/cloud/comparison#high-availability",
50 support: "/cloud/comparison#support",
51 "medusa cache": "/cloud/cache",
52 "hosting of monorepos": "/cloud/projects/prerequisites#monorepo-setup",
53 "custom domains": "/cloud/storefront#storefront-custom-domain",
54 "storefront previews": "/cloud/environments/preview",
55 "mcp server": "/learn/introduction/build-with-llms-ai/docs-mcp-server",
56 "development agent": "/cloud/assistant",
57 "medusa cloud cli": "/cloud/cli",
58 "webhook events": "/cloud/webhooks/events",
59 "log drains": "/cloud/projects/log-drains",
60 "use with starters": "/cloud/projects#1-create-project-from-a-starter",
61 "custom backend domain": "/cloud/environments/custom-domains",
62 "pre configured caching": "/cloud/cache",
63 "integrated querying": "/learn/fundamentals/query#cache-query-results",
64 "auto invalidation":
65 "/resources/infrastructure-modules/caching/concepts#automatic-cache-invalidation",
66 "full-text search": "/resources/infrastructure-modules/search",
67 "typo-tolerant": "/cloud/search/settings#typo-tolerance",
68 "faceting and filtering":
69 "/resources/infrastructure-modules/search/index-definitions/modifiers",
70 "auto index sync": "/resources/infrastructure-modules/search/reindexing",
71 "instantsearch-compatible": "/resources/instantsearch",
72 "search analytics": "/cloud/search/analytics",
73 "semantic and hybrid search": "/cloud/search/semantic-search",
74 "managed embeddings": "/cloud/search/semantic-search#index-the-text-to-embed",
75 "built-in emails": "/cloud/emails",
76 "delivery insights": "/cloud/emails#monitor-email-sending-activity-on-cloud",
77 "open tracking": "/cloud/emails#monitor-email-sending-activity-on-cloud",
78 "bounce details": "/cloud/emails#monitor-email-sending-activity-on-cloud",
79 }
80
81 /**
82 * Whether the pricing data can be loaded. The pricing data isn't available in
83 * the CI and preview environments.
84 */
85 export function isPricingAvailable(): boolean {
86 return (
87 process.env.NEXT_PUBLIC_ENV !== "CI" &&
88 process.env.NEXT_PUBLIC_ENV !== "preview" &&
89 process.env.NEXT_PUBLIC_VERCEL_ENV !== "preview"
90 )
91 }
92
93 /**
94 * Loads the plans and the plans' features from Sanity, or `null` when either
95 * is missing.
96 */
97 export async function loadPricingData(): Promise<PricingData | null> {
98 const data: PricingQueryResult = await sanityClient.fetch(
99 `*[
100 (_type == "featureTable" && _id == "9cb4e359-786a-4cdb-9334-88ad4ce44f05") ||
101 (_type == "heroPricing" && _id == "8d8f33e1-7f18-4b2f-8686-5bc57da697db")
102 ]{
103 _type,
104 _id,
105 // For featureTable
106 "featureTableFields": select(
107 _type == "featureTable" => {
108 columnHeaders,
109 featureSections,
110 links
111 }
112 ),
113 // For heroPricing
114 "heroPricingFields": select(
115 _type == "heroPricing" => {
116 options
117 }
118 )
119 }`
120 )
121
122 const heroPricing = data.find(
123 (item) => item._type === "heroPricing"
124 )?.heroPricingFields
125 const featureTable = data.find(
126 (item) => item._type === "featureTable"
127 )?.featureTableFields
128
129 if (!heroPricing || !featureTable) {
130 return null
131 }
132
133 return { heroPricing, featureTable }
134 }
135
136 export function getPricingButtonUrl(link: PricingButtonLink): string {
137 return (
138 link.url ||
139 (link.path?.startsWith("https://")
140 ? link.path
141 : `https://medusajs.com${link.path}`)
142 )
143 }
144
145 /**
146 * Returns the text lines of a feature table cell, with known feature names
147 * linked to their documentation pages. Tooltips are returned as empty lines
148 * unless `includeTooltips` is enabled.
149 */
150 export function getBlockLines(
151 blocks: Block[],
152 baseUrl: string,
153 { includeTooltips = false }: { includeTooltips?: boolean } = {}
154 ): string[] {
155 if (!blocks?.length) {
156 return []
157 }
158
159 return blocks.flatMap((block) => {
160 if (block._type !== "block" || !block.children) {
161 return []
162 }
163
164 return block.children.map((child) => {
165 if (child._type !== "span") {
166 return includeTooltips ? `_${child.text.trim()}_` : ""
167 }
168
169 const text = child.text.trim()
170 const link = featureLinks[text.toLowerCase()]
171
172 return link ? `[${text}](${baseUrl}${link})` : text
173 })
174 })
175 }
176
177 const escapeTableCell = (value: string) =>
178 value.replaceAll("|", "\\|").replaceAll("\n", " ")
179
180 const toTableRow = (cells: string[]) =>
181 `| ${cells.map(escapeTableCell).join(" | ")} |`
182
183 function getPlansMarkdown(heroPricing: HeroPricingFields): string {
184 return heroPricing.options
185 .map((option) => {
186 const parts = [`### ${option.title}`, `**${option.subtitle}**`]
187
188 if (option.description) {
189 parts.push(option.description)
190 }
191
192 if (option.pre_features) {
193 parts.push(option.pre_features)
194 }
195
196 if (option.features.length) {
197 parts.push(option.features.map((feature) => `- ${feature}`).join("\n"))
198 }
199
200 if (option.buttons.length) {
201 parts.push(
202 option.buttons
203 .map(
204 (button) =>
205 `[${button.link.label}](${getPricingButtonUrl(button.link)})`
206 )
207 .join(" · ")
208 )
209 }
210
211 return parts.join("\n\n")
212 })
213 .join("\n\n")
214 }
215
216 function getFeaturesMarkdown(
217 featureTable: FeatureTableFields,
218 baseUrl: string
219 ): string {
220 const { columnHeaders, featureSections } = featureTable
221 const tableHeader = [
222 toTableRow(["Feature", ...columnHeaders]),
223 toTableRow(["Feature", ...columnHeaders].map(() => "---")),
224 ]
225
226 return featureSections
227 .map((section) => {
228 const rows = section.rows.map((row) =>
229 toTableRow(
230 Array.from({ length: columnHeaders.length + 1 }, (_, index) => {
231 const blocks = row[`column${index + 1}` as keyof typeof row]
232
233 return getBlockLines(blocks as Block[], baseUrl, {
234 includeTooltips: true,
235 })
236 .join("<br />")
237 .replace(/(<br \/>)+$/, "")
238 })
239 )
240 )
241
242 return [
243 `### ${section.header.subtitle}`,
244 section.header.title,
245 [...tableHeader, ...rows].join("\n"),
246 ]
247 .filter(Boolean)
248 .join("\n\n")
249 })
250 .join("\n\n")
251 }
252
253 /**
254 * Builds the Markdown version of the pricing page's content, used by the
255 * `md-content` route to replace the `<PricingContent />` component with the
256 * plans and features it renders. Returns an empty string when the pricing
257 * data isn't available.
258 */
259 export async function getPricingMarkdown(baseUrl: string): Promise<string> {
260 if (!isPricingAvailable()) {
261 return ""
262 }
263
264 const data = await loadPricingData()
265
266 if (!data) {
267 return ""
268 }
269
270 return [
271 "## Cloud Plans",
272 getPlansMarkdown(data.heroPricing),
273 "---",
274 "## Plans Features",
275 getFeaturesMarkdown(data.featureTable, baseUrl),
276 ].join("\n\n")
277 }