protocols.test.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /// <reference types="vite/client" />
  2. import { describe, expect, it } from 'vitest';
  3. import { InboundSettingsSchema } from '@/schemas/protocols';
  4. // import.meta.glob (eager, default-import) gives us {path: parsedJson} at
  5. // compile time — no fs, no @types/node. Vitest inherits the vite/client
  6. // shape so this stays typed.
  7. const inboundFixtures = import.meta.glob<unknown>(
  8. './golden/fixtures/inbound/*.json',
  9. { eager: true, import: 'default' },
  10. );
  11. function fixtureName(path: string): string {
  12. const file = path.split('/').pop() ?? path;
  13. return file.replace(/\.json$/, '');
  14. }
  15. describe('InboundSettingsSchema fixtures', () => {
  16. const entries = Object.entries(inboundFixtures).sort(([a], [b]) => a.localeCompare(b));
  17. expect(entries.length, 'expected at least one fixture under golden/fixtures/inbound').toBeGreaterThan(0);
  18. for (const [path, raw] of entries) {
  19. it(`parses ${fixtureName(path)} byte-stably`, () => {
  20. const parsed = InboundSettingsSchema.parse(raw);
  21. expect(parsed).toMatchSnapshot();
  22. });
  23. }
  24. });
  25. // The fixture tests above pin coerced values only via regenerable snapshots. These
  26. // assert the load-bearing transforms directly, so a broken coercion fails independently
  27. // of the snapshot baseline.
  28. describe('InboundSettingsSchema coercions', () => {
  29. it('vmess: defaults alterId to 0 and coerces a string tgId to a number', () => {
  30. const parsed = InboundSettingsSchema.parse({
  31. protocol: 'vmess',
  32. settings: { clients: [{ id: 'u1', email: '[email protected]', tgId: '12345' }] },
  33. });
  34. if (parsed.protocol !== 'vmess') throw new Error('discriminator narrowed to the wrong protocol');
  35. const client = parsed.settings.clients[0];
  36. expect(client.alterId).toBe(0); // .default(0) injected for omitted field
  37. expect(client.tgId).toBe(12345); // string -> number transform
  38. });
  39. it('vmess: a non-numeric tgId coerces to 0', () => {
  40. const parsed = InboundSettingsSchema.parse({
  41. protocol: 'vmess',
  42. settings: { clients: [{ id: 'u1', email: '[email protected]', tgId: 'not-a-number' }] },
  43. });
  44. if (parsed.protocol !== 'vmess') throw new Error('wrong protocol');
  45. expect(parsed.settings.clients[0].tgId).toBe(0); // Number(v) || 0
  46. });
  47. it('vless: defaults decryption and encryption to "none"', () => {
  48. const parsed = InboundSettingsSchema.parse({ protocol: 'vless', settings: { clients: [] } });
  49. if (parsed.protocol !== 'vless') throw new Error('wrong protocol');
  50. expect(parsed.settings.decryption).toBe('none');
  51. expect(parsed.settings.encryption).toBe('none');
  52. });
  53. });