File size: 11,448 Bytes
391c43e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { PublishSettings } from '../vfs/types';
import { generateTrackingScript } from '../analytics/tracking-script';
import { generateConsentBanner } from './consent-banner';

export interface HtmlProcessingOptions {
  publishSettings: PublishSettings;
  projectId: string;
  baseUrl: string;
  deploymentId: string;
  hasEdgeFunctions?: boolean;
}

/**
 * Injects scripts, CDN links, SEO meta tags, analytics, and compliance banner into HTML
 *
 * Note: Under construction mode is handled separately by serving a dedicated page,
 * not by overlaying content
 */
export function processHtml(html: string, options: HtmlProcessingOptions): string {
  const { publishSettings, projectId, baseUrl, deploymentId, hasEdgeFunctions } = options;

  let processed = html;

  // 1. Inject SEO meta tags into <head>
  processed = injectSeoMetaTags(processed, publishSettings, baseUrl);

  // 2. Inject CDN links into <head>
  processed = injectCdnLinks(processed, publishSettings);

  // 3. Inject head scripts into <head>
  processed = injectHeadScripts(processed, publishSettings);

  // 4. Inject edge function interceptor into <head> (only if project has edge functions)
  if (hasEdgeFunctions) {
    processed = injectEdgeFunctionInterceptor(processed, deploymentId);
  }

  // 5. Inject body scripts before </body>
  processed = injectBodyScripts(processed, publishSettings);

  // 6. Inject analytics tracking (if enabled and builtin)
  processed = injectAnalytics(processed, deploymentId, publishSettings);

  // 7. Inject compliance banner (if enabled)
  processed = injectComplianceBanner(processed, deploymentId, publishSettings);

  return processed;
}

/**
 * Injects SEO meta tags into <head>
 */
function injectSeoMetaTags(html: string, settings: PublishSettings, baseUrl: string): string {
  const { seo } = settings;
  if (!seo || Object.keys(seo).length === 0) {
    return html;
  }

  const metaTags: string[] = [];

  // Basic meta tags
  if (seo.title) {
    metaTags.push(`<title>${escapeHtml(seo.title)}</title>`);
    metaTags.push(`<meta property="og:title" content="${escapeHtml(seo.title)}">`);
    metaTags.push(`<meta name="twitter:title" content="${escapeHtml(seo.title)}">`);
  }

  if (seo.description) {
    metaTags.push(`<meta name="description" content="${escapeHtml(seo.description)}">`);
    metaTags.push(`<meta property="og:description" content="${escapeHtml(seo.description)}">`);
    metaTags.push(`<meta name="twitter:description" content="${escapeHtml(seo.description)}">`);
  }

  if (seo.keywords && seo.keywords.length > 0) {
    metaTags.push(`<meta name="keywords" content="${escapeHtml(seo.keywords.join(', '))}">`);
  }

  // Open Graph
  if (seo.ogImage) {
    metaTags.push(`<meta property="og:image" content="${escapeHtml(seo.ogImage)}">`);
    metaTags.push(`<meta name="twitter:image" content="${escapeHtml(seo.ogImage)}">`);
  }

  metaTags.push(`<meta property="og:url" content="${escapeHtml(baseUrl)}">`);
  metaTags.push(`<meta property="og:type" content="website">`);

  // Twitter Card
  metaTags.push(`<meta name="twitter:card" content="summary_large_image">`);

  // Canonical URL
  if (seo.canonical) {
    metaTags.push(`<link rel="canonical" href="${escapeHtml(seo.canonical)}">`);
  }

  // Robots directives
  const robotsDirectives: string[] = [];
  if (seo.noIndex) robotsDirectives.push('noindex');
  if (seo.noFollow) robotsDirectives.push('nofollow');
  if (robotsDirectives.length > 0) {
    metaTags.push(`<meta name="robots" content="${robotsDirectives.join(', ')}">`);
  }

  // Inject into <head>
  return injectIntoHead(html, metaTags.join('\n    '));
}

/**
 * Injects CDN links (CSS and JS) into <head>
 */
function injectCdnLinks(html: string, settings: PublishSettings): string {
  const enabledCdnLinks = settings.cdnLinks.filter(cdn => cdn.enabled);
  if (enabledCdnLinks.length === 0) {
    return html;
  }

  const links: string[] = [];

  for (const cdn of enabledCdnLinks) {
    if (cdn.type === 'css') {
      links.push(`<link rel="stylesheet" href="${escapeHtml(cdn.url)}" ${cdn.integrity ? `integrity="${escapeHtml(cdn.integrity)}"` : ''} crossorigin="anonymous">`);
    } else if (cdn.type === 'js') {
      links.push(`<script src="${escapeHtml(cdn.url)}" ${cdn.integrity ? `integrity="${escapeHtml(cdn.integrity)}"` : ''} crossorigin="anonymous"></script>`);
    }
  }

  return injectIntoHead(html, links.join('\n    '));
}

/**
 * Injects head scripts into <head>
 */
function injectHeadScripts(html: string, settings: PublishSettings): string {
  const enabledHeadScripts = settings.headScripts.filter(script => script.enabled);
  if (enabledHeadScripts.length === 0) {
    return html;
  }

  const scripts: string[] = [];

  for (const script of enabledHeadScripts) {
    if (script.type === 'inline') {
      scripts.push(`<script>\n${script.content}\n</script>`);
    } else if (script.type === 'external') {
      scripts.push(`<script src="${escapeHtml(script.src!)}" ${script.async ? 'async' : ''} ${script.defer ? 'defer' : ''}></script>`);
    }
  }

  return injectIntoHead(html, scripts.join('\n    '));
}

/**
 * Injects body scripts before </body>
 */
function injectBodyScripts(html: string, settings: PublishSettings): string {
  const enabledBodyScripts = settings.bodyScripts.filter(script => script.enabled);
  if (enabledBodyScripts.length === 0) {
    return html;
  }

  const scripts: string[] = [];

  for (const script of enabledBodyScripts) {
    if (script.type === 'inline') {
      scripts.push(`<script>\n${script.content}\n</script>`);
    } else if (script.type === 'external') {
      scripts.push(`<script src="${escapeHtml(script.src!)}" ${script.async ? 'async' : ''} ${script.defer ? 'defer' : ''}></script>`);
    }
  }

  const bodyCloseTag = '</body>';
  const bodyCloseIndex = html.lastIndexOf(bodyCloseTag);

  if (bodyCloseIndex === -1) {
    // No </body> tag, append at the end
    return html + '\n' + scripts.join('\n') + '\n';
  }

  return (
    html.slice(0, bodyCloseIndex) +
    '    ' + scripts.join('\n    ') + '\n' +
    html.slice(bodyCloseIndex)
  );
}

/**
 * Helper to inject content into <head>
 */
function injectIntoHead(html: string, content: string): string {
  const headCloseTag = '</head>';
  const headCloseIndex = html.indexOf(headCloseTag);

  if (headCloseIndex === -1) {
    // No </head> tag, try to inject after <head> or at the beginning
    const headOpenTag = '<head>';
    const headOpenIndex = html.indexOf(headOpenTag);
    if (headOpenIndex !== -1) {
      return (
        html.slice(0, headOpenIndex + headOpenTag.length) +
        '\n    ' + content + '\n' +
        html.slice(headOpenIndex + headOpenTag.length)
      );
    }
    // No <head> at all, prepend
    return content + '\n' + html;
  }

  return (
    html.slice(0, headCloseIndex) +
    '    ' + content + '\n' +
    html.slice(headCloseIndex)
  );
}

/**
 * Inject analytics tracking script (if enabled and provider is builtin)
 */
function injectAnalytics(html: string, deploymentId: string, settings: PublishSettings): string {
  if (!settings.analytics.enabled || settings.analytics.provider !== 'builtin') {
    return html;
  }

  // Get analytics config with token and features
  const { analytics } = settings;
  const trackingOptions = {
    deploymentId: deploymentId,
    token: analytics.token,
    features: {
      basicTracking: analytics.features?.basicTracking !== false, // Default to true
      heatmaps: analytics.features?.heatmaps === true,
      sessionRecording: analytics.features?.sessionRecording === true,
      performanceMetrics: analytics.features?.performanceMetrics === true,
      engagementTracking: analytics.features?.engagementTracking === true,
      customEvents: analytics.features?.customEvents === true,
    },
  };

  // If compliance is enabled and blocks analytics, wrap in consent check
  if (settings.compliance.enabled && settings.compliance.blockAnalytics) {
    const wrappedScript = `
<script>
if (!window.oswAnalyticsBlocked) {
  ${generateTrackingScript(trackingOptions).replace(/<\/?script>/g, '')}
}
</script>
    `.trim();

    return injectBeforeBodyClose(html, wrappedScript);
  }

  // Otherwise, inject directly
  const trackingScript = generateTrackingScript(trackingOptions);
  return injectBeforeBodyClose(html, trackingScript);
}

/**
 * Inject compliance/consent banner (if enabled)
 */
function injectComplianceBanner(html: string, deploymentId: string, settings: PublishSettings): string {
  if (!settings.compliance.enabled) {
    return html;
  }

  const banner = generateConsentBanner({
    deploymentId,
    compliance: settings.compliance,
  });

  return injectBeforeBodyClose(html, banner);
}

/**
 * Helper to inject content before </body>
 */
function injectBeforeBodyClose(html: string, content: string): string {
  const bodyCloseTag = '</body>';
  const bodyCloseIndex = html.lastIndexOf(bodyCloseTag);

  if (bodyCloseIndex === -1) {
    // No </body> tag, append at the end
    return html + '\n' + content + '\n';
  }

  return (
    html.slice(0, bodyCloseIndex) +
    content + '\n' +
    html.slice(bodyCloseIndex)
  );
}

/**
 * Inject edge function interceptor script into <head>
 * Routes fetch/form requests to edge function API endpoints
 */
function injectEdgeFunctionInterceptor(html: string, deploymentId: string): string {
  if (!deploymentId) {
    return html;
  }

  // Minified interceptor script for production
  const interceptorScript = `<script>
(function(){var s="${deploymentId}";function e(u){if(!u||typeof u!=="string")return false;if(u.startsWith("http://")||u.startsWith("https://")||u.startsWith("blob:")||u.startsWith("data:")||u.startsWith("//")||u.startsWith("#"))return false;if(u.startsWith("/api/"))return false;var p=u.split("?")[0].split("#")[0];var l=p.split("/").pop()||"";if(l.includes("."))return false;return true}function a(u){var p=u;if(!p.startsWith("/"))p="/"+p;return"/api/deployments/"+s+"/functions"+p}var f=window.fetch;window.fetch=function(i,o){var u=typeof i==="string"?i:i.url;if(e(u))return f(a(u),o);return f(i,o)};var X=window.XMLHttpRequest;window.XMLHttpRequest=function(){var x=new X();var op=x.open;x.open=function(m,u){if(e(u))return op.call(this,m,a(u));return op.apply(this,arguments)};return x};document.addEventListener("submit",function(ev){var fm=ev.target;if(!(fm instanceof HTMLFormElement))return;var ac=fm.getAttribute("action")||"";if(!e(ac))return;ev.preventDefault();var m=(fm.method||"POST").toUpperCase();var fd=new FormData(fm);var d={};fd.forEach(function(v,k){d[k]=v});fetch(a(ac),{method:m,headers:{"Content-Type":"application/json"},body:m!=="GET"?JSON.stringify(d):undefined}).then(function(r){return r.json().catch(function(){return r.text()})}).then(function(r){var ev=new CustomEvent("edge-function-response",{detail:{action:ac,result:r}});fm.dispatchEvent(ev);document.dispatchEvent(ev)}).catch(function(err){console.error("[Edge Function]",err);var ev=new CustomEvent("edge-function-error",{detail:{action:ac,error:err.message}});fm.dispatchEvent(ev);document.dispatchEvent(ev)})},true)})();
</script>`;

  return injectIntoHead(html, interceptorScript);
}

/**
 * Escape HTML special characters
 */
function escapeHtml(text: string): string {
  const map: Record<string, string> = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;',
  };
  return text.replace(/[&<>"']/g, (char) => map[char]);
}