foliojs / fontkit

An advanced font engine for Node and the browser
1.45k stars 213 forks source link

Fix reference error for certain fonts #286

Closed fstrube closed 2 years ago

fstrube commented 2 years ago

Fixes #282.

This branch fixes a ReferenceError that gets thrown when parsing certain fonts, including the Playfair Display font that is in the fontkit repository. The error started happening when version 1.9.0 of fontkit was released.

     ReferenceError: Cannot access 'c3x' before initialization

The fix involved refactoring the parse() function to use block-scoping inside the switch case statements in that function. See the MDN docs on redeclarations.

Pomax commented 2 years ago

It might make sense to preallocate all the variables outside the switch, as that would have been the effective behaviour when babel transpiled to var (due to hoisting) anyway.

fstrube commented 2 years ago

@Pomax @blikblum I preallocated all the variables outside the switch as you suggested. The diff is much smaller, which is nice.

fstrube commented 2 years ago

Thanks for reviewing @Pomax! I made those two changes that you suggested.

There are also a few more instances of var declarations in that function.

Do you think it is worth changing them to let? Or should we leave them as is to avoid any unexpected behavior?

Pomax commented 2 years ago

Any opportunity to move from scope-hoisting to block scoped vars is a good opportunity I'd say, but I'll let @devongovett decide whether that's something he would like to see in this PR.

fstrube commented 2 years ago

Hi @devongovett, would you mind taking a look at this? It is causing most of our pdfkit projects that rely on OTF fonts to fail. I'm hoping we can get this merged in soon, then get https://github.com/foliojs/pdfkit/pull/1367 updated and merged as well.

AlainGourves commented 1 year ago

It is possible to make a new release with this PR ? The latest version is 2.0.2, released on June 19 2022 before this PR, so the error

ReferenceError: Cannot access 'c3x' before initialization

still occurs (for example with the font PlayfairDisplay-Regular.otf found in /test/data/PlayfairDisplay).

Thanks in advance!