Skip to content

Commit

Permalink
feat: set up env.d.ts on astro sync
Browse files Browse the repository at this point in the history
  • Loading branch information
bholmesdev committed Jan 10, 2023
1 parent b2b7e4d commit 07ff9c8
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 57 deletions.
2 changes: 2 additions & 0 deletions packages/astro/src/cli/sync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { contentObservable, createContentTypesGenerator } from '../../content/in
import { getTimeStat } from '../../core/build/util.js';
import { AstroError, AstroErrorData } from '../../core/errors/index.js';
import { info, LogOptions } from '../../core/logger/core.js';
import { setUpEnvTs } from '../../vite-plugin-inject-env-ts/index.js';

export async function sync(
settings: AstroSettings,
Expand All @@ -26,6 +27,7 @@ export async function sync(
}

info(logging, 'content', `Types generated ${dim(getTimeStat(timerStart, performance.now()))}`);
await setUpEnvTs({ settings, logging, fs });

return 0;
}
36 changes: 0 additions & 36 deletions packages/astro/src/content/types-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ export async function createContentTypesGenerator({

const contentTypesBase = await fs.promises.readFile(contentPaths.typesTemplate, 'utf-8');

await addContentTypeReference({ fs, logging, settings });

async function init() {
await handleEvent({ name: 'add', entry: contentPaths.config }, { logLevel: 'warn' });
const globResult = await glob('./**/*.*', {
Expand Down Expand Up @@ -347,37 +345,3 @@ function warnNonexistentCollections({
}
}
}

async function addContentTypeReference({
settings,
fs,
logging,
}: {
settings: AstroSettings;
fs: typeof fsMod;
logging: LogOptions;
}) {
const envTsPath = getEnvTsPath(settings.config);
let typesEnvContents = '';
try {
typesEnvContents = await fs.promises.readFile(envTsPath, 'utf-8');
} catch {
/*
* `src/env.d.ts` from Astro starter template is not present.
* Fail silently, and allow user to wire up type manually.
*/
return;
}

const expectedTypeReference = getDotAstroTypeReference(settings.config);

const typeEnvRelativeToRoot = normalizePath(
path.relative(fileURLToPath(settings.config.root), fileURLToPath(envTsPath))
);

if (!typesEnvContents.includes(expectedTypeReference)) {
typesEnvContents = `${expectedTypeReference}\n${typesEnvContents}`;
await fs.promises.writeFile(envTsPath, typesEnvContents, 'utf-8');
info(logging, 'content', `Added types reference to \`${typeEnvRelativeToRoot}\``);
}
}
73 changes: 52 additions & 21 deletions packages/astro/src/vite-plugin-inject-env-ts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,62 @@ export function astroInjectEnvTsPlugin({
fs: typeof fsMod;
}): Plugin {
return {
name: 'astro-inject-ts-env',
name: 'astro-inject-env-ts',
// Use `post` to ensure project setup is complete
// Ex. `.astro` types have been written
enforce: 'post',
async config() {
const envTsPath = getEnvTsPath(settings.config);
if (fs.existsSync(envTsPath)) return;

let referenceDefs: string[] = [];
if (settings.config.integrations.find((i) => i.name === '@astrojs/image')) {
referenceDefs.push('/// <reference types="@astrojs/image/client" />');
} else {
referenceDefs.push('/// <reference types="astro/client" />');
}

if (fs.existsSync(getContentPaths(settings.config).cacheDir)) {
referenceDefs.push(getDotAstroTypeReference(settings.config));
}

const envTsPathRelativetoRoot = normalizePath(
path.relative(fileURLToPath(settings.config.root), fileURLToPath(envTsPath))
);

await fs.promises.writeFile(envTsPath, referenceDefs.join('\n'));
info(logging, 'astro', `Added ${bold(envTsPathRelativetoRoot)} types`);
await setUpEnvTs({ settings, logging, fs });
},
};
}

export async function setUpEnvTs({
settings,
logging,
fs,
}: {
settings: AstroSettings;
logging: LogOptions;
fs: typeof fsMod;
}) {
const envTsPath = getEnvTsPath(settings.config);
const dotAstroDir = getContentPaths(settings.config).cacheDir;
const dotAstroTypeReference = getDotAstroTypeReference(settings.config);
const envTsPathRelativetoRoot = normalizePath(
path.relative(fileURLToPath(settings.config.root), fileURLToPath(envTsPath))
);

if (fs.existsSync(envTsPath)) {
// Add `.astro` types reference if none exists
if (!fs.existsSync(dotAstroDir)) return;

let typesEnvContents = await fs.promises.readFile(envTsPath, 'utf-8');
const expectedTypeReference = getDotAstroTypeReference(settings.config);

if (!typesEnvContents.includes(expectedTypeReference)) {
typesEnvContents = `${expectedTypeReference}\n${typesEnvContents}`;
await fs.promises.writeFile(envTsPath, typesEnvContents, 'utf-8');
info(logging, 'content', `Added ${bold(envTsPathRelativetoRoot)} types`);
}
} else {
// Otherwise, inject the `env.d.ts` file
let referenceDefs: string[] = [];
if (settings.config.integrations.find((i) => i.name === '@astrojs/image')) {
referenceDefs.push('/// <reference types="@astrojs/image/client" />');
} else {
referenceDefs.push('/// <reference types="astro/client" />');
}

if (fs.existsSync(dotAstroDir)) {
referenceDefs.push(dotAstroTypeReference);
}

const envTsPathRelativetoRoot = normalizePath(
path.relative(fileURLToPath(settings.config.root), fileURLToPath(envTsPath))
);

await fs.promises.writeFile(envTsPath, referenceDefs.join('\n'));
info(logging, 'astro', `Added ${bold(envTsPathRelativetoRoot)} types`);
}
}

0 comments on commit 07ff9c8

Please sign in to comment.