//     __ _____ _____ _____
//  __|  |   __|     |   | |  JSON for Modern C++
// |  |  |__   |  |  | | | |  version 3.12.0
// |_____|_____|_____|_|___|  https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#pragma once

#include <nlohmann/detail/abi_macros.hpp>
#include <nlohmann/detail/iterators/primitive_iterator.hpp>

NLOHMANN_JSON_NAMESPACE_BEGIN
namespace detail
{

/*!
@brief an iterator value

@note This structure could easily be a union, but MSVC currently does not allow
unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
*/
template<typename BasicJsonType> struct internal_iterator
{
    /// iterator for JSON objects
    typename BasicJsonType::object_t::iterator object_iterator {};
    /// iterator for JSON arrays
    typename BasicJsonType::array_t::iterator array_iterator {};
    /// generic iterator for all other types
    primitive_iterator_t primitive_iterator {};
};

}  // namespace detail
NLOHMANN_JSON_NAMESPACE_END


import 'vite/modulepreload-polyfill'
import cssUrl from '../styles/url.css?url'
import waterContainer from './water-container.svg'

const cssLink = document.createElement('link')
cssLink.rel = 'stylesheet'
cssLink.href = cssUrl
document.querySelector('head').prepend(cssLink)

const dummyMeta = document.createElement('meta')
dummyMeta.name = 'dummy'
dummyMeta.content = waterContainer
document.querySelector('head').append(dummyMeta)

export const colorClass = 'text-black'

export function colorHeading() {
  document.querySelector('h1').className = colorClass
}

colorHeading()

if (import.meta.hot) {
  import.meta.hot.accept()
}


#include <iostream>
#include <nlohmann/json.hpp>
#include <iomanip> // for std::setw

using json = nlohmann::json;
using namespace nlohmann::literals;

int main()
{
    // the original document
    json document = R"({
                "title": "Goodbye!",
                "author": {
                    "givenName": "John",
                    "familyName": "Doe"
                },
                "tags": [
                    "example",
                    "sample"
                ],
                "content": "This will be unchanged"
            })"_json;

    // the patch
    json patch = R"({
                "title": "Hello!",
                "phoneNumber": "+01-123-456-7890",
                "author": {
                    "familyName": null
                },
                "tags": [
                    "example"
                ]
            })"_json;

    // apply the patch
    document.merge_patch(patch);

    // output original and patched document
    std::cout << std::setw(4) << document << std::endl;
}


// This file tests `ViteTypeOptions` in `packages/vite/types/importMeta.d.ts`
import type { ExpectFalse, ExpectTrue } from '@type-challenges/utils'

// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface TypeOptions1 {}
interface TypeOptions2 {
  strictImportMetaEnv: unknown
}
interface TypeOptions3 {
  unknownKey: unknown
}

type IsEnabled<Opts, Key extends string> = Key extends keyof Opts ? true : false

export type cases = [
  ExpectFalse<IsEnabled<TypeOptions1, 'strictImportMetaEnv'>>,
  ExpectTrue<IsEnabled<TypeOptions2, 'strictImportMetaEnv'>>,
  ExpectFalse<IsEnabled<TypeOptions3, 'strictImportMetaEnv'>>,
]

export {}


:root {
  color-scheme: light dark;
  background-color: #ffffff;
}

@media (prefers-color-scheme: dark) {
  :root {
    background-color: #16171d;
  }
}

body {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 320px;
  min-height: 100svh;
  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  overflow-x: hidden;
}


#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // create empty JSON Pointer
    json::json_pointer ptr("/foo/bar/baz");
    std::cout << "\"" << ptr << "\"\n";

    // call pop_front()
    ptr.pop_front();
    std::cout << "\"" << ptr << "\"\n";

    ptr.pop_front();
    std::cout << "\"" << ptr << "\"\n";

    ptr.pop_front();
    std::cout << "\"" << ptr << "\"\n";
}


import { fileURLToPath } from 'node:url'
import { describe, expect, test } from 'vitest'
import { resolveConfig } from '../config'
import { createIsConfiguredAsExternal } from '../external'
import { PartialEnvironment } from '../baseEnvironment'

describe('createIsConfiguredAsExternal', () => {
  test('default', async () => {
    const isExternal = await createIsExternal()
    expect(isExternal('@vitejs/cjs-ssr-dep')).toBe(false)
  })

  test('force external', async () => {
    const isExternal = await createIsExternal(true)
    expect(isExternal('@vitejs/cjs-ssr-dep')).toBe(true)
  })
})

async function createIsExternal(external?: true) {
  const resolvedConfig = await resolveConfig(
    {
      configFile: false,
      root: fileURLToPath(new URL('./', import.meta.url)),
      resolve: { external },
    },
    'serve',
  )
  const environment = new PartialEnvironment('ssr', resolvedConfig)
  return createIsConfiguredAsExternal(environment)
}


// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Simple test for a fuzzer: find the interesting argument for div.
#include <assert.h>
#include <cstdint>
#include <cstring>
#include <cstddef>
#include <iostream>

static volatile int Sink;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size < 4) return 0;
  int a;
  memcpy(&a, Data, 4);
  Sink = 12345678 / (987654 - a);
  return 0;
}


import { component$, useSignal } from '@builder.io/qwik'

import qwikLogo from './assets/qwik.svg'
import viteLogo from './assets/vite.svg'
import heroImg from './assets/hero.png'
import './app.css'

export const App = component$(() => {
  const count = useSignal(0)

  return (
    <>

Get started

            Edit src/app.tsx and save to test HMR

        <button type="button" class="counter" onClick$={() => count.value++}>
          Count is {count.value}
        </button>

          <svg class="icon" role="presentation" aria-hidden="true">
            <use href="/icons.svg#documentation-icon"></use>
          </svg>

Documentation

Your questions, answered

                Explore Vite

                Learn more

          <svg class="icon" role="presentation" aria-hidden="true">
            <use href="/icons.svg#social-icon"></use>
          </svg>

Connect with us

Join the Vite community

                <svg class="button-icon" role="presentation" aria-hidden="true">
                  <use href="/icons.svg#github-icon"></use>
                </svg>
                GitHub

                <svg class="button-icon" role="presentation" aria-hidden="true">
                  <use href="/icons.svg#discord-icon"></use>
                </svg>
                Discord

                <svg class="button-icon" role="presentation" aria-hidden="true">
                  <use href="/icons.svg#x-icon"></use>
                </svg>
                X.com

                <svg class="button-icon" role="presentation" aria-hidden="true">
                  <use href="/icons.svg#bluesky-icon"></use>
                </svg>
                Bluesky

    </>
  )
})


# <small>nlohmann::basic_json::</small>clear

```cpp
void clear() noexcept;
```

Clears the content of a JSON value and resets it to the default value as if [`basic_json(value_t)`](basic_json.md) would
have been called with the current value type from [`type()`](type.md):

| Value type | initial value        |
|------------|----------------------|
| null       | `null`               |
| boolean    | `false`              |
| string     | `""`                 |
| number     | `0`                  |
| binary     | An empty byte vector |
| object     | `{}`                 |
| array      | `[]`                 |

Has the same effect as calling

```.cpp
*this = basic_json(type());
```

## Exception safety

No-throw guarantee: this function never throws exceptions.

## Complexity

Linear in the size of the JSON value.

## Notes

All iterators, pointers, and references related to this container are invalidated.

## Examples

??? example

    The example below shows the effect of `clear()` to different
    JSON types.

    ```cpp
    --8<-- "examples/clear.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/clear.output"
    ```

## Version history

- Added in version 1.0.0.
- Added support for binary types in version 3.8.0.


import { existsSync, readdirSync } from 'node:fs'
import { posix, resolve, win32 } from 'node:path'
import { fileURLToPath } from 'node:url'
import { setTimeout } from 'node:timers/promises'
import { describe, expect, it, vi } from 'vitest'
import { isWindows } from '../../../../shared/utils'
import type { ExternalFetchResult } from '../../../../shared/invokeMethods'
import { createServer } from '../../../server'
import {
  createRunnableDevEnvironment,
  isRunnableDevEnvironment,
} from '../../../server/environments/runnableEnvironment'
import type { HMRLogger } from '../../../../../dist/node/module-runner'
import { createModuleRunnerTester } from './utils'

const _URL = URL

describe('module runner initialization', async () => {
  const it = await createModuleRunnerTester({
    resolve: {
      external: ['tinyglobby'],
      noExternal: ['@oxc-project/runtime'],
    },
  })

  it('correctly runs ssr code', async ({ runner }) => {
    const mod = await runner.import('/fixtures/simple.js')
    expect(mod.test).toEqual('I am initialized')

    // loads the same module if id is a file url
    const fileUrl = new _URL('./fixtures/simple.js', import.meta.url)
    const mod2 = await runner.import(fileUrl.toString())
    expect(mod).toBe(mod2)

    // loads the same module if id is a file path
    const filePath = fileURLToPath(fileUrl)
    const mod3 = await runner.import(filePath)
    expect(mod).toBe(mod3)
  })

  it('can load virtual modules as an entry point', async ({ runner }) => {
    const mod = await runner.import('virtual:test')
    expect(mod.msg).toBe('virtual')

    // already resolved id works similar to `transformRequest`
    expect(await runner.import(`\0virtual:normal`)).toMatchInlineSnapshot(`
      {
        "default": "ok",
      }
    `)

    // escaped virtual module id works
    expect(await runner.import(`/@id/__x00__virtual:normal`))
      .toMatchInlineSnapshot(`
      {
        "default": "ok",
      }
    `)

    // timestamp query works
    expect(await runner.import(`virtual:normal?t=${Date.now()}`))
      .toMatchInlineSnapshot(`
      {
        "default": "ok",
      }
    `)

    // other arbitrary queries don't work
    await expect(() =>
      runner.import('virtual:normal?abcd=1234'),
    ).rejects.toMatchObject({
      message: expect.stringContaining(
        'Failed to load url virtual:normal?abcd=1234',
      ),
    })
  })

  it('css is loaded correctly', async ({ runner }) => {
    const css = await runner.import('/fixtures/test.css')
    expect(css.default).toBe(undefined)
    const module = await runner.import('/fixtures/test.module.css')
    expect(module).toMatchObject({
      default: {
        test: expect.stringMatching(/^_test_/),
      },
      test: expect.stringMatching(/^_test_/),
    })
  })

  it('assets are loaded correctly', async ({ runner }) => {
    const assets = await runner.import('/fixtures/assets.js')
    expect(assets).toMatchObject({
      mov: '/fixtures/assets/placeholder.mov',
      txt: '/fixtures/assets/placeholder.txt',
      png: '/fixtures/assets/placeholder.png',
      webp: '/fixtures/assets/placeholder.webp',
    })
  })

  it('ids with Vite queries are loaded correctly', async ({ runner }) => {
    const raw = await runner.import('/fixtures/simple.js?raw')
    expect(raw.default).toMatchInlineSnapshot(`
      "export const test = 'I am initialized'

      import.meta.hot?.accept()
      "
    `)
    const url = await runner.import('/fixtures/simple.js?url')
    expect(url.default).toMatchInlineSnapshot(`"/fixtures/simple.js"`)
    const inline = await runner.import('/fixtures/test.css?inline')
    expect(inline.default).toMatchInlineSnapshot(`
      ".test {
        color: red;
      }
      "
    `)
  })

  it('modules with query strings are treated as different modules', async ({
    runner,
  }) => {
    const modSimple = await runner.import('/fixtures/simple.js')
    const modUrl = await runner.import('/fixtures/simple.js?url')
    expect(modSimple).not.toBe(modUrl)
    expect(modUrl.default).toBe('/fixtures/simple.js')
  })

  it('exports is not modifiable', async ({ runner }) => {
    const mod = await runner.import('/fixtures/simple.js')
    expect(Object.isSealed(mod)).toBe(true)
    expect(() => {
      mod.test = 'I am modified'
    }).toThrowErrorMatchingInlineSnapshot(
      `[TypeError: Cannot set property test of [object Module] which has only a getter]`,
    )
    expect(() => {
      delete mod.test
    }).toThrowErrorMatchingInlineSnapshot(
      `[TypeError: Cannot delete property 'test' of [object Module]]`,
    )
    expect(() => {
      Object.defineProperty(mod, 'test', { value: 'I am modified' })
    }).toThrowErrorMatchingInlineSnapshot(
      `[TypeError: Cannot redefine property: test]`,
    )
    expect(() => {
      mod.other = 'I am added'
    }).toThrowErrorMatchingInlineSnapshot(
      `[TypeError: Cannot add property other, object is not extensible]`,
    )
  })

  it('throws the same error', async ({ runner }) => {
    expect.assertions(3)
    const s = Symbol()
    try {
      await runner.import('/fixtures/has-error.js')
    } catch (e) {
      expect(e[s]).toBeUndefined()
      e[s] = true
      expect(e[s]).toBe(true)
    }

    try {
      await runner.import('/fixtures/has-error.js')
    } catch (e) {
      expect(e[s]).toBe(true)
    }
  })

  it('importing external cjs library checks exports', async ({ runner }) => {
    await expect(() => runner.import('/fixtures/cjs-external-non-existing.js'))
      .rejects.toThrowErrorMatchingInlineSnapshot(`
      [SyntaxError: [vite] Named export 'nonExisting' not found. The requested module '@vitejs/cjs-external' is a CommonJS module, which may not support all module.exports as named exports.
      CommonJS modules can always be imported via the default export, for example using:

      import pkg from '@vitejs/cjs-external';
      const {nonExisting} = pkg;
      ]
    `)
    // subsequent imports of the same external package should not throw if imports are correct
    await expect(
      runner.import('/fixtures/cjs-external-existing.js'),
    ).resolves.toMatchObject({
      result: 'world',
    })
  })

  it('importing external esm library checks exports', async ({ runner }) => {
    await expect(() =>
      runner.import('/fixtures/esm-external-non-existing.js'),
    ).rejects.toThrowErrorMatchingInlineSnapshot(
      `[SyntaxError: [vite] The requested module '@vitejs/esm-external' does not provide an export named 'nonExisting']`,
    )
    // subsequent imports of the same external package should not throw if imports are correct
    await expect(
      runner.import('/fixtures/esm-external-existing.js'),
    ).resolves.toMatchObject({
      result: 'world',
    })
  })

  it("dynamic import doesn't produce duplicates", async ({ runner }) => {
    const mod = await runner.import('/fixtures/dynamic-import.js')
    const modules = await mod.initialize()
    // toBe checks that objects are actually the same, not just structurally
    // using toEqual here would be a mistake because it check the structural difference
    expect(modules.static).toBe(modules.dynamicProcessed)
    expect(modules.static).toBe(modules.dynamicRelative)
    expect(modules.static).toBe(modules.dynamicAbsolute)
    expect(modules.static).toBe(modules.dynamicAbsoluteExtension)
    expect(modules.static).toBe(modules.dynamicAbsoluteFull)
    expect(modules.static).toBe(modules.dynamicFileUrl)
  })

  it('correctly imports a virtual module', async ({ runner }) => {
    const mod = await runner.import('/fixtures/virtual.js')
    expect(mod.msg0).toBe('virtual0')
    expect(mod.msg).toBe('virtual')
  })

  it('importing package from node_modules', async ({ runner }) => {
    const mod = (await runner.import(
      '/fixtures/installed.js',
    )) as typeof import('tinyspy')
    const fn = mod.spy()
    fn()
    expect(fn.called).toBe(true)
  })

  it('importing native node package', async ({ runner }) => {
    const mod = await runner.import('/fixtures/native.js')
    expect(mod.readdirSync).toBe(readdirSync)
    expect(mod.existsSync).toBe(existsSync)
  })

  it('correctly resolves module url', async ({ runner, server }) => {
    const { meta } = await runner.import('/fixtures/basic')
    const basicUrl = new _URL('./fixtures/basic.js', import.meta.url).toString()
    expect(meta.url).toBe(basicUrl)

    const filename = meta.filename!
    const dirname = meta.dirname!

    if (isWindows) {
      const cwd = process.cwd()
      const drive = `${cwd[0].toUpperCase()}:\\`
      const root = server.config.root.replace(/\\/g, '/')

      expect(filename.startsWith(drive)).toBe(true)
      expect(dirname.startsWith(drive)).toBe(true)

      expect(filename).toBe(win32.join(root, '.\\fixtures\\basic.js'))
      expect(dirname).toBe(win32.join(root, '.\\fixtures'))
    } else {
      const root = server.config.root

      expect(posix.join(root, './fixtures/basic.js')).toBe(filename)
      expect(posix.join(root, './fixtures')).toBe(dirname)
    }
  })

  it(`no maximum call stack error ModuleRunner.isCircularImport`, async ({
    runner,
  }) => {
    // entry.js ⇔ entry-cyclic.js
    //   ⇓
    // action.js
    const mod = await runner.import('/fixtures/cyclic/entry')
    await mod.setupCyclic()
    const action = await mod.importAction('/fixtures/cyclic/action')
    expect(action).toBeDefined()
  })

  it('this of the exported function should be undefined', async ({
    runner,
  }) => {
    const mod = await runner.import('/fixtures/no-this/importer.js')
    expect(mod.result).toBe(undefined)
  })

  it.for([
    '/fixtures/cyclic2/test1/index.js',
    '/fixtures/cyclic2/test2/index.js',
    '/fixtures/cyclic2/test3/index.js',
    '/fixtures/cyclic2/test4/index.js',
  ] as const)(`cyclic %s`, async (entry, { runner }) => {
    const mod = await runner.import(entry)
    expect({ ...mod }).toEqual({
      dep1: {
        ok: true,
      },
      dep2: {
        ok: true,
      },
    })
  })

  it(`cyclic invalid 1`, async ({ runner }) => {
    // Node also fails but with a different message
    //   $ node packages/vite/src/node/ssr/runtime/__tests__/fixtures/cyclic2/test5/index.js
    //   ReferenceError: Cannot access 'dep1' before initialization
    await expect(() =>
      runner.import('/fixtures/cyclic2/test5/index.js'),
    ).rejects.toMatchInlineSnapshot(
      `[TypeError: Cannot read properties of undefined (reading 'ok')]`,
    )
  })

  it(`cyclic invalid 2`, async ({ runner }) => {
    // It should be an error but currently `undefined` fallback.
    expect(
      await runner.import('/fixtures/cyclic2/test6/index.js'),
    ).toMatchInlineSnapshot(
      `
      {
        "dep1": "dep1: dep2: undefined",
      }
    `,
    )
  })

  it(`cyclic with mixed import and re-export`, async ({ runner }) => {
    const mod = await runner.import('/fixtures/cyclic2/test7/Ion.js')
    expect(mod).toMatchInlineSnapshot(`
      {
        "IonTypes": {
          "BLOB": "Blob",
        },
        "dom": {
          "Blob": "Blob",
        },
      }
    `)
  })

  it(`execution order with mixed import and re-export`, async ({
    runner,
    onTestFinished,
  }) => {
    const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
    onTestFinished(() => spy.mockRestore())

    await runner.import('/fixtures/execution-order-re-export/index.js')
    expect(spy.mock.calls.map((v) => v[0])).toMatchInlineSnapshot(`
      [
        "dep1",
        "dep2",
      ]
    `)
  })

  it(`live binding (export default function f)`, async ({ runner }) => {
    const mod = await runner.import('/fixtures/live-binding/test1/index.js')
    expect(mod.default).toMatchInlineSnapshot(`
      [
        2,
        3,
      ]
    `)
  })

  it(`live binding (export default f)`, async ({ runner }) => {
    const mod = await runner.import('/fixtures/live-binding/test2/index.js')
    expect(mod.default).toMatchInlineSnapshot(`
      [
        1,
        1,
      ]
    `)
  })

  it(`live binding (export { f as default })`, async ({ runner }) => {
    const mod = await runner.import('/fixtures/live-binding/test3/index.js')
    expect(mod.default).toMatchInlineSnapshot(`
      [
        2,
        3,
      ]
    `)
  })

  it(`live binding (export default class C)`, async ({ runner }) => {
    const mod = await runner.import('/fixtures/live-binding/test4/index.js')
    expect(mod.default).toMatchInlineSnapshot(`
      [
        2,
        3,
      ]
    `)
  })

  it(`export default getter is hoisted`, async ({ runner }) => {
    // Node error is `ReferenceError: Cannot access 'dep' before initialization`
    // It should be an error but currently `undefined` fallback.
    expect(
      await runner.import('/fixtures/cyclic2/test9/index.js'),
    ).toMatchInlineSnapshot(
      `
      {
        "default": undefined,
      }
    `,
    )
  })

  it('oxc runtime helpers are loadable', async ({ runner }) => {
    const mod = await runner.import('/fixtures/oxc-runtime-helper.ts')
    expect(mod.result).toMatchInlineSnapshot(`
      "<script>
        console.log('hi')
      </script>"
    `)
  })

  it(`handle Object variable`, async ({ runner }) => {
    const mod = await runner.import('/fixtures/top-level-object.js')
    expect(mod).toMatchInlineSnapshot(`
      {
        "Object": "my-object",
      }
    `)
  })
})

describe('optimize-deps', async () => {
  const it = await createModuleRunnerTester({
    cacheDir: 'node_modules/.vite-test',
    ssr: {
      noExternal: true,
      optimizeDeps: {
        include: ['@vitejs/cjs-external'],
      },
    },
  })

  it('optimized dep as entry', async ({ runner }) => {
    const mod = await runner.import('@vitejs/cjs-external')
    expect(mod.default.hello()).toMatchInlineSnapshot(`"world"`)
  })
})

describe('resolveId absolute path entry', async () => {
  const it = await createModuleRunnerTester({
    plugins: [
      {
        name: 'test-resolevId',
        enforce: 'pre',
        resolveId(source) {
          if (
            source ===
            posix.join(this.environment.config.root, 'fixtures/basic.js')
          ) {
            return '\0virtual:basic'
          }
        },
        load(id) {
          if (id === '\0virtual:basic') {
            return `export const name = "virtual:basic"`
          }
        },
      },
    ],
  })

  it('ssrLoadModule', async ({ server }) => {
    const mod = await server.ssrLoadModule(
      posix.join(server.config.root, 'fixtures/basic.js'),
    )
    expect(mod.name).toMatchInlineSnapshot(`"virtual:basic"`)
  })

  it('runner', async ({ server, runner }) => {
    const mod = await runner.import(
      posix.join(server.config.root, 'fixtures/basic.js'),
    )
    expect(mod.name).toMatchInlineSnapshot(`"virtual:basic"`)
  })
})

describe('virtual module hmr', async () => {
  let state = 'init'

  const it = await createModuleRunnerTester({
    plugins: [
      {
        name: 'test-resolevId',
        enforce: 'pre',
        resolveId(source) {
          if (source === 'virtual:test') {
            return '\0' + source
          }
        },
        load(id) {
          if (id === '\0virtual:test') {
            return `export default ${JSON.stringify(state)}`
          }
        },
      },
    ],
  })

  it('full reload', async ({ server, runner }) => {
    const mod = await runner.import('virtual:test')
    expect(mod.default).toBe('init')
    state = 'reloaded'
    server.environments.ssr.moduleGraph.invalidateAll()
    server.environments.ssr.hot.send({ type: 'full-reload' })
    await vi.waitFor(() => {
      const mod = runner.evaluatedModules.getModuleById('\0virtual:test')
      expect(mod?.exports.default).toBe('reloaded')
    })
  })

  it("the external module's ID and file are resolved correctly", async ({
    server,
    runner,
  }) => {
    await runner.import(
      posix.join(server.config.root, 'fixtures/import-external.ts'),
    )
    const moduleNode = runner.evaluatedModules.getModuleByUrl('tinyglobby')!
    const meta = moduleNode.meta as ExternalFetchResult
    if (process.platform === 'win32') {
      expect(meta.externalize).toMatch(/^file:\/\/\/\w:\//) // file:///C:/
      expect(moduleNode.id).toMatch(/^\w:\//) // C:/
      expect(moduleNode.file).toMatch(/^\w:\//) // C:/
    } else {
      expect(meta.externalize).toMatch(/^file:\/\/\//) // file:///
      expect(moduleNode.id).toMatch(/^\//) // /
      expect(moduleNode.file).toMatch(/^\//) // /
    }
  })
})

describe('invalid package', async () => {
  const it = await createModuleRunnerTester({
    environments: {
      ssr: {
        resolve: {
          noExternal: true,
        },
      },
    },
  })

  it('can catch resolve error on runtime', async ({ runner }) => {
    const mod = await runner.import('./fixtures/invalid-package/test.js')
    expect(await mod.test()).toMatchInlineSnapshot(`
      {
        "data": [Error: Failed to resolve entry for package "test-dep-invalid-exports". The package may have incorrect main/module/exports specified in its package.json.],
        "ok": false,
      }
    `)
  })
})

describe('full-reload during close', () => {
  it('does not error when server closes during full-reload re-import', async () => {
    const errors: (string | Error)[] = []
    const logger: HMRLogger = {
      error: (msg) => errors.push(msg),
      debug: () => {},
    }

    const server = await createServer({
      root: import.meta.dirname,
      logLevel: 'error',
      server: {
        middlewareMode: true,
        watch: null,
        ws: false,
      },
      optimizeDeps: {
        disabled: true,
        noDiscovery: true,
      },
      environments: {
        ssr: {
          dev: {
            createEnvironment(name, config) {
              return createRunnableDevEnvironment(name, config, {
                runnerOptions: { hmr: { logger } },
              })
            },
          },
        },
      },
      plugins: [
        {
          name: 'test-slow-virtual',
          enforce: 'pre',
          resolveId(source) {
            if (source === 'virtual:slow') return '\0virtual:slow'
          },
          async load(id) {
            if (id === '\0virtual:slow') {
              await setTimeout(10)
              return `export default "ok"`
            }
          },
        },
      ],
    })

    const env = server.environments.ssr
    if (!isRunnableDevEnvironment(env)) {
      throw new Error('expected RunnableDevEnvironment')
    }

    const mod = await env.runner.import('virtual:slow')
    expect(mod.default).toBe('ok')

    // re-import will run async via the HMR queue
    env.moduleGraph.invalidateAll()
    env.hot.send({ type: 'full-reload' })

    // server.close() -> environment.close() -> runner.close() ->
    // transport.disconnect() rejects the pending fetchModule RPC
    await server.close()
    await setTimeout(100) // Give the HMR handler time to settle

    expect(
      errors.some((e) => e.toString().includes('transport was disconnected')),
    ).toBe(false)
  })
})

describe('server.fs check', async () => {
  const it = await createModuleRunnerTester({
    server: {
      fs: {
        allow: [resolve(import.meta.dirname, './fixtures/circular')],
      },
    },
  })

  it('it is not applied to the server module runner', async ({ runner }) => {
    const mod = await runner.import('/fixtures/basic.js')
    expect(mod.name).toBe('basic')
  })
})


import type { ForwardConsolePayload } from '#types/customEvent'
import {
  type NormalizedModuleRunnerTransport,
  SendBeforeConnectError,
} from './moduleRunnerTransport'

export type ForwardConsoleLogLevel =
  | 'error'
  | 'warn'
  | 'info'
  | 'log'
  | 'debug'
  | (string & {})

export interface ForwardConsoleOptions {
  unhandledErrors?: boolean
  logLevels?: ForwardConsoleLogLevel[]
}

export interface ResolvedForwardConsoleOptions {
  enabled: boolean
  unhandledErrors: boolean
  logLevels: ForwardConsoleLogLevel[]
}

export function setupForwardConsoleHandler(
  transport: NormalizedModuleRunnerTransport,
  options: ResolvedForwardConsoleOptions,
  console: Console = globalThis.console,
): void {
  if (!options.enabled) {
    return
  }

  async function sendError(type: 'error' | 'unhandled-rejection', error: any) {
    await transport.send({
      type: 'custom',
      event: 'vite:forward-console',
      data: {
        type,
        data: {
          name: error?.name || 'Unknown Error',
          message: error?.message || String(error),
          stack: error?.stack,
        },
      } satisfies ForwardConsolePayload,
    })
  }

  async function sendLog(level: ForwardConsoleLogLevel, args: unknown[]) {
    try {
      await transport.send({
        type: 'custom',
        event: 'vite:forward-console',
        data: {
          type: 'log',
          data: {
            level,
            message: formatConsoleArgs(args),
          },
        } satisfies ForwardConsolePayload,
      })
    } catch (err) {
      try {
        await sendError('unhandled-rejection', err)
      } catch (err) {
        if (!(err instanceof SendBeforeConnectError)) {
          originalConsoleError('Failed to send error to Vite server:', err)
        }
      }
    }
  }

  const originalConsoleError = console.error

  for (const level of options.logLevels) {
    const original = (console as any)[level]
    if (typeof original !== 'function') {
      continue
    }
    ;(console as any)[level] = (...args: unknown[]) => {
      original(...args)
      sendLog(level, args)
    }
  }

  if (options.unhandledErrors && typeof window !== 'undefined') {
    window.addEventListener('error', async (event) => {
      // `ErrorEvent` doesn't necessarily have `ErrorEvent.error`.
      // Use `ErrorEvent.message` as fallback e.g. for ResizeObserver error.
      // https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent/error
      // https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver#observation_errors
      const error =
        event.error ?? (event.message ? new Error(event.message) : event)
      try {
        await sendError('error', error)
      } catch (err) {
        if (!(err instanceof SendBeforeConnectError)) {
          originalConsoleError('Failed to send error to Vite server:', err)
        }
      }
    })

    window.addEventListener('unhandledrejection', async (event) => {
      try {
        await sendError('unhandled-rejection', event.reason)
      } catch (err) {
        if (!(err instanceof SendBeforeConnectError)) {
          originalConsoleError('Failed to send error to Vite server:', err)
        }
      }
    })
  }
}

// Zero dep version of Vitest's console formatter
// https://github.com/vitest-dev/vitest/blob/a2d650e00dbd8220397c5c25aef05c850100e446/packages/utils/src/display.ts#L129
export function formatConsoleArgs(args: unknown[]): string {
  if (args.length === 0) {
    return ''
  }

  if (typeof args[0] !== 'string') {
    return args.map((arg) => stringifyConsoleArg(arg)).join(' ')
  }

  const len = args.length
  let i = 1
  let message = args[0].replace(/%[sdjifoOc%]/g, (specifier) => {
    if (specifier === '%%') {
      return '%'
    }
    if (i >= len) {
      return specifier
    }

    const arg = args[i++]
    switch (specifier) {
      case '%s':
        if (typeof arg === 'bigint') {
          return `${arg.toString()}n`
        }
        return typeof arg === 'object' && arg != null
          ? stringifyConsoleArg(arg)
          : String(arg)
      case '%d':
        if (typeof arg === 'bigint') {
          return `${arg.toString()}n`
        }
        if (typeof arg === 'symbol') {
          return 'NaN'
        }
        return Number(arg).toString()
      case '%i':
        if (typeof arg === 'bigint') {
          return `${arg.toString()}n`
        }
        return Number.parseInt(String(arg), 10).toString()
      case '%f':
        return Number.parseFloat(String(arg)).toString()
      case '%o':
      case '%O':
        return stringifyConsoleArg(arg)
      case '%j':
        try {
          const serialized = JSON.stringify(arg)
          return serialized ?? 'undefined'
        } catch {
          return '[Circular]'
        }
      case '%c':
        return ''
      default:
        return specifier
    }
  })

  for (let arg = args[i]; i < len; arg = args[++i]) {
    if (arg == null || typeof arg !== 'object') {
      message += ` ${typeof arg === 'symbol' ? arg.toString() : String(arg)}`
    } else {
      message += ` ${stringifyConsoleArg(arg)}`
    }
  }

  return message
}

function stringifyConsoleArg(value: unknown): string {
  if (typeof value === 'string') {
    return value
  }
  if (
    typeof value === 'number' ||
    typeof value === 'boolean' ||
    typeof value === 'undefined'
  ) {
    return String(value)
  }
  if (typeof value === 'symbol') {
    return value.toString()
  }
  if (typeof value === 'function') {
    return value.name ? `[Function: ${value.name}]` : '[Function]'
  }
  if (value instanceof Error) {
    return value.stack || `${value.name}: ${value.message}`
  }
  if (typeof value === 'bigint') {
    return `${value}n`
  }

  const seen = new WeakSet<object>()
  try {
    const serialized = JSON.stringify(value, (_, nested) => {
      if (typeof nested === 'bigint') {
        return `${nested}n`
      }
      if (nested instanceof Error) {
        return {
          name: nested.name,
          message: nested.message,
          stack: nested.stack,
        }
      }
      if (nested && typeof nested === 'object') {
        if (seen.has(nested)) {
          return '[Circular]'
        }
        seen.add(nested)
      }
      return nested
    })
    return serialized ?? String(value)
  } catch {
    return String(value)
  }
}


import path from 'node:path'
import { stripVTControlCharacters as strip } from 'node:util'
import colors from 'picocolors'
import type { RollupError } from 'rolldown'
import type { Connect } from '#dep-types/connect'
import type { ErrorPayload } from '#types/hmrPayload'
import { pad } from '../../utils'
import type { ViteDevServer } from '../..'
import { CLIENT_PUBLIC_PATH } from '../../constants'

export function prepareError(err: Error | RollupError): ErrorPayload['err'] {
  // only copy the information we need and avoid serializing unnecessary
  // properties, since some errors may attach full objects (e.g. PostCSS)
  return {
    message: strip(err.message),
    stack: strip(cleanStack(err.stack || '')),
    id: (err as RollupError).id,
    frame: strip((err as RollupError).frame || ''),
    plugin: (err as RollupError).plugin,
    pluginCode: (err as RollupError).pluginCode?.toString(),
    loc: (err as RollupError).loc,
  }
}

export function buildErrorMessage(
  err: RollupError,
  args: string[] = [],
  includeStack = true,
): string {
  if (err.plugin) args.push(`  Plugin: ${colors.magenta(err.plugin)}`)
  const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : ''
  if (err.id) args.push(`  File: ${colors.cyan(err.id)}${loc}`)
  if (err.frame) args.push(colors.yellow(pad(err.frame)))
  if (includeStack && err.stack) args.push(pad(cleanStack(err.stack)))
  return args.join('\n')
}

function cleanStack(stack: string) {
  return stack
    .split(/\n/)
    .filter((l) => /^\s*at/.test(l))
    .join('\n')
}

export function logError(server: ViteDevServer, err: RollupError): void {
  const msg = buildErrorMessage(err, [
    colors.red(`Internal server error: ${err.message}`),
  ])

  server.config.logger.error(msg, {
    clear: true,
    timestamp: true,
    error: err,
  })

  server.environments.client.hot.send({
    type: 'error',
    err: prepareError(err),
  })
}

export function errorMiddleware(
  server: ViteDevServer,
  allowNext = false,
): Connect.ErrorHandleFunction {
  // note the 4 args must be kept for connect to treat this as error middleware
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  return function viteErrorMiddleware(err: RollupError, _req, res, next) {
    logError(server, err)

    if (allowNext) {
      next()
    } else {
      res.statusCode = 500
      res.end(`
        <!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="UTF-8" />
            <title>Error</title>
            <script type="module">
              const error = ${JSON.stringify(prepareError(err)).replace(
                /</g,
                '\\u003c',
              )}
              try {
                const { ErrorOverlay } = await import(${JSON.stringify(path.posix.join(server.config.base, CLIENT_PUBLIC_PATH))})
                document.body.appendChild(new ErrorOverlay(error))
              } catch {
                const h = (tag, text) => {
                  const el = document.createElement(tag)
                  el.textContent = text
                  return el
                }
                document.body.appendChild(h('h1', 'Internal Server Error'))
                document.body.appendChild(h('h2', error.message))
                document.body.appendChild(h('pre', error.stack))
                document.body.appendChild(h('p', '(Error overlay failed to load)'))
              }
            </script>
          </head>
          <body>
          </body>
        </html>
      `)
    }
  }
}


import SelfWorker from './self-reference-worker?worker'

self.addEventListener('message', (e) => {
  if (e.data === 'main') {
    const selfWorker = new SelfWorker()
    selfWorker.postMessage('nested')
    selfWorker.addEventListener('message', (e) => {
      self.postMessage(e.data)
    })
  }

  self.postMessage(`pong: ${e.data}`)
})


import { expect, test } from 'vitest'
import { port } from './serve'
import { isBuild, page } from '~utils'

const url = `http://localhost:${port}/`

test.runIf(!isBuild)('optimize', async () => {
  await page.goto(url)
  // reload page to get optimized missing deps
  await page.reload()
  await expect.poll(() => page.textContent('div')).toMatch('Client')

  // raw http request
  const aboutHtml = await (await fetch(url)).text()
  expect(aboutHtml).toContain('Server')
})


import { msg as msgFromDep } from '@vitejs/test-dep-to-optimize'
import depCjs from '@vitejs/test-worker-dep-cjs'
import { mode, msg } from './modules/workerImport.js'
import { bundleWithPlugin } from './modules/test-plugin'
import viteSvg from './vite.svg'
const metaUrl = import.meta.url

self.onmessage = (e) => {
  if (e.data === 'ping') {
    self.postMessage({
      msg,
      mode,
      bundleWithPlugin,
      viteSvg,
      metaUrl,
      name,
      depCjs,
    })
  }
  if (e.data === 'ping-unicode') {
    self.postMessage({
      msg: '•pong•',
      mode,
      bundleWithPlugin,
      viteSvg,
      metaUrl,
      name,
      depCjs,
    })
  }
}
self.postMessage({
  msg,
  mode,
  bundleWithPlugin,
  msgFromDep,
  viteSvg,
  metaUrl,
  name,
  depCjs,
})

// for sourcemap
console.log('my-worker.js')


# <small>nlohmann::basic_json::</small>insert

```cpp
// (1)
iterator insert(const_iterator pos, const basic_json& val);
iterator insert(const_iterator pos, basic_json&& val);

// (2)
iterator insert(const_iterator pos, size_type cnt, const basic_json& val);

// (3)
iterator insert(const_iterator pos, const_iterator first, const_iterator last);

// (4)
iterator insert(const_iterator pos, initializer_list_t ilist);

// (5)
void insert(const_iterator first, const_iterator last);
```

1. Inserts element `val` into an array before iterator `pos`.
2. Inserts `cnt` copies of `val` into an array before iterator `pos`.
3. Inserts elements from range `[first, last)` into an array before iterator `pos`.
4. Inserts elements from initializer list `ilist` into an array before iterator `pos`.
5. Inserts elements from range `[first, last)` into an object.

## Iterator invalidation

For all cases where an element is added to an **array**, a reallocation can happen, in which case all iterators
(including the [`end()`](end.md) iterator) and all references to the elements are invalidated. Otherwise, only the
[`end()`](end.md) iterator is invalidated. Also, any iterator or reference after the insertion point will point to the
same index, which is now a different value.

For [`ordered_json`](../ordered_json.md), also adding an element to an **object** can yield a reallocation which again
invalidates all iterators and all references. Also, any iterator or reference after the insertion point will point to
the same index, which is now a different value.

## Parameters

`pos` (in)
:   iterator before which the content will be inserted; may be the `end()` iterator

`val` (in)
:   value to insert

`cnt` (in)
:   number of copies of `val` to insert

`first` (in)
:   the start of the range of elements to insert

`last` (in)
:   the end of the range of elements to insert

`ilist` (in)
:   initializer list to insert the values from

## Return value

1. iterator pointing to the inserted `val`.
2. iterator pointing to the first element inserted, or `pos` if `#!cpp cnt==0`
3. iterator pointing to the first element inserted, or `pos` if `#!cpp first==last`
4. iterator pointing to the first element inserted, or `pos` if `ilist` is empty
5. (none)

## Exception safety

Strong exception safety: if an exception occurs, the original value stays intact.

## Exceptions

1. The function can throw the following exceptions:
    - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
      arrays; example: `"cannot use insert() with string"`
    - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if called on an
      iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"`
2. The function can throw the following exceptions:
    - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
      arrays; example: `"cannot use insert() with string"`
    - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if called on an
      iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"`
3. The function can throw the following exceptions:
    - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
      arrays; example: `"cannot use insert() with string"`
    - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if called on an
      iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"`
    - Throws [`invalid_iterator.210`](../../home/exceptions.md#jsonexceptioninvalid_iterator210) if `first` and `last`
      do not belong to the same JSON value; example: `"iterators do not fit"`
    - Throws [`invalid_iterator.211`](../../home/exceptions.md#jsonexceptioninvalid_iterator211) if `first` or `last`
      are iterators into container for which insert is called; example: `"passed iterators may not belong to container"`
4. The function can throw the following exceptions:
    - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
      arrays; example: `"cannot use insert() with string"`
    - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if called on an
      iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"`
5. The function can throw the following exceptions:
    - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
      objects; example: `"cannot use insert() with string"`
    - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if `first` or `last`
      do not point to an object; example: `"iterators first and last must point to objects"`
    - Throws [`invalid_iterator.210`](../../home/exceptions.md#jsonexceptioninvalid_iterator210) if `first` and `last`
      do not belong to the same JSON value; example: `"iterators do not fit"`

## Complexity

1. Constant plus linear in the distance between `pos` and end of the container.
2. Linear in `cnt` plus linear in the distance between `pos` and end of the container.
3. Linear in `#!cpp std::distance(first, last)` plus linear in the distance between `pos` and end of the container.
4. Linear in `ilist.size()` plus linear in the distance between `pos` and end of the container.
5. Logarithmic: `O(N*log(size() + N))`, where `N` is the number of elements to insert.

## Examples

??? example "Example (1): insert element into array"

    The example shows how `insert()` is used.

    ```cpp
    --8<-- "examples/insert.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/insert.output"
    ```

??? example "Example (2): insert copies of element into array"

    The example shows how `insert()` is used.

    ```cpp
    --8<-- "examples/insert__count.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/insert__count.output"
    ```

??? example "Example (3): insert a range of elements into an array"

    The example shows how `insert()` is used.

    ```cpp
    --8<-- "examples/insert__range.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/insert__range.output"
    ```

??? example "Example (4): insert elements from an initializer list into an array"

    The example shows how `insert()` is used.

    ```cpp
    --8<-- "examples/insert__ilist.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/insert__ilist.output"
    ```

??? example "Example (5): insert a range of elements into an object"

    The example shows how `insert()` is used.

    ```cpp
    --8<-- "examples/insert__range_object.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/insert__range_object.output"
    ```

## See also

- [emplace](emplace.md) add a value to an object
- [emplace_back](emplace_back.md) add a value to an array
- [push_back](push_back.md) add a value to an array/object
- [update](update.md) merges objects

## Version history

1. Added in version 1.0.0.
2. Added in version 1.0.0.
3. Added in version 1.0.0.
4. Added in version 1.0.0.
5. Added in version 3.0.0.


//     __ _____ _____ _____
//  __|  |   __|     |   | |  JSON for Modern C++ (supporting code)
// |  |  |__   |  |  | | | |  version 3.12.0
// |_____|_____|_____|_|___|  https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

/*
This file implements a parser test suitable for fuzz testing. Given a byte
array data, it performs the following steps:

- j1 = from_bjdata(data)
- vec = to_bjdata(j1)
- j2 = from_bjdata(vec)
- assert(j1 == j2)
- vec2 = to_bjdata(j1, use_size = true, use_type = false)
- j3 = from_bjdata(vec2)
- assert(j1 == j3)
- vec3 = to_bjdata(j1, use_size = true, use_type = true)
- j4 = from_bjdata(vec3)
- assert(j1 == j4)

The provided function `LLVMFuzzerTestOneInput` can be used in different fuzzer
drivers.
*/

#include <iostream>
#include <sstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

// see http://llvm.org/docs/LibFuzzer.html
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
    try
    {
        // step 1: parse input
        std::vector<uint8_t> const vec1(data, data + size);
        json const j1 = json::from_bjdata(vec1);

        try
        {
            // step 2.1: round trip without adding size annotations to container types
            std::vector<uint8_t> const vec2 = json::to_bjdata(j1, false, false);

            // step 2.2: round trip with adding size annotations but without adding type annotations to container types
            std::vector<uint8_t> const vec3 = json::to_bjdata(j1, true, false);

            // step 2.3: round trip with adding size as well as type annotations to container types
            std::vector<uint8_t> const vec4 = json::to_bjdata(j1, true, true);

            // parse serialization
            json const j2 = json::from_bjdata(vec2);
            json const j3 = json::from_bjdata(vec3);
            json const j4 = json::from_bjdata(vec4);

            // serializations must match
            assert(json::to_bjdata(j2, false, false) == vec2);
            assert(json::to_bjdata(j3, true, false) == vec3);
            assert(json::to_bjdata(j4, true, true) == vec4);
        }
        catch (const json::parse_error&)
        {
            // parsing a BJData serialization must not fail
            assert(false);
        }
    }
    catch (const json::parse_error&)
    {
        // parse errors are ok, because input may be random bytes
    }
    catch (const json::type_error&)
    {
        // type errors can occur during parsing, too
    }
    catch (const json::out_of_range&)
    {
        // out of range errors may happen if provided sizes are excessive
    }

    // return 0 - non-zero return values are reserved for future use
    return 0;
}