const attributesMarkerLength = '&attributes='.length; function generateAttributedId(rawId: string, attributes?: Record): string { if (!attributes || Object.keys(attributes).length === 0) { return rawId; } // Rollup builds this with Object.fromEntries, which keeps a "__proto__" attribute as an own key const sortedAttributes: Record = Object.create(null); for (const key of Object.keys(attributes).sort()) { sortedAttributes[key] = attributes[key]; } return `${rawId}${rawId.includes('?') ? '&' : '?'}attributes=${encodeURIComponent( JSON.stringify(sortedAttributes) )}`; } export function stripAttributes(id: string): string { const attributesMarkerIndex = Math.max( id.lastIndexOf('?attributes='), id.lastIndexOf('&attributes=') ); if (attributesMarkerIndex === -1) { return id; } try { const rawId = id.slice(0, attributesMarkerIndex); const attributes = JSON.parse( decodeURIComponent(id.slice(attributesMarkerIndex + attributesMarkerLength)) ); if (generateAttributedId(rawId, attributes) === id) { return rawId; } } catch { // fall through to treat the id as opaque } return id; }