Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add multiple cdn support #9898

Closed
wants to merge 2 commits into from
Closed
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
6 changes: 3 additions & 3 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { AddressInfo } from 'node:net';
import type * as rollup from 'rollup';
import type * as vite from 'vite';
import type { RemotePattern } from '../assets/utils/remotePattern.js';
import type { SerializedSSRManifest } from '../core/app/types.js';
import type { SerializedSSRManifest, AssetsPrefix } from '../core/app/types.js';
import type { PageBuildData } from '../core/build/types.js';
import type { AstroConfigType } from '../core/config/index.js';
import type { AstroTimer } from '../core/config/timer.js';
Expand Down Expand Up @@ -63,7 +63,7 @@ export type {
UnresolvedImageTransform,
} from '../assets/types.js';
export type { RemotePattern } from '../assets/utils/remotePattern.js';
export type { SSRManifest } from '../core/app/types.js';
export type { SSRManifest, AssetsPrefix } from '../core/app/types.js';
export type {
AstroCookieGetOptions,
AstroCookieSetOptions,
Expand Down Expand Up @@ -838,7 +838,7 @@ export interface AstroUserConfig {
* }
* ```
*/
assetsPrefix?: string;
assetsPrefix?: AssetsPrefix;
/**
* @docs
* @name build.serverEntry
Expand Down
28 changes: 22 additions & 6 deletions packages/astro/src/assets/vite-plugin-assets.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import MagicString from 'magic-string';
import type * as vite from 'vite';
import { normalizePath } from 'vite';
import { getFileExtension } from '@astrojs/internal-helpers/path';
import type { AstroPluginOptions, ImageTransform } from '../@types/astro.js';
import { extendManualChunks } from '../core/build/plugins/util.js';
import { AstroError, AstroErrorData } from '../core/errors/index.js';
Expand Down Expand Up @@ -94,9 +95,15 @@ export default function assets({
}

// Rollup will copy the file to the output directory, this refer to this final path, not to the original path
const finalOriginalImagePath = (
isESMImportedImage(options.src) ? options.src.src : options.src
).replace(settings.config.build.assetsPrefix || '', '');
const ESMImportedImageSrc = isESMImportedImage(options.src) ? options.src.src : options.src;
let pf = ''
const fileExtension = getFileExtension(ESMImportedImageSrc)
if (settings.config.build.assetsPrefix && typeof settings.config.build.assetsPrefix === 'string') {
pf = settings.config.build.assetsPrefix
} else if (typeof settings.config.build.assetsPrefix === 'function') {
pf = settings.config.build.assetsPrefix(fileExtension)
}
const finalOriginalImagePath = ESMImportedImageSrc.replace(pf, '');

const hash = hashTransform(
options,
Expand Down Expand Up @@ -130,8 +137,10 @@ export default function assets({

// The paths here are used for URLs, so we need to make sure they have the proper format for an URL
// (leading slash, prefixed with the base / assets prefix, encoded, etc)
if (settings.config.build.assetsPrefix) {
if (settings.config.build.assetsPrefix && typeof settings.config.build.assetsPrefix === 'string') {
return encodeURI(joinPaths(settings.config.build.assetsPrefix, finalFilePath));
} else if (typeof settings.config.build.assetsPrefix === 'function') {
return encodeURI(joinPaths(pf, finalFilePath));
} else {
return encodeURI(prependForwardSlash(joinPaths(settings.config.base, finalFilePath)));
}
Expand All @@ -148,8 +157,15 @@ export default function assets({
const [full, hash, postfix = ''] = match;

const file = this.getFileName(hash);
const prefix = settings.config.build.assetsPrefix
? appendForwardSlash(settings.config.build.assetsPrefix)
let pf
if (settings.config.build.assetsPrefix && typeof settings.config.build.assetsPrefix === 'string') {
pf = settings.config.build.assetsPrefix
} else if (typeof settings.config.build.assetsPrefix === 'function') {
const fileExtension = getFileExtension(file)
pf = settings.config.build.assetsPrefix(fileExtension)
}
const prefix = pf
? appendForwardSlash(pf)
: resolvedConfig.base;
const outputFilepath = prefix + normalizePath(file + postfix);

Expand Down
9 changes: 7 additions & 2 deletions packages/astro/src/content/vite-plugin-content-assets.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { extname } from 'node:path';
import { pathToFileURL } from 'node:url';
import type { Plugin, Rollup } from 'vite';
import { getFileExtension } from '@astrojs/internal-helpers/path';
import type { AstroSettings } from '../@types/astro.js';
import { moduleIsTopLevelPage, walkParentInfos } from '../core/build/graph.js';
import { getPageDataByViteID, type BuildInternals } from '../core/build/internal.js';
Expand Down Expand Up @@ -125,8 +126,12 @@ export function astroConfigBuildPlugin(
'build:post': ({ ssrOutputs, clientOutputs, mutate }) => {
const outputs = ssrOutputs.flatMap((o) => o.output);
const prependBase = (src: string) => {
if (options.settings.config.build.assetsPrefix) {
return joinPaths(options.settings.config.build.assetsPrefix, src);
const { assetsPrefix } = options.settings.config.build
if (typeof assetsPrefix === "string") {
return joinPaths(assetsPrefix, src);
} else if (typeof assetsPrefix === "function") {
const pf = assetsPrefix(getFileExtension(src)) || ""
return joinPaths(pf, src);
} else {
return prependForwardSlash(joinPaths(options.settings.config.base, src));
}
Expand Down
4 changes: 3 additions & 1 deletion packages/astro/src/core/app/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export type SerializedRouteInfo = Omit<RouteInfo, 'routeData'> & {

export type ImportComponentInstance = () => Promise<SinglePageBuiltModule>;

export type AssetsPrefix = string | ((fileType: string) => string)

export type SSRManifest = {
adapterName: string;
routes: RouteInfo[];
Expand All @@ -42,7 +44,7 @@ export type SSRManifest = {
trailingSlash: 'always' | 'never' | 'ignore';
buildFormat: 'file' | 'directory';
compressHTML: boolean;
assetsPrefix?: string;
assetsPrefix?: AssetsPrefix;
renderers: SSRLoadedRenderer[];
/**
* Map of directive name (e.g. `load`) to the directive script code
Expand Down
4 changes: 4 additions & 0 deletions packages/astro/src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,10 @@ export async function generatePages(opts: StaticBuildOptions, internals: BuildIn
renderers.renderers as SSRLoadedRenderer[]
);
}
// solve JSON.stringify lose assetsPrefix function
if (typeof opts.settings.config.build.assetsPrefix === 'function') {
manifest.assetsPrefix = opts.settings.config.build.assetsPrefix
}
const pipeline = new BuildPipeline(opts, internals, manifest);

const outFolder = ssr
Expand Down
7 changes: 6 additions & 1 deletion packages/astro/src/core/build/plugins/plugin-manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import glob from 'fast-glob';
import { fileURLToPath } from 'node:url';
import type { OutputChunk } from 'rollup';
import { type Plugin as VitePlugin } from 'vite';
import { getFileExtension } from '@astrojs/internal-helpers/path';
import { runHookBuildSsr } from '../../../integrations/index.js';
import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from '../../../vite-plugin-scripts/index.js';
import type {
Expand Down Expand Up @@ -165,8 +166,12 @@ function buildManifest(
}

const prefixAssetPath = (pth: string) => {
if (settings.config.build.assetsPrefix) {
if (typeof settings.config.build.assetsPrefix === "string") {
return joinPaths(settings.config.build.assetsPrefix, pth);
} else if (typeof settings.config.build.assetsPrefix === "function") {
const fileType = getFileExtension(pth)
const pf = settings.config.build.assetsPrefix(fileType) || ""
return joinPaths(pf, pth);
} else {
return prependForwardSlash(joinPaths(settings.config.base, pth));
}
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/core/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export const AstroConfigSchema = z.object({
.default(ASTRO_CONFIG_DEFAULTS.build.server)
.transform((val) => new URL(val)),
assets: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.assets),
assetsPrefix: z.string().optional(),
assetsPrefix: z.function().args(z.string()).returns(z.string()).optional().or(z.string().optional()),
serverEntry: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.serverEntry),
redirects: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.redirects),
inlineStylesheets: z
Expand Down Expand Up @@ -479,7 +479,7 @@ export function createRelativeSchema(cmd: string, fileProtocolRoot: string) {
.default(ASTRO_CONFIG_DEFAULTS.build.server)
.transform((val) => resolveDirAsUrl(val, fileProtocolRoot)),
assets: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.assets),
assetsPrefix: z.string().optional(),
assetsPrefix: z.function().args(z.string()).returns(z.string()).optional().or(z.string().optional()),
serverEntry: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.serverEntry),
redirects: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.redirects),
inlineStylesheets: z
Expand Down
13 changes: 10 additions & 3 deletions packages/astro/src/core/create-vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,6 @@ export async function createVite(
define: {
'import.meta.env.SITE': stringifyForDefine(settings.config.site),
'import.meta.env.BASE_URL': stringifyForDefine(settings.config.base),
'import.meta.env.ASSETS_PREFIX': stringifyForDefine(settings.config.build.assetsPrefix),
},
server: {
hmr:
Expand Down Expand Up @@ -198,15 +197,23 @@ export async function createVite(
external: [...(mode === 'dev' ? ONLY_DEV_EXTERNAL : []), ...astroPkgsConfig.ssr.external],
},
};

const { assetsPrefix } = settings.config.build;
if (assetsPrefix && typeof assetsPrefix === 'string' && commonConfig.define) {
commonConfig.define['import.meta.env.ASSETS_PREFIX'] = stringifyForDefine(assetsPrefix);
}

// If the user provides a custom assets prefix, make sure assets handled by Vite
// are prefixed with it too. This uses one of it's experimental features, but it
// has been stable for a long time now.
const assetsPrefix = settings.config.build.assetsPrefix;
if (assetsPrefix) {
commonConfig.experimental = {
renderBuiltUrl(filename, { type }) {
renderBuiltUrl(filename, { type, hostType }) {
if (type === 'asset') {
if (typeof assetsPrefix === 'function') {
const pf = assetsPrefix(hostType)
return joinPaths(pf, filename);
}
return joinPaths(assetsPrefix, filename);
}
},
Expand Down
23 changes: 14 additions & 9 deletions packages/astro/src/core/render/ssr-element.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import type { SSRElement } from '../../@types/astro.js';
import type { SSRElement, AssetsPrefix } from '../../@types/astro.js';
import { joinPaths, prependForwardSlash, slash } from '../../core/path.js';
import type { StylesheetAsset } from '../app/types.js';
import { getFileExtension } from '@astrojs/internal-helpers/path';

export function createAssetLink(href: string, base?: string, assetsPrefix?: string): string {
if (assetsPrefix) {
export function createAssetLink(href: string, base?: string, assetsPrefix?: AssetsPrefix): string {
if (typeof assetsPrefix === "string") {
return joinPaths(assetsPrefix, slash(href));
} else if (typeof assetsPrefix === "function") {
const fileType = getFileExtension(href)
const pf = assetsPrefix(fileType) || ""
return joinPaths(pf, slash(href));
} else if (base) {
return prependForwardSlash(joinPaths(base, slash(href)));
} else {
Expand All @@ -15,7 +20,7 @@ export function createAssetLink(href: string, base?: string, assetsPrefix?: stri
export function createStylesheetElement(
stylesheet: StylesheetAsset,
base?: string,
assetsPrefix?: string
assetsPrefix?: AssetsPrefix
): SSRElement {
if (stylesheet.type === 'inline') {
return {
Expand All @@ -36,15 +41,15 @@ export function createStylesheetElement(
export function createStylesheetElementSet(
stylesheets: StylesheetAsset[],
base?: string,
assetsPrefix?: string
assetsPrefix?: AssetsPrefix
): Set<SSRElement> {
return new Set(stylesheets.map((s) => createStylesheetElement(s, base, assetsPrefix)));
}

export function createModuleScriptElement(
script: { type: 'inline' | 'external'; value: string },
base?: string,
assetsPrefix?: string
assetsPrefix?: AssetsPrefix
): SSRElement {
if (script.type === 'external') {
return createModuleScriptElementWithSrc(script.value, base, assetsPrefix);
Expand All @@ -61,7 +66,7 @@ export function createModuleScriptElement(
export function createModuleScriptElementWithSrc(
src: string,
base?: string,
assetsPrefix?: string
assetsPrefix?: AssetsPrefix
): SSRElement {
return {
props: {
Expand All @@ -75,7 +80,7 @@ export function createModuleScriptElementWithSrc(
export function createModuleScriptElementWithSrcSet(
srces: string[],
site?: string,
assetsPrefix?: string
assetsPrefix?: AssetsPrefix
): Set<SSRElement> {
return new Set<SSRElement>(
srces.map((src) => createModuleScriptElementWithSrc(src, site, assetsPrefix))
Expand All @@ -85,7 +90,7 @@ export function createModuleScriptElementWithSrcSet(
export function createModuleScriptsSet(
scripts: { type: 'inline' | 'external'; value: string }[],
base?: string,
assetsPrefix?: string
assetsPrefix?: AssetsPrefix
): Set<SSRElement> {
return new Set<SSRElement>(
scripts.map((script) => createModuleScriptElement(script, base, assetsPrefix))
Expand Down
5 changes: 5 additions & 0 deletions packages/internal-helpers/src/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ export function removeFileExtension(path: string) {
return idx === -1 ? path : path.slice(0, idx);
}

export function getFileExtension(path: string) {
let idx = path.lastIndexOf('.');
return idx === -1 ? '' : path.slice(idx+1);
}

export function removeQueryString(path: string) {
const index = path.lastIndexOf('?');
return index > 0 ? path.substring(0, index) : path;
Expand Down
Loading