export default async function deepSelector (selector) {
  if (!selector) {
    return []
  }

  const roots = [document]

  // Add all shadow roots including nested.
  for (const el of roots) {
    const wcs = [...el.querySelectorAll('[data-name="WebComponent"] *')].filter(wcEl => wcEl.tagName?.includes('-'))
    for (const wc of wcs) {
      await customElements.whenDefined(wc.tagName.toLowerCase())
      wc?.shadowRoot?.querySelectorAll && roots.push(wc.shadowRoot)
    }
  }

  // Get all the results across all shadow roots.
  const result = []
  for (const root of roots) {
    try {
      result.push(...root.querySelectorAll(selector))
    } catch {
      // Ignore incorrect selector.
    }
  }

  return result
}
