diff --git a/.changeset/fix-stackblitz-path-to-regexp.md b/.changeset/fix-stackblitz-path-to-regexp.md new file mode 100644 index 000000000000..3cee714916fc --- /dev/null +++ b/.changeset/fix-stackblitz-path-to-regexp.md @@ -0,0 +1,12 @@ +--- +'@data-client/rest': patch +--- + +Fix compatibility with StackBlitz WebContainers + +Consolidate `path-to-regexp` imports into a single module to avoid +CJS/ESM interop failures in StackBlitz's WebContainers environment, +where webpack could not resolve the `pathToRegexp` named export from +the CJS `path-to-regexp` package. + +Also caches `pathToRegexp()` results, improving repeated `testKey()` performance. diff --git a/packages/rest/src/RestEndpoint.js b/packages/rest/src/RestEndpoint.js index cf8bb9b38ebe..b362163b3f05 100644 --- a/packages/rest/src/RestEndpoint.js +++ b/packages/rest/src/RestEndpoint.js @@ -1,12 +1,16 @@ import { Endpoint } from '@data-client/endpoint'; -import { pathToRegexp } from 'path-to-regexp'; import extractCollection from './extractCollection.js'; import mapCollection from './mapCollection.js'; import NetworkError from './NetworkError.js'; import { createPaginationSchema } from './paginatedCollections.js'; import paramsToString from './paramsToString.js'; -import { getUrlBase, getUrlTokens, isPojo } from './RestHelpers.js'; +import { + getUrlBase, + getUrlTokens, + getPathRegex, + isPojo, +} from './RestHelpers.js'; /** Simplifies endpoint definitions that follow REST patterns * @@ -196,7 +200,7 @@ Response (first 300 characters): ${text.substring(0, 300)}`; } get pathRegex() { - return pathToRegexp(this.path).regexp; + return getPathRegex(this.path); } testKey(key) { diff --git a/packages/rest/src/RestHelpers.ts b/packages/rest/src/RestHelpers.ts index ead662737e24..66315a5038c4 100644 --- a/packages/rest/src/RestHelpers.ts +++ b/packages/rest/src/RestHelpers.ts @@ -1,4 +1,11 @@ -import { compile, PathFunction, parse, Token, ParamData } from 'path-to-regexp'; +import { + compile, + PathFunction, + parse, + pathToRegexp, + Token, + ParamData, +} from 'path-to-regexp'; import { ShortenPath } from './pathTypes.js'; @@ -18,6 +25,14 @@ export function getUrlTokens(path: string): Set { return urlTokensCache[path]; } +const pathRegexCache: Record = Object.create(null); +export function getPathRegex(path: string): RegExp { + if (!(path in pathRegexCache)) { + pathRegexCache[path] = pathToRegexp(path).regexp; + } + return pathRegexCache[path]; +} + function tokenMap(tokens: Token[]): Set { const tokenNames = new Set(); for (const token of tokens) {