Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/deployment-preview.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
PUBLIC_GOOGLE_MAPS_API_KEY: ${{ vars.PUBLIC_GOOGLE_MAPS_API_KEY }}
PUBLIC_GOOGLE_MAP_ID: ${{ vars.PUBLIC_GOOGLE_MAP_ID }}
PUBLIC_SENTRY_DSN: ${{ vars.PUBLIC_SENTRY_DSN }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
PUBLIC_UPSTASH_SEARCH_REST_URL: ${{ vars.PUBLIC_UPSTASH_SEARCH_REST_URL }}
PUBLIC_UPSTASH_SEARCH_READONLY_TOKEN: ${{ vars.PUBLIC_UPSTASH_SEARCH_READONLY_TOKEN }}
VERCEL_ORG_ID: ${{ vars.VERCEL_ORG_ID }}
Expand Down Expand Up @@ -69,6 +70,7 @@ jobs:
- name: Vercel build (preview)
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
run: vercel build --token=${VERCEL_TOKEN}

- name: Deploy to Vercel (preview)
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/deployment-production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ jobs:
PUBLIC_GOOGLE_MAPS_API_KEY: ${{ vars.PUBLIC_GOOGLE_MAPS_API_KEY }}
PUBLIC_GOOGLE_MAP_ID: ${{ vars.PUBLIC_GOOGLE_MAP_ID }}
PUBLIC_SENTRY_DSN: ${{ vars.PUBLIC_SENTRY_DSN }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
PUBLIC_UPSTASH_SEARCH_REST_URL: ${{ vars.PUBLIC_UPSTASH_SEARCH_REST_URL }}
PUBLIC_UPSTASH_SEARCH_READONLY_TOKEN: ${{ vars.PUBLIC_UPSTASH_SEARCH_READONLY_TOKEN }}
VERCEL_ORG_ID: ${{ vars.VERCEL_ORG_ID }}
Expand Down Expand Up @@ -63,6 +64,7 @@ jobs:
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
NODE_ENV: production
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
run: vercel build --prod --token=${VERCEL_TOKEN}

##
Expand Down
18 changes: 10 additions & 8 deletions astro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,16 @@ import { createLogger, type LogOptions, type PluginOption } from 'vite'
*/
import {
environmentalVariablesConfig,
getSentryAuthToken,
getSiteUrl,
isE2eTest,
isVercel,
markdownConfig,
pwaConfig,
vercelConfig,
} from './src/lib/config'
import { callToActionValidator } from './src/integrations/CtaValidator'
import { faviconGenerator } from './src/integrations/FaviconGenerator'
import { packageRelease } from './src/integrations/PackageRelease'
import { privacyPolicyVersion } from './src/integrations/PrivacyPolicyVersion'
import { getPackageRelease, packageRelease } from './src/integrations/PackageRelease'
import { testimonialsLengthWarning } from './src/integrations/TestimonialsLengthWarning'
import { fixContentAssetPropagation } from './src/lib/plugins/fixContentAssetPropagation'
import { pwaDevAssetServer } from './src/lib/plugins/pwaDevAssetServer'
Expand All @@ -41,6 +39,9 @@ import { createSerializeFunction, pagesJsonWriter } from './src/integrations/sit
// Ensure Vite's HMR websocket connects through the same exposed dev server port used by Astro.
const devServerPort = Number(process.env['DEV_SERVER_PORT'] ?? 4321)
const viteLogger = createLogger(undefined, { allowClearScreen: false })
const sentryAuthToken = process.env['SENTRY_AUTH_TOKEN']
const sentryRelease = getPackageRelease()
const shouldEnableSentryIntegration = Boolean(sentryAuthToken)

const shouldSuppressViteWarning = (message: string): boolean => {
return (
Expand Down Expand Up @@ -82,11 +83,12 @@ const standardIntegrations = [
privacyPolicyVersion(),
/** Warn when testimonial bodies are too short/too long (helps keep carousel cards consistent) */
testimonialsLengthWarning({ min: 300, max: 400 }),
/** Only include Sentry integration in Vercel environments */
...(isVercel() ? [sentry({
project: "webstack-builders-corporate-website",
org: "webstack-builders",
authToken: getSentryAuthToken(),
/** Enable Sentry build integration when CI provides upload credentials. */
...(shouldEnableSentryIntegration && sentryAuthToken ? [sentry({
project: 'webstack-builders-corporate-website',
org: 'webstack-builders',
authToken: sentryAuthToken,
release: sentryRelease,
})] : []),
sitemap({
serialize: createSerializeFunction({
Expand Down
46 changes: 43 additions & 3 deletions src/components/Pwa/PrefetchOfflinePage/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,25 @@
<script>
import { handleScriptError } from '@components/scripts/errors/handler'

const BODY_PREVIEW_LENGTH = 240

const getHeaderValue = (response: Response, headerName: string) =>
response.headers.get(headerName) ?? 'missing'

const getBodyPreview = async (response: Response) => {
try {
const bodyText = await response.text()

if (!bodyText) {
return 'empty'
}

return bodyText.slice(0, BODY_PREVIEW_LENGTH).replace(/\s+/g, ' ')
} catch {
return 'unavailable'
}
}

const prefetch = (url: string) => {
try {
fetch(url, {
Expand All @@ -15,14 +34,35 @@
'x-prefetch-source': 'PrefetchOfflinePage',
},
})
.then(response => {
.then(async response => {
if (response.ok) {
return response
}

throw new Error(
`Prefetch failed for ${url}: ${response.status} ${response.statusText || 'Unknown Status'} (content-type: ${response.headers.get('content-type') ?? 'unknown'})`
const contentType = getHeaderValue(response, 'content-type')
const bodyPreview = await getBodyPreview(response)
const statusText = response.statusText || 'Unknown Status'
const error = new Error(
`Prefetch failed for ${url}: ${response.status} ${statusText} (content-type: ${contentType})`
)

handleScriptError(error, {
scriptName: 'BaseLayout',
operation: `prefetch ${url}`,
extra: {
prefetchUrl: url,
requestStatus: response.status,
statusText,
contentType,
bodyPreview,
xPrefetchSource: 'PrefetchOfflinePage',
xVercelId: getHeaderValue(response, 'x-vercel-id'),
xMatchedPath: getHeaderValue(response, 'x-matched-path'),
cacheControl: getHeaderValue(response, 'cache-control'),
},
})

return response
})
.catch(error => {
handleScriptError(error, { scriptName: 'BaseLayout', operation: `prefetch ${url}` })
Expand Down
8 changes: 8 additions & 0 deletions src/components/scripts/errors/__tests__/handler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ describe('handleScriptError', () => {
const result = handleScriptError(new TestError('boom'), {
scriptName: 'AppBootstrap',
operation: 'init',
extra: {
requestStatus: 500,
contentType: 'text/html',
},
})

expect(result).toBeInstanceOf(ClientScriptError)
Expand All @@ -38,6 +42,10 @@ describe('handleScriptError', () => {
scriptName: 'AppBootstrap',
operation: 'init',
},
extra: {
requestStatus: 500,
contentType: 'text/html',
},
})
expect(consoleErrorSpy).not.toHaveBeenCalled()
})
Expand Down
4 changes: 4 additions & 0 deletions src/components/scripts/errors/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import { captureException } from '@sentry/browser'
import { ClientScriptError } from './ClientScriptError'
import { isProd } from '@components/scripts/utils/environmentClient'

type ScriptErrorExtraValue = string | number | boolean | null

export interface ScriptErrorContext {
scriptName: string
operation?: string
extra?: Record<string, ScriptErrorExtraValue>
}

/**
Expand Down Expand Up @@ -35,6 +38,7 @@ export function handleScriptError(error: unknown, context: ScriptErrorContext):
scriptName: context.scriptName,
...(context.operation && { operation: context.operation }),
},
...(context.extra && { extra: context.extra }),
})
} else {
// Log it for debugging
Expand Down
72 changes: 63 additions & 9 deletions src/integrations/PackageRelease/index.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,93 @@
/**
* Package Release Integration
*
* Automatically injects the package name and version at build time from package.json.
* This provides a release identifier for tracking regressions between numbered releases
* in monitoring services like Sentry.
* Automatically injects a build-time release identifier for monitoring systems like Sentry.
*
* The release is injected as PACKAGE_RELEASE_VERSION environment variable in the format
* "name@version" and is available throughout the app as import.meta.env.PACKAGE_RELEASE_VERSION
* "name@commitSha" when CI metadata is available, with a local fallback to "name@version".
* It is available throughout the app as import.meta.env.PACKAGE_RELEASE_VERSION.
*
* Fallback order:
* 1. Manual env var (PACKAGE_RELEASE_VERSION in .env)
* 1. CI/Vercel commit SHA
* 2. package.json name@version
* 3. "unknown@0.0.0" (if package.json cannot be read)
* 3. BuildError if package.json cannot be read
*/

import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import type { AstroIntegration } from 'astro'
import { getOptionalEnv, isTest } from '../../lib/config/environmentServer'
import { BuildError } from '../../lib/errors/BuildError'

interface PackageJson {
name?: string
version?: string
}

function readPackageJson(): PackageJson {
const packageJsonPath = resolve(process.cwd(), 'package.json')
const packageJsonContent = readFileSync(packageJsonPath, 'utf-8')

return JSON.parse(packageJsonContent) as PackageJson
}

function getPackageName(): string {
try {
const packageJsonPath = resolve(process.cwd(), 'package.json')
const packageJson = readPackageJson()
const name = packageJson.name

if (!name) {
throw new BuildError('package.json is missing required field. name: missing', {
phase: 'config-setup',
filePath: packageJsonPath,
})
}

return name
} catch (error) {
if (error instanceof BuildError) {
throw error
}

const packageJsonPath = resolve(process.cwd(), 'package.json')
throw new BuildError(
`Could not read package.json for package name: ${error instanceof Error ? error.message : String(error)}`,
{ phase: 'config-setup', filePath: packageJsonPath, cause: error }
)
}
}

function getBuildRelease(): string | undefined {
if (isTest()) {
return undefined
}

const releaseCandidate = getOptionalEnv('GITHUB_SHA') ||
getOptionalEnv('VERCEL_GIT_COMMIT_SHA') ||
getOptionalEnv('PUBLIC_VERCEL_GIT_COMMIT_SHA')

if (!releaseCandidate) {
return undefined
}

return `${getPackageName()}@${releaseCandidate}`
}

/**
* Get package release from package.json
* @returns Release string in format "name@version"
* @throws {BuildError} If package.json cannot be read or parsed
*/
function getPackageRelease(): string {
export function getPackageRelease(): string {
const buildRelease = getBuildRelease()
if (buildRelease) {
return buildRelease
}

try {
const packageJsonPath = resolve(process.cwd(), 'package.json')
const packageJsonContent = readFileSync(packageJsonPath, 'utf-8')
const packageJson = JSON.parse(packageJsonContent) as PackageJson
const packageJson = readPackageJson()

const name = packageJson.name
const version = packageJson.version
Expand Down
2 changes: 1 addition & 1 deletion src/layouts/BaseLayout.astro
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ const {
} = Astro.props

const requestUrl = Astro.url?.href
const requestHeaders = Astro.request?.headers
const requestHeaders = Astro.isPrerendered ? undefined : Astro.request.headers

applyRenderSentryContext({
contextName: 'pageRender',
Expand Down
Loading