Skip to content

Commit

Permalink
feat: astro:env allow schema keys to include numbers (#11437)
Browse files Browse the repository at this point in the history
Co-authored-by: Florian Lefebvre <contact@florian-lefebvre.dev>
  • Loading branch information
NuroDev and florian-lefebvre authored Jul 10, 2024
1 parent ea4bc04 commit 6ccb30e
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/loud-socks-doubt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes a case where Astro's config `experimental.env.schema` keys did not allow numbers. Numbers are still not allowed as the first character to be able to generate valid JavaScript identifiers
14 changes: 10 additions & 4 deletions packages/astro/src/env/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,18 @@ const EnvFieldMetadata = z.union([
SecretServerEnvFieldMetadata,
]);

const KEY_REGEX = /^[A-Z_]+$/;
const EnvSchemaKey = z
.string()
.min(1)
.refine(([firstChar]) => isNaN(Number.parseInt(firstChar)), {
message: 'A valid variable name cannot start with a number.',
})
.refine((str) => /^[A-Z0-9_]+$/.test(str), {
message: 'A valid variable name can only contain uppercase letters, numbers and underscores.',
});

export const EnvSchema = z.record(
z.string().regex(KEY_REGEX, {
message: 'A valid variable name can only contain uppercase letters and underscores.',
}),
EnvSchemaKey,
z.intersection(EnvFieldMetadata, EnvFieldType)
);

Expand Down
38 changes: 38 additions & 0 deletions packages/astro/test/units/config/config-validate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { describe, it } from 'node:test';
import stripAnsi from 'strip-ansi';
import { z } from 'zod';
import { validateConfig } from '../../../dist/core/config/validate.js';
import { envField } from '../../../dist/env/config.js';
import { formatConfigErrorMessage } from '../../../dist/core/messages.js';

describe('Config Validation', () => {
Expand Down Expand Up @@ -367,5 +368,42 @@ describe('Config Validation', () => {
).catch((err) => err)
);
});

it('Should allow schema variables with numbers', () => {
assert.doesNotThrow(() =>
validateConfig(
{
experimental: {
env: {
schema: {
ABC123: envField.string({ access: 'public', context: 'server' }),
},
},
},
},
process.cwd()
).catch((err) => err)
);
});

it('Should not allow schema variables starting with a number', async () => {
const configError = await validateConfig(
{
experimental: {
env: {
schema: {
"123ABC": envField.string({ access: 'public', context: 'server' }),
},
},
},
},
process.cwd()
).catch((err) => err);
assert.equal(configError instanceof z.ZodError, true);
assert.equal(
configError.errors[0].message,
'A valid variable name cannot start with a number.'
);
});
});
});

0 comments on commit 6ccb30e

Please sign in to comment.