summaryrefslogtreecommitdiff
path: root/packages/integrations/cloudflare/src
diff options
context:
space:
mode:
authorGravatar Emanuele Stoppa <my.burning@gmail.com> 2023-12-21 13:52:11 +0000
committerGravatar GitHub <noreply@github.com> 2023-12-21 13:52:11 +0000
commit51e8c8420836b184c24ff8d63b325ef93e83e427 (patch)
tree049acdace8a29f3d1d6b7f21eeabde23c30d3b9a /packages/integrations/cloudflare/src
parent9161cb9bbe4ac8c6aef56ff3682e1a2c4524886b (diff)
downloadastro-51e8c8420836b184c24ff8d63b325ef93e83e427.tar.gz
astro-51e8c8420836b184c24ff8d63b325ef93e83e427.tar.zst
astro-51e8c8420836b184c24ff8d63b325ef93e83e427.zip
chore: use Biome as linter (#111)
* chore: biome safe fixes * chore: biome unsafe fixes * chore: biome safe fixes * chore: biome unsafe fixes * chore: update script * chore: format * chore: turn off some eslint rule * small refactor * fix
Diffstat (limited to 'packages/integrations/cloudflare/src')
-rw-r--r--packages/integrations/cloudflare/src/entrypoints/server.advanced.ts4
-rw-r--r--packages/integrations/cloudflare/src/entrypoints/server.directory.ts4
-rw-r--r--packages/integrations/cloudflare/src/index.ts39
-rw-r--r--packages/integrations/cloudflare/src/util.ts5
-rw-r--r--packages/integrations/cloudflare/src/utils/assets.ts24
-rw-r--r--packages/integrations/cloudflare/src/utils/local-runtime.ts12
-rw-r--r--packages/integrations/cloudflare/src/utils/parser.ts14
-rw-r--r--packages/integrations/cloudflare/src/utils/prependForwardSlash.ts2
-rw-r--r--packages/integrations/cloudflare/src/utils/wasm-module-loader.ts43
9 files changed, 73 insertions, 74 deletions
diff --git a/packages/integrations/cloudflare/src/entrypoints/server.advanced.ts b/packages/integrations/cloudflare/src/entrypoints/server.advanced.ts
index 170b2839d..885f9e221 100644
--- a/packages/integrations/cloudflare/src/entrypoints/server.advanced.ts
+++ b/packages/integrations/cloudflare/src/entrypoints/server.advanced.ts
@@ -39,7 +39,7 @@ export function createExports(manifest: SSRManifest) {
return env.ASSETS.fetch(request);
}
- let routeData = app.match(request);
+ const routeData = app.match(request);
Reflect.set(
request,
Symbol.for('astro.clientAddress'),
@@ -57,7 +57,7 @@ export function createExports(manifest: SSRManifest) {
},
};
- let response = await app.render(request, routeData, locals);
+ const response = await app.render(request, routeData, locals);
if (app.setCookieHeaders) {
for (const setCookieHeader of app.setCookieHeaders(response)) {
diff --git a/packages/integrations/cloudflare/src/entrypoints/server.directory.ts b/packages/integrations/cloudflare/src/entrypoints/server.directory.ts
index 6c86f685f..1ab33d868 100644
--- a/packages/integrations/cloudflare/src/entrypoints/server.directory.ts
+++ b/packages/integrations/cloudflare/src/entrypoints/server.directory.ts
@@ -32,7 +32,7 @@ export function createExports(manifest: SSRManifest) {
return env.ASSETS.fetch(request);
}
- let routeData = app.match(request);
+ const routeData = app.match(request);
Reflect.set(
request,
Symbol.for('astro.clientAddress'),
@@ -50,7 +50,7 @@ export function createExports(manifest: SSRManifest) {
},
};
- let response = await app.render(request, routeData, locals);
+ const response = await app.render(request, routeData, locals);
if (app.setCookieHeaders) {
for (const setCookieHeader of app.setCookieHeaders(response)) {
diff --git a/packages/integrations/cloudflare/src/index.ts b/packages/integrations/cloudflare/src/index.ts
index 509da8e5a..83aef2ae9 100644
--- a/packages/integrations/cloudflare/src/index.ts
+++ b/packages/integrations/cloudflare/src/index.ts
@@ -270,7 +270,7 @@ export default function createIntegration(args?: Options): AstroIntegration {
});
}
- const outputFiles: Array<string> = await glob(`**/*`, {
+ const outputFiles: Array<string> = await glob('**/*', {
cwd: outputDir,
filesOnly: true,
});
@@ -410,20 +410,16 @@ export default function createIntegration(args?: Options): AstroIntegration {
.map((route) => {
if (route.component === 'src/pages/404.astro' && route.prerender === false)
notFoundIsSSR = true;
- const includePattern =
- '/' +
- route.segments
- .flat()
- .map((segment) => (segment.dynamic ? '*' : segment.content))
- .join('/');
+ const includePattern = `/${route.segments
+ .flat()
+ .map((segment) => (segment.dynamic ? '*' : segment.content))
+ .join('/')}`;
const regexp = new RegExp(
- '^\\/' +
- route.segments
- .flat()
- .map((segment) => (segment.dynamic ? '(.*)' : segment.content))
- .join('\\/') +
- '$'
+ `^\\/${route.segments
+ .flat()
+ .map((segment) => (segment.dynamic ? '(.*)' : segment.content))
+ .join('\\/')}$`
);
return {
@@ -442,7 +438,7 @@ export default function createIntegration(args?: Options): AstroIntegration {
.filter((file: string) => cloudflareSpecialFiles.indexOf(file) < 0)
.map((file: string) => `/${file.replace(/\\/g, '/')}`);
- for (let page of pages) {
+ for (const page of pages) {
let pagePath = prependForwardSlash(page.pathname);
if (_config.base !== '/') {
const base = _config.base.endsWith('/') ? _config.base.slice(0, -1) : _config.base;
@@ -467,15 +463,14 @@ export default function createIntegration(args?: Options): AstroIntegration {
const parts = line.split(' ');
if (parts.length < 2) {
return null;
- } else {
- // convert /products/:id to /products/*
- return (
- parts[0]
- .replace(/\/:.*?(?=\/|$)/g, '/*')
- // remove query params as they are not supported by cloudflare
- .replace(/\?.*$/, '')
- );
}
+ // convert /products/:id to /products/*
+ return (
+ parts[0]
+ .replace(/\/:.*?(?=\/|$)/g, '/*')
+ // remove query params as they are not supported by cloudflare
+ .replace(/\?.*$/, '')
+ );
})
.filter(
(line, index, arr) => line !== null && arr.indexOf(line) === index
diff --git a/packages/integrations/cloudflare/src/util.ts b/packages/integrations/cloudflare/src/util.ts
index 120cb7334..0ca79de20 100644
--- a/packages/integrations/cloudflare/src/util.ts
+++ b/packages/integrations/cloudflare/src/util.ts
@@ -8,10 +8,7 @@ export function getProcessEnvProxy() {
get: (target, prop) => {
console.warn(
// NOTE: \0 prevents Vite replacement
- `Unable to access \`import.meta\0.env.${prop.toString()}\` on initialization ` +
- `as the Cloudflare platform only provides the environment variables per request. ` +
- `Please move the environment variable access inside a function ` +
- `that's only called after a request has been received.`
+ `Unable to access \`import.meta\0.env.${prop.toString()}\` on initialization as the Cloudflare platform only provides the environment variables per request. Please move the environment variable access inside a function that's only called after a request has been received.`
);
},
}
diff --git a/packages/integrations/cloudflare/src/utils/assets.ts b/packages/integrations/cloudflare/src/utils/assets.ts
index 68cfe7189..edc563c05 100644
--- a/packages/integrations/cloudflare/src/utils/assets.ts
+++ b/packages/integrations/cloudflare/src/utils/assets.ts
@@ -9,12 +9,15 @@ export function isRemotePath(src: string) {
export function matchHostname(url: URL, hostname?: string, allowWildcard?: boolean) {
if (!hostname) {
return true;
- } else if (!allowWildcard || !hostname.startsWith('*')) {
+ }
+ if (!allowWildcard || !hostname.startsWith('*')) {
return hostname === url.hostname;
- } else if (hostname.startsWith('**.')) {
+ }
+ if (hostname.startsWith('**.')) {
const slicedHostname = hostname.slice(2); // ** length
return slicedHostname !== url.hostname && url.hostname.endsWith(slicedHostname);
- } else if (hostname.startsWith('*.')) {
+ }
+ if (hostname.startsWith('*.')) {
const slicedHostname = hostname.slice(1); // * length
const additionalSubdomains = url.hostname
.replace(slicedHostname, '')
@@ -34,12 +37,15 @@ export function matchProtocol(url: URL, protocol?: string) {
export function matchPathname(url: URL, pathname?: string, allowWildcard?: boolean) {
if (!pathname) {
return true;
- } else if (!allowWildcard || !pathname.endsWith('*')) {
+ }
+ if (!allowWildcard || !pathname.endsWith('*')) {
return pathname === url.pathname;
- } else if (pathname.endsWith('/**')) {
+ }
+ if (pathname.endsWith('/**')) {
const slicedPathname = pathname.slice(0, -2); // ** length
return slicedPathname !== url.pathname && url.pathname.startsWith(slicedPathname);
- } else if (pathname.endsWith('/*')) {
+ }
+ if (pathname.endsWith('/*')) {
const slicedPathname = pathname.slice(0, -1); // * length
const additionalPathChunks = url.pathname
.replace(slicedPathname, '')
@@ -91,11 +97,11 @@ export function joinPaths(...paths: (string | undefined)[]) {
.map((path, i) => {
if (i === 0) {
return removeTrailingForwardSlash(path);
- } else if (i === paths.length - 1) {
+ }
+ if (i === paths.length - 1) {
return removeLeadingForwardSlash(path);
- } else {
- return trimSlashes(path);
}
+ return trimSlashes(path);
})
.join('/');
}
diff --git a/packages/integrations/cloudflare/src/utils/local-runtime.ts b/packages/integrations/cloudflare/src/utils/local-runtime.ts
index dea14a052..79cbd39bd 100644
--- a/packages/integrations/cloudflare/src/utils/local-runtime.ts
+++ b/packages/integrations/cloudflare/src/utils/local-runtime.ts
@@ -83,11 +83,11 @@ class LocalRuntime {
this._astroConfig = astroConfig;
this._logger = logger;
- let varBindings: Required<Pick<WorkerOptions, 'bindings'>>['bindings'] = {};
- let kvBindings: Required<Pick<WorkerOptions, 'kvNamespaces'>>['kvNamespaces'] = [];
- let d1Bindings: Required<Pick<WorkerOptions, 'd1Databases'>>['d1Databases'] = [];
- let r2Bindings: Required<Pick<WorkerOptions, 'r2Buckets'>>['r2Buckets'] = [];
- let durableObjectBindings: Required<Pick<WorkerOptions, 'durableObjects'>>['durableObjects'] =
+ const varBindings: Required<Pick<WorkerOptions, 'bindings'>>['bindings'] = {};
+ const kvBindings: Required<Pick<WorkerOptions, 'kvNamespaces'>>['kvNamespaces'] = [];
+ const d1Bindings: Required<Pick<WorkerOptions, 'd1Databases'>>['d1Databases'] = [];
+ const r2Bindings: Required<Pick<WorkerOptions, 'r2Buckets'>>['r2Buckets'] = [];
+ const durableObjectBindings: Required<Pick<WorkerOptions, 'durableObjects'>>['durableObjects'] =
{};
for (const bindingName in runtimeConfig.bindings) {
@@ -280,6 +280,8 @@ export class LocalWorkersRuntime extends LocalRuntime {
}
export class LocalPagesRuntime extends LocalRuntime {
+
+ // biome-ignore lint/complexity/noUselessConstructor: not types information yet, so we need to disable the rule for the time being
public constructor(
astroConfig: AstroConfig,
runtimeConfig: Extract<RUNTIME, { type: 'pages' }>,
diff --git a/packages/integrations/cloudflare/src/utils/parser.ts b/packages/integrations/cloudflare/src/utils/parser.ts
index 7e3132594..5140b22a1 100644
--- a/packages/integrations/cloudflare/src/utils/parser.ts
+++ b/packages/integrations/cloudflare/src/utils/parser.ts
@@ -21,11 +21,11 @@ function findWranglerToml(
): string | undefined {
if (preferJson) {
return (
- findUpSync(`wrangler.json`, { cwd: referencePath }) ??
- findUpSync(`wrangler.toml`, { cwd: referencePath })
+ findUpSync('wrangler.json', { cwd: referencePath }) ??
+ findUpSync('wrangler.toml', { cwd: referencePath })
);
}
- return findUpSync(`wrangler.toml`, { cwd: referencePath });
+ return findUpSync('wrangler.toml', { cwd: referencePath });
}
type File = {
file?: string;
@@ -117,9 +117,8 @@ function getVarsForDev(config: any, configPath: string | undefined): any {
...config.vars,
...loaded.parsed,
};
- } else {
- return config.vars;
}
+ return config.vars;
}
function parseConfig() {
@@ -179,12 +178,13 @@ export function getDOBindings(): Record<
> {
const { rawConfig } = parseConfig();
if (!rawConfig) return {};
- if (!rawConfig?.durable_objects) return {};
+ if (!rawConfig.durable_objects) return {};
const output = new Object({}) as Record<
string,
{ scriptName?: string | undefined; unsafeUniqueKey?: string | undefined; className: string }
>;
- for (const binding of rawConfig?.durable_objects.bindings) {
+ const bindings = rawConfig.durable_objects.bindings;
+ for (const binding of bindings) {
Reflect.set(output, binding.name, { className: binding.class_name });
}
return output;
diff --git a/packages/integrations/cloudflare/src/utils/prependForwardSlash.ts b/packages/integrations/cloudflare/src/utils/prependForwardSlash.ts
index b66b588f3..a034c1268 100644
--- a/packages/integrations/cloudflare/src/utils/prependForwardSlash.ts
+++ b/packages/integrations/cloudflare/src/utils/prependForwardSlash.ts
@@ -1,3 +1,3 @@
export function prependForwardSlash(path: string) {
- return path[0] === '/' ? path : '/' + path;
+ return path[0] === '/' ? path : `/${path}`;
}
diff --git a/packages/integrations/cloudflare/src/utils/wasm-module-loader.ts b/packages/integrations/cloudflare/src/utils/wasm-module-loader.ts
index b93b9ef29..c186d2648 100644
--- a/packages/integrations/cloudflare/src/utils/wasm-module-loader.ts
+++ b/packages/integrations/cloudflare/src/utils/wasm-module-loader.ts
@@ -57,33 +57,32 @@ export default wasmModule
if (isDev) {
// no need to wire up the assets in dev mode, just rewrite
return base64Module;
- } else {
- // just some shared ID
- let hash = hashString(base64);
- // emit the wasm binary as an asset file, to be picked up later by the esbuild bundle for the worker.
- // give it a shared deterministic name to make things easy for esbuild to switch on later
- const assetName = path.basename(filePath).split('.')[0] + '.' + hash + '.wasm';
- this.emitFile({
- type: 'asset',
- // put it explicitly in the _astro assets directory with `fileName` rather than `name` so that
- // vite doesn't give it a random id in its name. We need to be able to easily rewrite from
- // the .mjs loader and the actual wasm asset later in the ESbuild for the worker
- fileName: path.join(assetsDirectory, assetName),
- source: fs.readFileSync(filePath),
- });
+ }
+ // just some shared ID
+ const hash = hashString(base64);
+ // emit the wasm binary as an asset file, to be picked up later by the esbuild bundle for the worker.
+ // give it a shared deterministic name to make things easy for esbuild to switch on later
+ const assetName = `${path.basename(filePath).split('.')[0]}.${hash}.wasm`;
+ this.emitFile({
+ type: 'asset',
+ // put it explicitly in the _astro assets directory with `fileName` rather than `name` so that
+ // vite doesn't give it a random id in its name. We need to be able to easily rewrite from
+ // the .mjs loader and the actual wasm asset later in the ESbuild for the worker
+ fileName: path.join(assetsDirectory, assetName),
+ source: fs.readFileSync(filePath),
+ });
- // however, by default, the SSG generator cannot import the .wasm as a module, so embed as a base64 string
- const chunkId = this.emitFile({
- type: 'prebuilt-chunk',
- fileName: assetName + '.mjs',
- code: base64Module,
- });
+ // however, by default, the SSG generator cannot import the .wasm as a module, so embed as a base64 string
+ const chunkId = this.emitFile({
+ type: 'prebuilt-chunk',
+ fileName: `${assetName}.mjs`,
+ code: base64Module,
+ });
- return `
+ return `
import wasmModule from "__WASM_ASSET__${chunkId}.wasm.mjs";
export default wasmModule;
`;
- }
},
// output original wasm file relative to the chunk