Skip to content

TypeError: Invalid Version when resolving npm imports without cached packages #2053

@shallwefootball

Description

@shallwefootball

Bug

When starting Observable Framework dev server with a clean cache (no .observablehq/cache/_npm/), pages that import npm packages crash with:

TypeError: Invalid Version: 7

The page renders only Invalid Version: 7 with no sidebar, content, or error details.

Steps to reproduce

  1. Create a fresh Observable Framework project (v1.13.4)
  2. Add a page with import * as d3 from "npm:d3@7.9.0" in a fenced js block
  3. Delete .observablehq/ cache directory (or start fresh)
  4. Run npx observable preview
  5. Open any page that imports d3

Expected: Page renders normally
Actual: Page shows only Invalid Version: 7

Note: if .observablehq/cache/_npm/d3@7.9.0/ already exists from a previous session, the error does NOT occur. This only happens on a clean cache.

Root cause

In dist/npm.js, resolveNpmImport() calls rsort() from semver on cached version strings. When resolving a package for the first time (no cache), a version string that isn't valid semver (e.g. bare "7") can end up in the versions array. semver.rsort() then throws because "7" is not a valid semver string.

Specifically at lines ~160 and ~194:

cache.set(key, rsort(value));  // crashes if value contains non-semver string
cache.set(name, versions ? rsort(versions.concat(version)) : [version]);

Workaround

Wrapping rsort() calls in try-catch prevents the crash:

try { cache.set(key, rsort(value)); } catch(e) { cache.set(key, value); }

Environment

  • Observable Framework: 1.13.4
  • Node: v22.14.0 and v22.20.0 (both affected)
  • OS: Ubuntu 24.04
  • semver: 7.7.4
  • npm: 10.9.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions