sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.65k stars 150 forks source link

esm.sh builds are broken if using FormatRegistry #843

Closed 1951FDG closed 3 months ago

1951FDG commented 3 months ago

Hi there,

When importing via esm.sh

https://esm.sh/@sinclair/typebox https://esm.sh/@sinclair/typebox/value

import { FormatRegistry, Type } from './esm/typebox.mjs';
import { Value } from './esm/value.js';
FormatRegistry.Set('date', IsDate);
const dataSchema = Type.Object({
  updated_at: Type.String({ format: 'date' }),
});

FormatRegistry is accessible, but doing the following, will fail with ("message": "Unknown format 'date'")

Value.Check(dataSchema, data);

It seems https://esm.sh/@sinclair/typebox/value > https://esm.sh/v135/@sinclair/typebox@0.32.22/es2022/value.js, has no mention of FormatRegistry, it seems to be stripped out.

Also wouldn't it be better for FormatRegistry to be it's own import, instead of part of typebox import. It's the first time I ran into this issue using esm.sh, so far other dependencies have never given me any issues. I'm hoping you can help me out.

I copied the node esm build folder, and am using this as a workaround now:

import { Type } from './import/type/index.mjs';
import { Value } from './import/value/value/index.mjs';
import { FormatRegistry } from './import/type/registry/index.mjs';
sinclairzx81 commented 3 months ago

@1951FDG Hi,

This is a known issue with esm.sh where it appears to instance the same module multiple times. This is actually broken behavior as modules should be singleton. In terms of how this impacts TypeBox, rather than having a singular FormatRegistry, multiple registries are being instanced (where the registry you define formats on is different to the registry observed by TypeBox internally)

I've drafted an issue about this last year, unfortunately, there doesn't appear to be any feedback / follow up on it. I've since had to remove esm.sh as a distribution option for TypeBox. But you can read about the issue at the following URL

https://github.com/esm-dev/esm.sh/issues/741

Will close off this issue here, but best to track things over at the esm.sh repository. The recommendation moving forward is to pull TypeBox from NPM (and where other platforms such as Deno can also source the package there)

Hope this brings some insight. S