diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 00000000..4750d5f9 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Ad Frontend Design & Development - Agency + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/content/CONTENT.md b/content/CONTENT.md new file mode 100644 index 00000000..aa406040 --- /dev/null +++ b/content/CONTENT.md @@ -0,0 +1 @@ +In deze folder kunnen teksten en visuals voor de web app geplaatst worden diff --git a/design/community-drops.png b/design/community-drops.png new file mode 100644 index 00000000..ec29d400 Binary files /dev/null and b/design/community-drops.png differ diff --git a/design/emotioneel-verder-gaan.png b/design/emotioneel-verder-gaan.png new file mode 100644 index 00000000..4d000d42 Binary files /dev/null and b/design/emotioneel-verder-gaan.png differ diff --git a/design/verder-in-verandering.png b/design/verder-in-verandering.png new file mode 100644 index 00000000..271cab1a Binary files /dev/null and b/design/verder-in-verandering.png differ diff --git a/docs/INSTRUCTIONS.md b/docs/INSTRUCTIONS.md deleted file mode 100644 index f4119bed..00000000 --- a/docs/INSTRUCTIONS.md +++ /dev/null @@ -1,78 +0,0 @@ -# Don't Repeat Yourself - Component Library -Ontwikkel een website voor een opdrachtgever op basis van een component library. - -## Context -Deze leertaak hoort bij sprint 16 Don't Repeat Yourself. Dit is een opdracht die je deels individueel en deels als team uitvoert voor een opdrachtgever. - -Bij deze leertaak hoort de deeltaak: - -* [Component Building Block](https://github.com/fdnd-task/dont-repeat-yourself-component-building-block) - -## Doel van deze opdracht -Je leert hoe je herbruikbare stukken code op een systematische manier ontsluit zodat jij en jouw mede frontenders ze kunnen gebruiken in andere projecten. - -## Werkwijze -Bij elke leertaak wordt de development-lifecycle doorlopen. Hierdoor ontwikkel je een standaard aanpak voor frontend praktijkvraagstukken, werk je systematisch aan leertaken, ervaar je de relevantie van het geleerde en verwerf je de kennis, houding en vaardigheden die de beroepspraktijk van je vraagt. De development lifecycle bestaat uit de stappen: Analyseren, Ontwerpen, Bouwen, Integreren en Testen. - -De component library (letterlijk: een bibliotheek met componenten) die je gaat maken bestaat uit een serie herbruikbare bouwblokken voor een opdrachtgever in een apart project. Het voordeel van het gebruiken van een component library is dat alle projecten die voor deze opdrachtgever gemaakt worden terug kunnen verwijzen naar dezelfde component library. - -Door op deze manier te werken wordt de *developer experience* (hierna DX) beter omdat: -1. Uniformiteit wordt afgedwongen -2. Een design strategie wordt omarmd -3. Herhaling niet meer hoeft (DRY!) -4. Bugs oplossen eenvoudiger wordt -5. Samenwerken makkelijker wordt - -Het omarmen van deze ontwikkelstrategie vereist wel enig schakelen in de manier waarop je over code denkt. Het wordt abstracter omdat er meer afhankelijkheden en abstracties in je code gaan plaatsvinden. Je gaat bijvoorbeeld denken in termen van NPM packages in plaats van in componenten in één repository. Waarschijnlijk heb je ergens tijdens de vorige sprints de kracht van componenten in een lokaal project al ontdekt, nu is het tijd om externe componenten in te laden! - -### Aanpak - -In deze leertaak vind je slechts een partiële instructie, namelijk voor het [opzetten van de structuur](#structuur-opzetten-team) die nodig is om een component library als project in NPM te krijgen. Als dit gelukt is begint eigenlijk de leertaak pas. Je gaat je component library inzetten bij de [doorontwikkeling van projecten](#doorontwikkeling-individueel) (lees user-stories) voor jouw opdrachtgever. - -#### Structuur opzetten (team) - -Het opzetten van de structuur voor een component library is een beetje een gedoe maar het loont als je dit eenmaal gedaan hebt. - -1. Fork deze leertaak, in deze leertaak ga je de implementatie van de component library maken. Met andere woorden, je linkt in deze repository een andere repository welke de component library bevat. -2. Maak een nieuwe repository aan op jouw GitHub omgeving, geef deze een logische naam, bijvoorbeeld: fdnd-components, bij de volgende stappen staat *CLib* als het om deze ‘andere’ repository gaat. -3. *CLib* Initialiseer een nieuw SvelteKit library project! -4. *CLib* Check package.json voor de benodigde scripts. Als alles gelukt is zie je het commando `package` bij het lijstje staan. -5. *CLib* Maak om te testen een nieuw eenvoudig component aan in de /src/lib map, bijvoorbeeld `HelloWorld.svelte` -6. *CLib* Roep het commando `npm run package` aan om in de repository een package klaar te zetten. -7. *CLib* Bekijk de nieuw gegenereerde map `/package` -8. *CLib* Pas in de gegenereerde `package.json` de belangrijke velden aan, zoals `name`, `version`, `description`, enzovoorts. -9. *CLib* Publiceer gegenereerde package (dus niet het hele project!) als *scoped public package* via npm (zie bronnen). Het kan goed zijn dat je eerst een gebruiker en een organisatie moet aanmaken. -10. Check npmjs.com en zoek jouw organisatie/package (supertof!) -11. Initialiseer een SvelteKit skeletten project. -11. Link jouw package als dependancy door `npm install organisatie/package` uit te voeren. -12. Importeer jouw component door `import { HelloWorld } from 'organisatie/package`, zet het ergens neer met `` en test of het werkt. -13. Ga verder bij [Doorontwikkeling](#doorontwikkeling-individueel) - -##### Bronnen: -- [Don’t Repeat Yourself](http://wiki.c2.com/?DontRepeatYourself) -- [SvelteKit](https://kit.svelte.dev/) voor het opstartscript -- [svelte-package](https://kit.svelte.dev/docs/packaging) voor het verpakken van de componenten uit `/src/lib` in een nieuwe package. N.B.: Je krijgt een melding dat de package `svelte2tsx` geïnstalleerd moet worden, dat kan je doen met `npm install -D svelte2tsx` -- [How to Create Svelte Component Libraries with SvelteKit (iets verouderd!)](https://medium.com/mkdir-awesome/how-to-create-svelte-component-libraries-with-sveltekit-98fd2ff12f0f) -- [npm Docs](https://docs.npmjs.com/) -- [Creating and publishing scoped public packages](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages) -- [How to Publish Your First npm Package](https://bretcameron.medium.com/how-to-publish-your-first-npm-package-b224296fc57b) -- [How to publish packages to npm (the way the industry does things)](https://zellwk.com/blog/publish-to-npm/) - -#### Doorontwikkeling (individueel) - -Als de structuur staat kan je verder gaan aan de ontwikkeling voor jouw opdrachtgever. Eventueel kan je wat tijd besteden aan het overhevelen van herhaalde stukken code uit je oude projecten maar dat hoeft niet per se, je kunt ook opnieuw beginnen. - -1. Kies een user story uit de backlog van het project waar je aan gaat werken. De projecten staan bij [FDND Agency](https://github.com/fdnd-agency). -2. Kopieer/plak de user story waar jij aan gaat werken naar de Wiki van de geforkte repository, dit ga je ontwerpen en maken -3. Documenteer je proces a.h.v de development life cycle -4. En schrijf een goede readme -5. Ga terug naar 1 tot de sprint voorbij is. - -## Criteria - -Deze opdracht is done als: - -- [ ] je een component library hebt gemaakt. -- [ ] je hebt gewerkt volgens de verschillende fases van de development-lifecycle -- [ ] je hebt je werk gedocumenteerd in de Readme en Wiki (user story, ontwerpbeslissingen, schetsen en code voorbeelden) -- [ ] de website op Github staat en een live url heeft diff --git a/docs/opdrachtomschrijving.png b/docs/opdrachtomschrijving.png deleted file mode 100644 index 205f79ad..00000000 Binary files a/docs/opdrachtomschrijving.png and /dev/null differ diff --git a/my-app/.gitignore b/my-app/.gitignore new file mode 100644 index 00000000..446dbdc4 --- /dev/null +++ b/my-app/.gitignore @@ -0,0 +1,22 @@ +node_modules +package-lock.json + +# Output +.output +.vercel +/.svelte-kit +/build + +# OS +.DS_Store +Thumbs.db + +# Env +.env +.env.* +!.env.example +!.env.test + +# Vite +vite.config.js.timestamp-* +vite.config.ts.timestamp-* diff --git a/my-app/.npmrc b/my-app/.npmrc new file mode 100644 index 00000000..b6f27f13 --- /dev/null +++ b/my-app/.npmrc @@ -0,0 +1 @@ +engine-strict=true diff --git a/my-app/README.md b/my-app/README.md new file mode 100644 index 00000000..5ce67661 --- /dev/null +++ b/my-app/README.md @@ -0,0 +1,38 @@ +# create-svelte + +Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte). + +## Creating a project + +If you're seeing this, you've probably already done this step. Congrats! + +```bash +# create a new project in the current directory +npm create svelte@latest + +# create a new project in my-app +npm create svelte@latest my-app +``` + +## Developing + +Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server: + +```bash +npm run dev + +# or start the server and open the app in a new browser tab +npm run dev -- --open +``` + +## Building + +To create a production version of your app: + +```bash +npm run build +``` + +You can preview the production build with `npm run preview`. + +> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment. diff --git a/my-app/package.json b/my-app/package.json new file mode 100644 index 00000000..ed2d84be --- /dev/null +++ b/my-app/package.json @@ -0,0 +1,25 @@ +{ + "name": "my-app", + "version": "0.0.1", + "private": true, + "scripts": { + "dev": "vite dev", + "build": "vite build", + "preview": "vite preview" + }, + "devDependencies": { + "@sveltejs/adapter-auto": "^3.0.0", + "@sveltejs/kit": "^2.0.0", + "@sveltejs/vite-plugin-svelte": "^3.0.0", + "svelte": "^5.2.2", + "vite": "^5.0.3" + }, + "type": "module", + "dependencies": { + "agora-rtm-sdk": "^2.2.0", + "express": "^4.21.1", + "socket.io": "^4.8.1", + "socket.io-client": "^4.8.1", + "uuid": "^11.0.3" + } +} diff --git a/my-app/src/app.html b/my-app/src/app.html new file mode 100644 index 00000000..cda88b0a --- /dev/null +++ b/my-app/src/app.html @@ -0,0 +1,14 @@ + + + + + + + Drop & Heal + %sveltekit.head% + + + +
%sveltekit.body%
+ + diff --git a/my-app/src/lib/arrow-l.svelte b/my-app/src/lib/arrow-l.svelte new file mode 100644 index 00000000..4d9b1ec7 --- /dev/null +++ b/my-app/src/lib/arrow-l.svelte @@ -0,0 +1,12 @@ + + + previous page + + + + + \ No newline at end of file diff --git a/my-app/src/lib/arrow-r.svelte b/my-app/src/lib/arrow-r.svelte new file mode 100644 index 00000000..86f350bf --- /dev/null +++ b/my-app/src/lib/arrow-r.svelte @@ -0,0 +1,11 @@ + + next page + + + + + \ No newline at end of file diff --git a/my-app/src/lib/blurgrad-blue.svelte b/my-app/src/lib/blurgrad-blue.svelte new file mode 100644 index 00000000..c4517ffe --- /dev/null +++ b/my-app/src/lib/blurgrad-blue.svelte @@ -0,0 +1,26 @@ + + + + \ No newline at end of file diff --git a/my-app/src/lib/blurgrad-green.svelte b/my-app/src/lib/blurgrad-green.svelte new file mode 100644 index 00000000..70fd5883 --- /dev/null +++ b/my-app/src/lib/blurgrad-green.svelte @@ -0,0 +1,25 @@ + + + + \ No newline at end of file diff --git a/my-app/src/lib/blurgrad-pink.svelte b/my-app/src/lib/blurgrad-pink.svelte new file mode 100644 index 00000000..b7c500ae --- /dev/null +++ b/my-app/src/lib/blurgrad-pink.svelte @@ -0,0 +1,26 @@ + + + + \ No newline at end of file diff --git a/my-app/src/lib/blurgrad-red.svelte b/my-app/src/lib/blurgrad-red.svelte new file mode 100644 index 00000000..9ac0187f --- /dev/null +++ b/my-app/src/lib/blurgrad-red.svelte @@ -0,0 +1,25 @@ + + + + \ No newline at end of file diff --git a/my-app/src/lib/chatbot.svelte b/my-app/src/lib/chatbot.svelte new file mode 100644 index 00000000..44f32317 --- /dev/null +++ b/my-app/src/lib/chatbot.svelte @@ -0,0 +1,228 @@ + + +
+
+

Community drops

+

Deel wat je van de oefening vond, lees ervaringen van anderen en steun elkaar in de reis door rouw. Je bent niet alleen.

+ + + +
+
+ + +
+ +
    + {#each messages as message} +
  • {message}
  • + {/each} +
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/my-app/src/lib/fetch-json.js b/my-app/src/lib/fetch-json.js new file mode 100644 index 00000000..962062b3 --- /dev/null +++ b/my-app/src/lib/fetch-json.js @@ -0,0 +1,20 @@ +/** + * An asynchronous helper function that wraps the standard node.js fetch API. + * This function calls an API url passed as the first and mandatory parameter, + * there is an optional payload parameter to send a json object, eg. a filter. + * It then calls the API and returns the response body parsed as a json object. + * @example fetchJson as returning function using the await keyword + * const data = await fetchJson('https://api-url.com/endpoint/') + * @example fetchJson as oneliner using the then() structure. + * fetchJson('https://api-url.com/endpoint/').then((data)=>{ + * // use data... + * }) + * @param {string} url the api endpoint to address + * @param {object} [payload] the payload to send to the API + * @returns the response from the API endpoint parsed as a json object + */ +export default async function fetchJson(url, payload = {}) { + return await fetch(url, payload) + .then((response) => response.json()) + .catch((error) => error) +} \ No newline at end of file diff --git a/my-app/src/lib/index.js b/my-app/src/lib/index.js new file mode 100644 index 00000000..08e757e2 --- /dev/null +++ b/my-app/src/lib/index.js @@ -0,0 +1,12 @@ +// place files you want to import through the `$lib` alias in this folder. + +export { default as MeshgradBlue } from './meshgrad-blue.svelte' +export { default as MeshgradRed } from './meshgrad-red.svelte' +export { default as MeshgradGreen } from './meshgrad-green.svelte' +export { default as MeshgradPink } from './meshgrad-pink.svelte' +export { default as BlurgradBlue } from './blurgrad-blue.svelte' +export { default as BlurgradRed } from './blurgrad-red.svelte' +export { default as BlurgradGreen } from './blurgrad-green.svelte' +export { default as BlurgradPink } from './blurgrad-pink.svelte' +export { default as ArrowL } from './arrow-l.svelte' +export { default as ArrowR } from './arrow-r.svelte' \ No newline at end of file diff --git a/my-app/src/lib/meshgrad-blue-static.svelte b/my-app/src/lib/meshgrad-blue-static.svelte new file mode 100644 index 00000000..e851dcc1 --- /dev/null +++ b/my-app/src/lib/meshgrad-blue-static.svelte @@ -0,0 +1,17 @@ + + + \ No newline at end of file diff --git a/my-app/src/lib/meshgrad-blue.svelte b/my-app/src/lib/meshgrad-blue.svelte new file mode 100644 index 00000000..1d0d846d --- /dev/null +++ b/my-app/src/lib/meshgrad-blue.svelte @@ -0,0 +1,27 @@ + + + \ No newline at end of file diff --git a/my-app/src/lib/meshgrad-green.svelte b/my-app/src/lib/meshgrad-green.svelte new file mode 100644 index 00000000..19b03cd9 --- /dev/null +++ b/my-app/src/lib/meshgrad-green.svelte @@ -0,0 +1,27 @@ + + + \ No newline at end of file diff --git a/my-app/src/lib/meshgrad-pink.svelte b/my-app/src/lib/meshgrad-pink.svelte new file mode 100644 index 00000000..8f9dd269 --- /dev/null +++ b/my-app/src/lib/meshgrad-pink.svelte @@ -0,0 +1,27 @@ + + + \ No newline at end of file diff --git a/my-app/src/lib/meshgrad-red.svelte b/my-app/src/lib/meshgrad-red.svelte new file mode 100644 index 00000000..fa15732a --- /dev/null +++ b/my-app/src/lib/meshgrad-red.svelte @@ -0,0 +1,28 @@ + + + \ No newline at end of file diff --git a/my-app/src/lib/messagesStore.js b/my-app/src/lib/messagesStore.js new file mode 100644 index 00000000..817cb68e --- /dev/null +++ b/my-app/src/lib/messagesStore.js @@ -0,0 +1,17 @@ +// src/lib/messagesStore.js +import { writable } from 'svelte/store'; + +// Controleer of we in de browser draaien +const isBrowser = typeof window !== 'undefined'; + +// Haal de berichten op uit localStorage als we in de browser zijn +export const messages = writable( + isBrowser ? JSON.parse(localStorage.getItem('messages')) || [] : [] +); + +// Subscribe naar de store en sla berichten op in localStorage +if (isBrowser) { + messages.subscribe($messages => { + localStorage.setItem('messages', JSON.stringify($messages)); + }); +} \ No newline at end of file diff --git a/my-app/src/routes/+page.js b/my-app/src/routes/+page.js new file mode 100644 index 00000000..cba219d1 --- /dev/null +++ b/my-app/src/routes/+page.js @@ -0,0 +1 @@ +export let csr = true \ No newline at end of file diff --git a/my-app/src/routes/+page.svelte b/my-app/src/routes/+page.svelte new file mode 100644 index 00000000..344c5efd --- /dev/null +++ b/my-app/src/routes/+page.svelte @@ -0,0 +1,104 @@ + + + +
+ +
+

Drop
& Heal

+

+ Welkom bij Drop & Heal. Een veilige plek voor jouw reis door rouwverwerking.

+ Er volgt eerst een introductie en kennismaking, hierna kan je op eigen tempo aan de slag in de omgeving. +

+
+ +
+ + \ No newline at end of file diff --git a/my-app/src/routes/api/messages.js b/my-app/src/routes/api/messages.js new file mode 100644 index 00000000..cad3dcc0 --- /dev/null +++ b/my-app/src/routes/api/messages.js @@ -0,0 +1,20 @@ +export async function post(request) { + const { message } = Object.fromEntries(await request.formData()); + + if (!message) { + return { + status: 400, + body: { error: 'Bericht kan niet leeg zijn' } + }; + } + + + + // Simuleer opslaan van het bericht (in een database of lokaal bestand) + console.log('Nieuw bericht ontvangen:', message); + + return { + status: 200, + body: { message: 'Bericht succesvol ontvangen!' } + }; +} \ No newline at end of file diff --git a/my-app/src/routes/chatbot/+page.server.js b/my-app/src/routes/chatbot/+page.server.js new file mode 100644 index 00000000..dbdf0a12 --- /dev/null +++ b/my-app/src/routes/chatbot/+page.server.js @@ -0,0 +1,20 @@ +import { messages } from '$lib/messagesStore.js'; + +/** @type {import('./$types').Actions} */ +export const actions = { + default: async (event) => { + const formData = await event.request.formData(); + const newMessage = formData.get('message'); + + // Update the messages store + messages.update(currentMessages => { + return [...currentMessages, newMessage]; + }); + + return { + success: true + }; + + } +}; + diff --git a/my-app/src/routes/chatbot/+page.svelte b/my-app/src/routes/chatbot/+page.svelte new file mode 100644 index 00000000..13b49a23 --- /dev/null +++ b/my-app/src/routes/chatbot/+page.svelte @@ -0,0 +1,14 @@ + + +
+
+ + + + + +
+ diff --git a/my-app/src/routes/introduction-h-1/+page.server.js b/my-app/src/routes/introduction-h-1/+page.server.js new file mode 100644 index 00000000..3ddca251 --- /dev/null +++ b/my-app/src/routes/introduction-h-1/+page.server.js @@ -0,0 +1,18 @@ +import fetchJson from "$lib/fetch-json"; + +export async function load() { + const url = 'https://fdnd-agency.directus.app/items/dropandheal_task'; + + const response = await fetchJson(url); + console.log('API Response:', response); + + const task = response.data.map(task => ({ + ...task, + description: task.description.replace(/<\/?[^>]+(>|$)/g, "") + // Verwijderd HTML tags die meegegeven zijn vanuit directus + })); + + return { + task: task || [] + }; +} \ No newline at end of file diff --git a/my-app/src/routes/introduction-h-1/+page.svelte b/my-app/src/routes/introduction-h-1/+page.svelte new file mode 100644 index 00000000..02b78389 --- /dev/null +++ b/my-app/src/routes/introduction-h-1/+page.svelte @@ -0,0 +1,174 @@ + + +
+ +
+ +
+
+

{title}

+ skip + +
+ + +
+
+
+

{sub}

+

{des}

+
+ + +
+
+
+
+ + \ No newline at end of file diff --git a/my-app/src/routes/introduction-h-2/+page.server.js b/my-app/src/routes/introduction-h-2/+page.server.js new file mode 100644 index 00000000..3ddca251 --- /dev/null +++ b/my-app/src/routes/introduction-h-2/+page.server.js @@ -0,0 +1,18 @@ +import fetchJson from "$lib/fetch-json"; + +export async function load() { + const url = 'https://fdnd-agency.directus.app/items/dropandheal_task'; + + const response = await fetchJson(url); + console.log('API Response:', response); + + const task = response.data.map(task => ({ + ...task, + description: task.description.replace(/<\/?[^>]+(>|$)/g, "") + // Verwijderd HTML tags die meegegeven zijn vanuit directus + })); + + return { + task: task || [] + }; +} \ No newline at end of file diff --git a/my-app/src/routes/introduction-h-2/+page.svelte b/my-app/src/routes/introduction-h-2/+page.svelte new file mode 100644 index 00000000..bcd6dd29 --- /dev/null +++ b/my-app/src/routes/introduction-h-2/+page.svelte @@ -0,0 +1,173 @@ + + +
+ +
+ +
+
+

{title}

+ skip + +
+ + +
+
+
+

{sub}

+

{des}

+
+ + +
+
+
+
+ + \ No newline at end of file diff --git a/my-app/src/routes/introduction-h-3/+page.server.js b/my-app/src/routes/introduction-h-3/+page.server.js new file mode 100644 index 00000000..3ddca251 --- /dev/null +++ b/my-app/src/routes/introduction-h-3/+page.server.js @@ -0,0 +1,18 @@ +import fetchJson from "$lib/fetch-json"; + +export async function load() { + const url = 'https://fdnd-agency.directus.app/items/dropandheal_task'; + + const response = await fetchJson(url); + console.log('API Response:', response); + + const task = response.data.map(task => ({ + ...task, + description: task.description.replace(/<\/?[^>]+(>|$)/g, "") + // Verwijderd HTML tags die meegegeven zijn vanuit directus + })); + + return { + task: task || [] + }; +} \ No newline at end of file diff --git a/my-app/src/routes/introduction-h-3/+page.svelte b/my-app/src/routes/introduction-h-3/+page.svelte new file mode 100644 index 00000000..694f9339 --- /dev/null +++ b/my-app/src/routes/introduction-h-3/+page.svelte @@ -0,0 +1,178 @@ + + +
+ +
+ +
+
+

{title}

+ skip + +
+ + +
+
+ +
+
+ + \ No newline at end of file diff --git a/my-app/src/routes/introduction-task-1/+page.server.js b/my-app/src/routes/introduction-task-1/+page.server.js new file mode 100644 index 00000000..3ddca251 --- /dev/null +++ b/my-app/src/routes/introduction-task-1/+page.server.js @@ -0,0 +1,18 @@ +import fetchJson from "$lib/fetch-json"; + +export async function load() { + const url = 'https://fdnd-agency.directus.app/items/dropandheal_task'; + + const response = await fetchJson(url); + console.log('API Response:', response); + + const task = response.data.map(task => ({ + ...task, + description: task.description.replace(/<\/?[^>]+(>|$)/g, "") + // Verwijderd HTML tags die meegegeven zijn vanuit directus + })); + + return { + task: task || [] + }; +} \ No newline at end of file diff --git a/my-app/src/routes/introduction-task-1/+page.svelte b/my-app/src/routes/introduction-task-1/+page.svelte new file mode 100644 index 00000000..765311e5 --- /dev/null +++ b/my-app/src/routes/introduction-task-1/+page.svelte @@ -0,0 +1,212 @@ + + +
+ +
+ +
+
+

Introductie rouwtaken

+ skip +
+ + +
+
+

{rt}

+

{sub1}

+

{d1}

+ +
+ +
+
+ + + +
+ +
+
+ + \ No newline at end of file diff --git a/my-app/src/routes/introduction-task-2/+page.server.js b/my-app/src/routes/introduction-task-2/+page.server.js new file mode 100644 index 00000000..3ddca251 --- /dev/null +++ b/my-app/src/routes/introduction-task-2/+page.server.js @@ -0,0 +1,18 @@ +import fetchJson from "$lib/fetch-json"; + +export async function load() { + const url = 'https://fdnd-agency.directus.app/items/dropandheal_task'; + + const response = await fetchJson(url); + console.log('API Response:', response); + + const task = response.data.map(task => ({ + ...task, + description: task.description.replace(/<\/?[^>]+(>|$)/g, "") + // Verwijderd HTML tags die meegegeven zijn vanuit directus + })); + + return { + task: task || [] + }; +} \ No newline at end of file diff --git a/my-app/src/routes/introduction-task-2/+page.svelte b/my-app/src/routes/introduction-task-2/+page.svelte new file mode 100644 index 00000000..8628c3cc --- /dev/null +++ b/my-app/src/routes/introduction-task-2/+page.svelte @@ -0,0 +1,187 @@ + + +
+ +
+ +
+

Introductie rouwtaken

+ +
+
+

{rt}2

+

{sub2}

+

{d2}

+
+ + +
+
+ + + +
+ +
+
+ + \ No newline at end of file diff --git a/my-app/src/routes/introduction-task-3/+page.server.js b/my-app/src/routes/introduction-task-3/+page.server.js new file mode 100644 index 00000000..3ddca251 --- /dev/null +++ b/my-app/src/routes/introduction-task-3/+page.server.js @@ -0,0 +1,18 @@ +import fetchJson from "$lib/fetch-json"; + +export async function load() { + const url = 'https://fdnd-agency.directus.app/items/dropandheal_task'; + + const response = await fetchJson(url); + console.log('API Response:', response); + + const task = response.data.map(task => ({ + ...task, + description: task.description.replace(/<\/?[^>]+(>|$)/g, "") + // Verwijderd HTML tags die meegegeven zijn vanuit directus + })); + + return { + task: task || [] + }; +} \ No newline at end of file diff --git a/my-app/src/routes/introduction-task-3/+page.svelte b/my-app/src/routes/introduction-task-3/+page.svelte new file mode 100644 index 00000000..4ee20697 --- /dev/null +++ b/my-app/src/routes/introduction-task-3/+page.svelte @@ -0,0 +1,187 @@ + + +
+ +
+ +
+

Introductie rouwtaken

+ +
+
+

{rt}3

+

{sub3}

+

{d3}

+
+ + +
+
+ + + +
+ +
+
+ + \ No newline at end of file diff --git a/my-app/src/routes/introduction-task-4/+page.server.js b/my-app/src/routes/introduction-task-4/+page.server.js new file mode 100644 index 00000000..3ddca251 --- /dev/null +++ b/my-app/src/routes/introduction-task-4/+page.server.js @@ -0,0 +1,18 @@ +import fetchJson from "$lib/fetch-json"; + +export async function load() { + const url = 'https://fdnd-agency.directus.app/items/dropandheal_task'; + + const response = await fetchJson(url); + console.log('API Response:', response); + + const task = response.data.map(task => ({ + ...task, + description: task.description.replace(/<\/?[^>]+(>|$)/g, "") + // Verwijderd HTML tags die meegegeven zijn vanuit directus + })); + + return { + task: task || [] + }; +} \ No newline at end of file diff --git a/my-app/src/routes/introduction-task-4/+page.svelte b/my-app/src/routes/introduction-task-4/+page.svelte new file mode 100644 index 00000000..c5436bee --- /dev/null +++ b/my-app/src/routes/introduction-task-4/+page.svelte @@ -0,0 +1,189 @@ + + +
+ +
+ +
+

Introductie rouwtaken

+ +
+
+

{rt}4

+

{sub4}

+

{d4}

+
+ + +
+
+ + + +
+ +
+
+ + \ No newline at end of file diff --git a/my-app/src/routes/navigation.svelte b/my-app/src/routes/navigation.svelte new file mode 100644 index 00000000..f547983f --- /dev/null +++ b/my-app/src/routes/navigation.svelte @@ -0,0 +1,16 @@ + diff --git a/my-app/src/routes/privacy/+page.svelte b/my-app/src/routes/privacy/+page.svelte new file mode 100644 index 00000000..3ab17e6e --- /dev/null +++ b/my-app/src/routes/privacy/+page.svelte @@ -0,0 +1,130 @@ + + +
+
+
+

Introductie
algemeen

+
+
+

Privacy

+

Jouw privacy en comfort zijn onze prioriteit. Alles wat je deelt blijft vertrouwelijk.

+
+
+ + + + +
+ + + diff --git a/my-app/src/routes/rouwtaken/+page.svelte b/my-app/src/routes/rouwtaken/+page.svelte new file mode 100644 index 00000000..623407f4 --- /dev/null +++ b/my-app/src/routes/rouwtaken/+page.svelte @@ -0,0 +1,133 @@ + + +
+
+
+

Introductie
algemeen

+
+
+

Rouwtaken

+

+ Onze methode is gebaseerd op de erkende rouwtaken van William Worden, Amerikaans rouwexpert, + zorgvuldig samengesteld om jou te ondersteunen tijdens je rouwreis.

+ Ontdek met ons de betekenis en steun die het jou kan bieden. +

+
+
+ + + + +
+ + + diff --git a/my-app/src/routes/tools/+page.svelte b/my-app/src/routes/tools/+page.svelte new file mode 100644 index 00000000..2cb7c28b --- /dev/null +++ b/my-app/src/routes/tools/+page.svelte @@ -0,0 +1,132 @@ + + +
+
+
+

Introductie
algemeen

+
+
+

Tools

+

+ We hebben tools samengesteld om je te ondersteunen in je reis door rouw. + Straks geven we een rondleiding binnen de omgeving. + Laten we nu eerst samen het landschap van rouw verkennen. +

+
+
+ + + + +
+ + \ No newline at end of file diff --git a/my-app/src/routes/uitleg-metafoor/+page.svelte b/my-app/src/routes/uitleg-metafoor/+page.svelte new file mode 100644 index 00000000..ceb9b4fc --- /dev/null +++ b/my-app/src/routes/uitleg-metafoor/+page.svelte @@ -0,0 +1,112 @@ + + +
+
+ +
+
+

+ Drop & Heal is een metafoor voor het loslaten van de zware last van verdriet en het starten van een helend proces. + Als een druppel in het water valt, wordt het onderdeel van een groter, krachtiger geheel, dit gebeurt ook wanneer we ons verdriet delen.

+ 'Drop' verwijst naar het moment waarop je je verdriet of emoties deelt, laat vallen, of erkent.

+ 'Heal' staat voor het genezingsproces dat volgt, waarbij je op je eigen tempo de stappen zet naar herstel en acceptatie. + Het is een uitnodiging om je verdriet te erkennen, het los te laten en jezelf toe te staan te helen, stap voor stap, druppel voor druppel. +

+
+ + + +
+ + + + + diff --git a/my-app/static/css/global.css b/my-app/static/css/global.css new file mode 100644 index 00000000..eb6e75bd --- /dev/null +++ b/my-app/static/css/global.css @@ -0,0 +1,58 @@ +:root { + --w: #FFFF; + --b: #111; + --g: #A6A6A6; + --rt-1: #64AAC7; + --rt-2: #984A4A; + --rt-3: #6E9158; + --rt-4: #7C6097; + + --b-2: #B26161; + --b-4: #9279A9; + --progress-bg: #595959; + } + + @font-face { + font-family: Calvino; + src: url(../font/calvino-trial/Calvino-Grande-Regular-trial.ttf); + font-weight: 500; + } + + @font-face { + font-family: Figtree; + src: url(../font/figtree/Figtree-Regular.ttf); + font-weight: 200; + } + + @font-face { + font-family: dm-serif; + src: url(../font/dm-serif/DMSerifDisplay-Regular.ttf); + font-weight: 100; + } + + @font-face { + font-family: Heroic; + src: url(../font/heroic/heroic-brutal.otf); + font-weight: 100; +} +@font-face { + font-family: Calvino-Grande; + src: url(../font/calvino-trial/Calvino-Grande-Bold-trial.ttf); + font-weight: 800; + } + +* { + font-family: Figtree; + scroll-behavior: smooth; + margin: 0; + padding: 0; + box-sizing: border-box; + scrollbar-width: none; + } + +*::-webkit-scrollbar {display: none;} + +::view-transition-old(root), +::view-transition-new(root) { + animation-duration: 1s; +} \ No newline at end of file diff --git a/my-app/static/favicon.png b/my-app/static/favicon.png new file mode 100644 index 00000000..825b9e65 Binary files /dev/null and b/my-app/static/favicon.png differ diff --git a/my-app/static/font/calvino-trial/Calvino-Bold-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Bold-Italic-trial.ttf new file mode 100644 index 00000000..b817af35 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Bold-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Bold-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Bold-trial.ttf new file mode 100644 index 00000000..d2607120 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Bold-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Book-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Book-Italic-trial.ttf new file mode 100644 index 00000000..cdc4acfd Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Book-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Book-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Book-trial.ttf new file mode 100644 index 00000000..dcab6103 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Book-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Extrabold-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Extrabold-Italic-trial.ttf new file mode 100644 index 00000000..942e88c6 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Extrabold-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Extrabold-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Extrabold-trial.ttf new file mode 100644 index 00000000..68628b0c Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Extrabold-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Extralight-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Extralight-Italic-trial.ttf new file mode 100644 index 00000000..f0c7c1ee Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Extralight-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Extralight-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Extralight-trial.ttf new file mode 100644 index 00000000..70a7fe62 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Extralight-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Black-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Black-Italic-trial.ttf new file mode 100644 index 00000000..25086138 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Black-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Black-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Black-trial.ttf new file mode 100644 index 00000000..d7a54c94 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Black-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Bold-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Bold-Italic-trial.ttf new file mode 100644 index 00000000..e1bcebde Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Bold-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Bold-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Bold-trial.ttf new file mode 100644 index 00000000..9a40cba2 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Bold-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Extrabold-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Extrabold-Italic-trial.ttf new file mode 100644 index 00000000..0f4cdc01 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Extrabold-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Extrabold-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Extrabold-trial.ttf new file mode 100644 index 00000000..2fa7d6f7 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Extrabold-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Extralight-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Extralight-Italic-trial.ttf new file mode 100644 index 00000000..b5d01c04 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Extralight-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Extralight-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Extralight-trial.ttf new file mode 100644 index 00000000..475dcf1b Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Extralight-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Italic-Variable-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Italic-Variable-trial.ttf new file mode 100644 index 00000000..211f28cc Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Italic-Variable-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Italic-trial.ttf new file mode 100644 index 00000000..8733cd96 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Light-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Light-Italic-trial.ttf new file mode 100644 index 00000000..6493a9de Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Light-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Light-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Light-trial.ttf new file mode 100644 index 00000000..6260bf2e Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Light-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Monoline-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Monoline-Italic-trial.ttf new file mode 100644 index 00000000..f63114f0 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Monoline-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Monoline-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Monoline-trial.ttf new file mode 100644 index 00000000..a0e3c331 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Monoline-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Regular-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Regular-trial.ttf new file mode 100644 index 00000000..a3b8d707 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Regular-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Semibold-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Semibold-Italic-trial.ttf new file mode 100644 index 00000000..c0fd85e2 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Semibold-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Semibold-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Semibold-trial.ttf new file mode 100644 index 00000000..1885e88d Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Semibold-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Thin-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Thin-Italic-trial.ttf new file mode 100644 index 00000000..6d7e6e7d Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Thin-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Thin-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Thin-trial.ttf new file mode 100644 index 00000000..40a43765 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Thin-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Grande-Variable-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Grande-Variable-trial.ttf new file mode 100644 index 00000000..193fcff0 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Grande-Variable-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Italic-Variable-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Italic-Variable-trial.ttf new file mode 100644 index 00000000..ca44c8ad Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Italic-Variable-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Italic-trial.ttf new file mode 100644 index 00000000..06e9a161 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Light-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Light-Italic-trial.ttf new file mode 100644 index 00000000..ce3a27ef Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Light-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Light-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Light-trial.ttf new file mode 100644 index 00000000..685a16cb Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Light-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Regular-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Regular-trial.ttf new file mode 100644 index 00000000..b0a2a697 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Regular-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Semibold-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Semibold-Italic-trial.ttf new file mode 100644 index 00000000..6e46af8a Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Semibold-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Semibold-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Semibold-trial.ttf new file mode 100644 index 00000000..5bffaa6b Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Semibold-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Thin-Italic-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Thin-Italic-trial.ttf new file mode 100644 index 00000000..6c8af494 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Thin-Italic-trial.ttf differ diff --git a/my-app/static/font/calvino-trial/Calvino-Thin-trial.ttf b/my-app/static/font/calvino-trial/Calvino-Thin-trial.ttf new file mode 100644 index 00000000..f655eac4 Binary files /dev/null and b/my-app/static/font/calvino-trial/Calvino-Thin-trial.ttf differ diff --git a/my-app/static/font/dm-serif/DMSerifDisplay-Italic.ttf b/my-app/static/font/dm-serif/DMSerifDisplay-Italic.ttf new file mode 100644 index 00000000..39fb5ae4 Binary files /dev/null and b/my-app/static/font/dm-serif/DMSerifDisplay-Italic.ttf differ diff --git a/my-app/static/font/dm-serif/DMSerifDisplay-Regular.ttf b/my-app/static/font/dm-serif/DMSerifDisplay-Regular.ttf new file mode 100644 index 00000000..65a57b7c Binary files /dev/null and b/my-app/static/font/dm-serif/DMSerifDisplay-Regular.ttf differ diff --git a/my-app/static/font/figtree/Figtree-Black.ttf b/my-app/static/font/figtree/Figtree-Black.ttf new file mode 100644 index 00000000..57948e89 Binary files /dev/null and b/my-app/static/font/figtree/Figtree-Black.ttf differ diff --git a/my-app/static/font/figtree/Figtree-BlackItalic.ttf b/my-app/static/font/figtree/Figtree-BlackItalic.ttf new file mode 100644 index 00000000..f0fffc3e Binary files /dev/null and b/my-app/static/font/figtree/Figtree-BlackItalic.ttf differ diff --git a/my-app/static/font/figtree/Figtree-Bold.ttf b/my-app/static/font/figtree/Figtree-Bold.ttf new file mode 100644 index 00000000..76d69527 Binary files /dev/null and b/my-app/static/font/figtree/Figtree-Bold.ttf differ diff --git a/my-app/static/font/figtree/Figtree-BoldItalic.ttf b/my-app/static/font/figtree/Figtree-BoldItalic.ttf new file mode 100644 index 00000000..126859d5 Binary files /dev/null and b/my-app/static/font/figtree/Figtree-BoldItalic.ttf differ diff --git a/my-app/static/font/figtree/Figtree-ExtraBold.ttf b/my-app/static/font/figtree/Figtree-ExtraBold.ttf new file mode 100644 index 00000000..93f6debf Binary files /dev/null and b/my-app/static/font/figtree/Figtree-ExtraBold.ttf differ diff --git a/my-app/static/font/figtree/Figtree-ExtraBoldItalic.ttf b/my-app/static/font/figtree/Figtree-ExtraBoldItalic.ttf new file mode 100644 index 00000000..74201159 Binary files /dev/null and b/my-app/static/font/figtree/Figtree-ExtraBoldItalic.ttf differ diff --git a/my-app/static/font/figtree/Figtree-Italic.ttf b/my-app/static/font/figtree/Figtree-Italic.ttf new file mode 100644 index 00000000..b220a17f Binary files /dev/null and b/my-app/static/font/figtree/Figtree-Italic.ttf differ diff --git a/my-app/static/font/figtree/Figtree-Light.ttf b/my-app/static/font/figtree/Figtree-Light.ttf new file mode 100644 index 00000000..246b77d9 Binary files /dev/null and b/my-app/static/font/figtree/Figtree-Light.ttf differ diff --git a/my-app/static/font/figtree/Figtree-LightItalic.ttf b/my-app/static/font/figtree/Figtree-LightItalic.ttf new file mode 100644 index 00000000..aeee7fea Binary files /dev/null and b/my-app/static/font/figtree/Figtree-LightItalic.ttf differ diff --git a/my-app/static/font/figtree/Figtree-Medium.ttf b/my-app/static/font/figtree/Figtree-Medium.ttf new file mode 100644 index 00000000..13ab96ca Binary files /dev/null and b/my-app/static/font/figtree/Figtree-Medium.ttf differ diff --git a/my-app/static/font/figtree/Figtree-MediumItalic.ttf b/my-app/static/font/figtree/Figtree-MediumItalic.ttf new file mode 100644 index 00000000..b2ee1f5b Binary files /dev/null and b/my-app/static/font/figtree/Figtree-MediumItalic.ttf differ diff --git a/my-app/static/font/figtree/Figtree-Regular.ttf b/my-app/static/font/figtree/Figtree-Regular.ttf new file mode 100644 index 00000000..c03409ba Binary files /dev/null and b/my-app/static/font/figtree/Figtree-Regular.ttf differ diff --git a/my-app/static/font/figtree/Figtree-SemiBold.ttf b/my-app/static/font/figtree/Figtree-SemiBold.ttf new file mode 100644 index 00000000..6c83802d Binary files /dev/null and b/my-app/static/font/figtree/Figtree-SemiBold.ttf differ diff --git a/my-app/static/font/figtree/Figtree-SemiBoldItalic.ttf b/my-app/static/font/figtree/Figtree-SemiBoldItalic.ttf new file mode 100644 index 00000000..d8c8c39a Binary files /dev/null and b/my-app/static/font/figtree/Figtree-SemiBoldItalic.ttf differ diff --git a/my-app/static/font/heroic/heroic-brutal.otf b/my-app/static/font/heroic/heroic-brutal.otf new file mode 100644 index 00000000..731a6a99 Binary files /dev/null and b/my-app/static/font/heroic/heroic-brutal.otf differ diff --git a/my-app/static/gradients/Gr-blue.png b/my-app/static/gradients/Gr-blue.png new file mode 100644 index 00000000..33be9a46 Binary files /dev/null and b/my-app/static/gradients/Gr-blue.png differ diff --git a/my-app/static/gradients/Gr-green.png b/my-app/static/gradients/Gr-green.png new file mode 100644 index 00000000..7597cdbc Binary files /dev/null and b/my-app/static/gradients/Gr-green.png differ diff --git a/my-app/static/gradients/Gr-pink.png b/my-app/static/gradients/Gr-pink.png new file mode 100644 index 00000000..535ebda8 Binary files /dev/null and b/my-app/static/gradients/Gr-pink.png differ diff --git a/my-app/static/gradients/Gr-red.png b/my-app/static/gradients/Gr-red.png new file mode 100644 index 00000000..a19b0df9 Binary files /dev/null and b/my-app/static/gradients/Gr-red.png differ diff --git a/my-app/static/gradients/Meshgrad-blue.png b/my-app/static/gradients/Meshgrad-blue.png new file mode 100644 index 00000000..f4f43e02 Binary files /dev/null and b/my-app/static/gradients/Meshgrad-blue.png differ diff --git a/my-app/static/gradients/Meshgrad-green.png b/my-app/static/gradients/Meshgrad-green.png new file mode 100644 index 00000000..6bdd0d3f Binary files /dev/null and b/my-app/static/gradients/Meshgrad-green.png differ diff --git a/my-app/static/gradients/Meshgrad-pink.png b/my-app/static/gradients/Meshgrad-pink.png new file mode 100644 index 00000000..2f15665e Binary files /dev/null and b/my-app/static/gradients/Meshgrad-pink.png differ diff --git a/my-app/static/gradients/Meshgrad-red.png b/my-app/static/gradients/Meshgrad-red.png new file mode 100644 index 00000000..0252665d Binary files /dev/null and b/my-app/static/gradients/Meshgrad-red.png differ diff --git a/my-app/svelte.config.js b/my-app/svelte.config.js new file mode 100644 index 00000000..2ca5922a --- /dev/null +++ b/my-app/svelte.config.js @@ -0,0 +1,13 @@ +import adapter from '@sveltejs/adapter-auto'; + +/** @type {import('@sveltejs/kit').Config} */ +const config = { + kit: { + // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list. + // If your environment is not supported, or you settled on a specific environment, switch out the adapter. + // See https://kit.svelte.dev/docs/adapters for more information about adapters. + adapter: adapter() + } +}; + +export default config; diff --git a/my-app/vite.config.js b/my-app/vite.config.js new file mode 100644 index 00000000..bbf8c7da --- /dev/null +++ b/my-app/vite.config.js @@ -0,0 +1,6 @@ +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [sveltekit()] +}); diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 100644 index 00000000..679bd163 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../acorn/bin/acorn" "$@" +else + exec node "$basedir/../acorn/bin/acorn" "$@" +fi diff --git a/node_modules/.bin/acorn.cmd b/node_modules/.bin/acorn.cmd new file mode 100644 index 00000000..a9324df9 --- /dev/null +++ b/node_modules/.bin/acorn.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\acorn\bin\acorn" %* diff --git a/node_modules/.bin/acorn.ps1 b/node_modules/.bin/acorn.ps1 new file mode 100644 index 00000000..6f6dcddf --- /dev/null +++ b/node_modules/.bin/acorn.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args + } else { + & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../acorn/bin/acorn" $args + } else { + & "node$exe" "$basedir/../acorn/bin/acorn" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/degit b/node_modules/.bin/degit new file mode 100644 index 00000000..1b81688c --- /dev/null +++ b/node_modules/.bin/degit @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../degit/degit" "$@" +else + exec node "$basedir/../degit/degit" "$@" +fi diff --git a/node_modules/.bin/degit.cmd b/node_modules/.bin/degit.cmd new file mode 100644 index 00000000..cdb1aab3 --- /dev/null +++ b/node_modules/.bin/degit.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\degit\degit" %* diff --git a/node_modules/.bin/degit.ps1 b/node_modules/.bin/degit.ps1 new file mode 100644 index 00000000..a555aa46 --- /dev/null +++ b/node_modules/.bin/degit.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../degit/degit" $args + } else { + & "$basedir/node$exe" "$basedir/../degit/degit" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../degit/degit" $args + } else { + & "node$exe" "$basedir/../degit/degit" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/esbuild b/node_modules/.bin/esbuild new file mode 100644 index 00000000..63bb6d40 --- /dev/null +++ b/node_modules/.bin/esbuild @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../esbuild/bin/esbuild" "$@" +else + exec node "$basedir/../esbuild/bin/esbuild" "$@" +fi diff --git a/node_modules/.bin/esbuild.cmd b/node_modules/.bin/esbuild.cmd new file mode 100644 index 00000000..cc920c59 --- /dev/null +++ b/node_modules/.bin/esbuild.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esbuild\bin\esbuild" %* diff --git a/node_modules/.bin/esbuild.ps1 b/node_modules/.bin/esbuild.ps1 new file mode 100644 index 00000000..81ffbf9c --- /dev/null +++ b/node_modules/.bin/esbuild.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args + } else { + & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../esbuild/bin/esbuild" $args + } else { + & "node$exe" "$basedir/../esbuild/bin/esbuild" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid new file mode 100644 index 00000000..46220bdb --- /dev/null +++ b/node_modules/.bin/nanoid @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../nanoid/bin/nanoid.cjs" "$@" +else + exec node "$basedir/../nanoid/bin/nanoid.cjs" "$@" +fi diff --git a/node_modules/.bin/nanoid.cmd b/node_modules/.bin/nanoid.cmd new file mode 100644 index 00000000..9c40107c --- /dev/null +++ b/node_modules/.bin/nanoid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nanoid\bin\nanoid.cjs" %* diff --git a/node_modules/.bin/nanoid.ps1 b/node_modules/.bin/nanoid.ps1 new file mode 100644 index 00000000..d8a4d7ad --- /dev/null +++ b/node_modules/.bin/nanoid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } else { + & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } else { + & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/rollup b/node_modules/.bin/rollup new file mode 100644 index 00000000..998fc164 --- /dev/null +++ b/node_modules/.bin/rollup @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../rollup/dist/bin/rollup" "$@" +else + exec node "$basedir/../rollup/dist/bin/rollup" "$@" +fi diff --git a/node_modules/.bin/rollup.cmd b/node_modules/.bin/rollup.cmd new file mode 100644 index 00000000..b3f110b3 --- /dev/null +++ b/node_modules/.bin/rollup.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\rollup\dist\bin\rollup" %* diff --git a/node_modules/.bin/rollup.ps1 b/node_modules/.bin/rollup.ps1 new file mode 100644 index 00000000..10f657d7 --- /dev/null +++ b/node_modules/.bin/rollup.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } else { + & "$basedir/node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } else { + & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/svelte-kit b/node_modules/.bin/svelte-kit new file mode 100644 index 00000000..b9c8383a --- /dev/null +++ b/node_modules/.bin/svelte-kit @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../@sveltejs/kit/svelte-kit.js" "$@" +else + exec node "$basedir/../@sveltejs/kit/svelte-kit.js" "$@" +fi diff --git a/node_modules/.bin/svelte-kit.cmd b/node_modules/.bin/svelte-kit.cmd new file mode 100644 index 00000000..38d52f90 --- /dev/null +++ b/node_modules/.bin/svelte-kit.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\@sveltejs\kit\svelte-kit.js" %* diff --git a/node_modules/.bin/svelte-kit.ps1 b/node_modules/.bin/svelte-kit.ps1 new file mode 100644 index 00000000..1ac1f3f7 --- /dev/null +++ b/node_modules/.bin/svelte-kit.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../@sveltejs/kit/svelte-kit.js" $args + } else { + & "$basedir/node$exe" "$basedir/../@sveltejs/kit/svelte-kit.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../@sveltejs/kit/svelte-kit.js" $args + } else { + & "node$exe" "$basedir/../@sveltejs/kit/svelte-kit.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/vite b/node_modules/.bin/vite new file mode 100644 index 00000000..014463f9 --- /dev/null +++ b/node_modules/.bin/vite @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../vite/bin/vite.js" "$@" +else + exec node "$basedir/../vite/bin/vite.js" "$@" +fi diff --git a/node_modules/.bin/vite.cmd b/node_modules/.bin/vite.cmd new file mode 100644 index 00000000..f62e966d --- /dev/null +++ b/node_modules/.bin/vite.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\vite\bin\vite.js" %* diff --git a/node_modules/.bin/vite.ps1 b/node_modules/.bin/vite.ps1 new file mode 100644 index 00000000..a7759bcf --- /dev/null +++ b/node_modules/.bin/vite.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../vite/bin/vite.js" $args + } else { + & "$basedir/node$exe" "$basedir/../vite/bin/vite.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../vite/bin/vite.js" $args + } else { + & "node$exe" "$basedir/../vite/bin/vite.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.cache/@babel/register/.babel.7.5.5.development.json b/node_modules/.cache/@babel/register/.babel.7.5.5.development.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/node_modules/.cache/@babel/register/.babel.7.5.5.development.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 00000000..77f9203b --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,710 @@ +{ + "name": "drop-and-heal", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@ampproject/remapping": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", + "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "peer": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", + "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", + "peer": true, + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "peer": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "peer": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", + "peer": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "peer": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@polka/url": { + "version": "1.0.0-next.28", + "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.28.tgz", + "integrity": "sha512-8LduaNlMZGwdZ6qWrKlfa+2M4gahzFkprZiAt2TF8uS0qQgBizKXpXURqvTJ4WtmupWxaLqjRb2UCTe72mu+Aw==", + "peer": true + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.22.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.22.5.tgz", + "integrity": "sha512-+lvL/4mQxSV8MukpkKyyvfwhH266COcWlXE/1qxwN08ajovta3459zrjLghYMgDerlzNwLAcFpvU+WWE5y6nAQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "peer": true + }, + "node_modules/@sveltejs/adapter-auto": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/@sveltejs/adapter-auto/-/adapter-auto-3.2.5.tgz", + "integrity": "sha512-27LR+uKccZ62lgq4N/hvyU2G+hTP9fxWEAfnZcl70HnyfAjMSsGk1z/SjAPXNCD1mVJIE7IFu3TQ8cQ/UH3c0A==", + "dependencies": { + "import-meta-resolve": "^4.1.0" + }, + "peerDependencies": { + "@sveltejs/kit": "^2.0.0" + } + }, + "node_modules/@sveltejs/kit": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.6.1.tgz", + "integrity": "sha512-QFlch3GPGZYidYhdRAub0fONw8UTguPICFHUSPxNkA/jdlU1p6C6yqq19J1QWdxIHS2El/ycDCGrHb3EAiMNqg==", + "hasInstallScript": true, + "peer": true, + "dependencies": { + "@types/cookie": "^0.6.0", + "cookie": "^0.6.0", + "devalue": "^5.1.0", + "esm-env": "^1.0.0", + "import-meta-resolve": "^4.1.0", + "kleur": "^4.1.5", + "magic-string": "^0.30.5", + "mrmime": "^2.0.0", + "sade": "^1.8.1", + "set-cookie-parser": "^2.6.0", + "sirv": "^2.0.4", + "tiny-glob": "^0.2.9" + }, + "bin": { + "svelte-kit": "svelte-kit.js" + }, + "engines": { + "node": ">=18.13" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1", + "svelte": "^4.0.0 || ^5.0.0-next.0", + "vite": "^5.0.3" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-3.1.2.tgz", + "integrity": "sha512-Txsm1tJvtiYeLUVRNqxZGKR/mI+CzuIQuc2gn+YCs9rMTowpNZ2Nqt53JdL8KF9bLhAf2ruR/dr9eZCwdTriRA==", + "peer": true, + "dependencies": { + "@sveltejs/vite-plugin-svelte-inspector": "^2.1.0", + "debug": "^4.3.4", + "deepmerge": "^4.3.1", + "kleur": "^4.1.5", + "magic-string": "^0.30.10", + "svelte-hmr": "^0.16.0", + "vitefu": "^0.2.5" + }, + "engines": { + "node": "^18.0.0 || >=20" + }, + "peerDependencies": { + "svelte": "^4.0.0 || ^5.0.0-next.0", + "vite": "^5.0.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte-inspector": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte-inspector/-/vite-plugin-svelte-inspector-2.1.0.tgz", + "integrity": "sha512-9QX28IymvBlSCqsCll5t0kQVxipsfhFFL+L2t3nTWfXnddYwxBuAEtTtlaVQpRz9c37BhJjltSeY4AJSC03SSg==", + "peer": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.0.0 || >=20" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^3.0.0", + "svelte": "^4.0.0 || ^5.0.0-next.0", + "vite": "^5.0.0" + } + }, + "node_modules/@types/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==", + "peer": true + }, + "node_modules/@types/estree": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", + "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "peer": true + }, + "node_modules/acorn": { + "version": "8.12.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", + "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aria-query": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz", + "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/code-red": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/code-red/-/code-red-1.0.4.tgz", + "integrity": "sha512-7qJWqItLA8/VPVlKJlFXU+NBlo/qyfs39aJcuMT/2ere32ZqvF5OSxgdM5xOfJJ7O429gg2HM47y8v9P+9wrNw==", + "peer": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15", + "@types/estree": "^1.0.1", + "acorn": "^8.10.0", + "estree-walker": "^3.0.3", + "periscopic": "^3.1.0" + } + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/css-tree": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.3.1.tgz", + "integrity": "sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==", + "peer": true, + "dependencies": { + "mdn-data": "2.0.30", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "peer": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/degit": { + "version": "2.8.4", + "resolved": "https://registry.npmjs.org/degit/-/degit-2.8.4.tgz", + "integrity": "sha512-vqYuzmSA5I50J882jd+AbAhQtgK6bdKUJIex1JNfEUPENCgYsxugzKVZlFyMwV4i06MmnV47/Iqi5Io86zf3Ng==", + "bin": { + "degit": "degit" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/devalue": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.1.1.tgz", + "integrity": "sha512-maua5KUiapvEwiEAe+XnlZ3Rh0GD+qI1J/nb9vrJc3muPXvcF/8gXYTWF76+5DAqHyDUtOIImEuo0YKE9mshVw==", + "peer": true + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "hasInstallScript": true, + "peer": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/esm-env": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.0.0.tgz", + "integrity": "sha512-Cf6VksWPsTuW01vU9Mk/3vRue91Zevka5SjyNf3nEpokFRuqt/KjUQoGAwq9qMmhpLTHmXzSIrFRw8zxWzmFBA==", + "peer": true + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "peer": true, + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/globalyzer": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/globalyzer/-/globalyzer-0.1.0.tgz", + "integrity": "sha512-40oNTM9UfG6aBmuKxk/giHn5nQ8RVz/SS4Ir6zgzOv9/qC3kKZ9v4etGTcJbEl/NyVQH7FGU7d+X1egr57Md2Q==", + "peer": true + }, + "node_modules/globrex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/globrex/-/globrex-0.1.2.tgz", + "integrity": "sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==", + "peer": true + }, + "node_modules/import-meta-resolve": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.1.0.tgz", + "integrity": "sha512-I6fiaX09Xivtk+THaMfAwnA3MVA5Big1WHF1Dfx9hFuvNIWpXnorlkzhcQf6ehrqQiiZECRt1poOAkPmer3ruw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-reference": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.2.tgz", + "integrity": "sha512-v3rht/LgVcsdZa3O2Nqs+NMowLOxeOm7Ay9+/ARQ2F+qEoANRcqrjAZKGN0v8ymUetZGgkp26LTnGT7H0Qo9Pg==", + "peer": true, + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "peer": true + }, + "node_modules/magic-string": { + "version": "0.30.11", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.11.tgz", + "integrity": "sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A==", + "peer": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0" + } + }, + "node_modules/mdn-data": { + "version": "2.0.30", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.30.tgz", + "integrity": "sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==", + "peer": true + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/mrmime": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.0.tgz", + "integrity": "sha512-eu38+hdgojoyq63s+yTpN4XMBdt5l8HhMhc4VKLO9KM5caLIBvUm4thi7fFaxyTmCKeNnXZ5pAlBwCUnhA09uw==", + "peer": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "peer": true + }, + "node_modules/nanoid": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/periscopic": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/periscopic/-/periscopic-3.1.0.tgz", + "integrity": "sha512-vKiQ8RRtkl9P+r/+oefh25C3fhybptkHKCZSPlcXiJux2tJF55GnEj3BVn4A5gKfq9NWWXXrxkHBwVPUfH0opw==", + "peer": true, + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^3.0.0", + "is-reference": "^3.0.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.0.tgz", + "integrity": "sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==", + "peer": true + }, + "node_modules/postcss": { + "version": "8.4.47", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.47.tgz", + "integrity": "sha512-56rxCq7G/XfB4EkXq9Egn5GCqugWvDFjafDOThIdMBsI15iqPqR5r15TfSr1YPYeEI19YeaXMCbY6u88Y76GLQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peer": true, + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.1.0", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.22.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.22.5.tgz", + "integrity": "sha512-WoinX7GeQOFMGznEcWA1WrTQCd/tpEbMkc3nuMs9BT0CPjMdSjPMTVClwWd4pgSQwJdP65SK9mTCNvItlr5o7w==", + "peer": true, + "dependencies": { + "@types/estree": "1.0.6" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.22.5", + "@rollup/rollup-android-arm64": "4.22.5", + "@rollup/rollup-darwin-arm64": "4.22.5", + "@rollup/rollup-darwin-x64": "4.22.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.22.5", + "@rollup/rollup-linux-arm-musleabihf": "4.22.5", + "@rollup/rollup-linux-arm64-gnu": "4.22.5", + "@rollup/rollup-linux-arm64-musl": "4.22.5", + "@rollup/rollup-linux-powerpc64le-gnu": "4.22.5", + "@rollup/rollup-linux-riscv64-gnu": "4.22.5", + "@rollup/rollup-linux-s390x-gnu": "4.22.5", + "@rollup/rollup-linux-x64-gnu": "4.22.5", + "@rollup/rollup-linux-x64-musl": "4.22.5", + "@rollup/rollup-win32-arm64-msvc": "4.22.5", + "@rollup/rollup-win32-ia32-msvc": "4.22.5", + "@rollup/rollup-win32-x64-msvc": "4.22.5", + "fsevents": "~2.3.2" + } + }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "peer": true, + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.0.tgz", + "integrity": "sha512-lXLOiqpkUumhRdFF3k1osNXCy9akgx/dyPZ5p8qAg9seJzXr5ZrlqZuWIMuY6ejOsVLE6flJ5/h3lsn57fQ/PQ==", + "peer": true + }, + "node_modules/sirv": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/sirv/-/sirv-2.0.4.tgz", + "integrity": "sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ==", + "peer": true, + "dependencies": { + "@polka/url": "^1.0.0-next.24", + "mrmime": "^2.0.0", + "totalist": "^3.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/svelte": { + "version": "4.2.19", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-4.2.19.tgz", + "integrity": "sha512-IY1rnGr6izd10B0A8LqsBfmlT5OILVuZ7XsI0vdGPEvuonFV7NYEUK4dAkm9Zg2q0Um92kYjTpS1CAP3Nh/KWw==", + "peer": true, + "dependencies": { + "@ampproject/remapping": "^2.2.1", + "@jridgewell/sourcemap-codec": "^1.4.15", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/estree": "^1.0.1", + "acorn": "^8.9.0", + "aria-query": "^5.3.0", + "axobject-query": "^4.0.0", + "code-red": "^1.0.3", + "css-tree": "^2.3.1", + "estree-walker": "^3.0.3", + "is-reference": "^3.0.1", + "locate-character": "^3.0.0", + "magic-string": "^0.30.4", + "periscopic": "^3.1.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/svelte-hmr": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/svelte-hmr/-/svelte-hmr-0.16.0.tgz", + "integrity": "sha512-Gyc7cOS3VJzLlfj7wKS0ZnzDVdv3Pn2IuVeJPk9m2skfhcu5bq3wtIZyQGggr7/Iim5rH5cncyQft/kRLupcnA==", + "peer": true, + "engines": { + "node": "^12.20 || ^14.13.1 || >= 16" + }, + "peerDependencies": { + "svelte": "^3.19.0 || ^4.0.0" + } + }, + "node_modules/tiny-glob": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/tiny-glob/-/tiny-glob-0.2.9.tgz", + "integrity": "sha512-g/55ssRPUjShh+xkfx9UPDXqhckHEsHr4Vd9zX55oSdGZc/MD0m3sferOkwWtp98bv+kcVfEHtRJgBVJzelrzg==", + "peer": true, + "dependencies": { + "globalyzer": "0.1.0", + "globrex": "^0.1.2" + } + }, + "node_modules/totalist": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz", + "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/vite": { + "version": "5.4.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.8.tgz", + "integrity": "sha512-FqrItQ4DT1NC4zCUqMB4c4AZORMKIa0m8/URVCZ77OZ/QSNeJ54bU1vrFADbDsuwfIPcgknRkmqakQcgnL4GiQ==", + "peer": true, + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vitefu": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-0.2.5.tgz", + "integrity": "sha512-SgHtMLoqaeeGnd2evZ849ZbACbnwQCIwRH57t18FxcXoZop0uQu0uzlIhJBlF/eWVzuce0sHeqPcDo+evVcg8Q==", + "peer": true, + "peerDependencies": { + "vite": "^3.0.0 || ^4.0.0 || ^5.0.0" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + } + } +} diff --git a/node_modules/.svelte2tsx-language-server-files/svelte-native-jsx.d.ts b/node_modules/.svelte2tsx-language-server-files/svelte-native-jsx.d.ts new file mode 100644 index 00000000..0c08d71c --- /dev/null +++ b/node_modules/.svelte2tsx-language-server-files/svelte-native-jsx.d.ts @@ -0,0 +1,32 @@ +declare namespace svelteNative.JSX { + + // Every namespace eligible for use needs to implement the following two functions + function mapElementTag( + tag: string + ): any; + + function createElement( + element: Key | undefined | null, attrs: Elements[Key] + ): any; + function createElement( + element: Key | undefined | null, attrEnhancers: T, attrs: Elements[Key] & T + ): any; + + + /* svelte specific */ + interface ElementClass { + $$prop_def: any; + } + + interface ElementAttributesProperty { + $$prop_def: any; // specify the property name to use + } + + // Add empty IntrinsicAttributes to prevent fallback to the one in the JSX namespace + interface IntrinsicAttributes { + } + + interface IntrinsicElements { + [name: string]: { [name: string]: any }; + } +} \ No newline at end of file diff --git a/node_modules/.svelte2tsx-language-server-files/svelte-shims-v4.d.ts b/node_modules/.svelte2tsx-language-server-files/svelte-shims-v4.d.ts new file mode 100644 index 00000000..fcaf92f6 --- /dev/null +++ b/node_modules/.svelte2tsx-language-server-files/svelte-shims-v4.d.ts @@ -0,0 +1,287 @@ +// Whenever a ambient declaration changes, its number should be increased +// This way, we avoid the situation where multiple ambient versions of svelte2tsx +// are loaded and their declarations conflict each other +// See https://github.com/sveltejs/language-tools/issues/1059 for an example bug that stems from it +// If you change anything in this file, think about whether or not it should be backported to svelte-shims.d.ts + +type AConstructorTypeOf = new (...args: U) => T; + +/** @internal PRIVATE API, DO NOT USE */ +type SvelteActionReturnType = { + update?: (args: any) => void, + destroy?: () => void +} | void + +/** @internal PRIVATE API, DO NOT USE */ +type SvelteTransitionConfig = { + delay?: number, + duration?: number, + easing?: (t: number) => number, + css?: (t: number, u: number) => string, + tick?: (t: number, u: number) => void +} + +/** @internal PRIVATE API, DO NOT USE */ +type SvelteTransitionReturnType = SvelteTransitionConfig | (() => SvelteTransitionConfig) + +/** @internal PRIVATE API, DO NOT USE */ +type SvelteAnimationReturnType = { + delay?: number, + duration?: number, + easing?: (t: number) => number, + css?: (t: number, u: number) => string, + tick?: (t: number, u: number) => void +} + +/** @internal PRIVATE API, DO NOT USE */ +type SvelteWithOptionalProps = Omit & Partial>; +/** @internal PRIVATE API, DO NOT USE */ +type SvelteAllProps = { [index: string]: any } +/** @internal PRIVATE API, DO NOT USE */ +type SveltePropsAnyFallback = {[K in keyof Props]: Props[K] extends never ? never : Props[K] extends undefined ? any : Props[K]} +/** @internal PRIVATE API, DO NOT USE */ +type SvelteSlotsAnyFallback = {[K in keyof Slots]: {[S in keyof Slots[K]]: Slots[K][S] extends undefined ? any : Slots[K][S]}} +/** @internal PRIVATE API, DO NOT USE */ +type SvelteRestProps = { [index: string]: any } +/** @internal PRIVATE API, DO NOT USE */ +type SvelteSlots = { [index: string]: any } +/** @internal PRIVATE API, DO NOT USE */ +type SvelteStore = { subscribe: (run: (value: T) => any, invalidate?: any) => any } + +// Forces TypeScript to look into the type which results in a better representation of it +// which helps for error messages and is necessary for d.ts file transformation so that +// no ambient type references are left in the output +/** @internal PRIVATE API, DO NOT USE */ +type Expand = T extends infer O ? { [K in keyof O]: O[K] } : never; + +/** @internal PRIVATE API, DO NOT USE */ +type KeysMatching = {[K in keyof Obj]-?: Obj[K] extends V ? K : never}[keyof Obj] +/** @internal PRIVATE API, DO NOT USE */ +declare type __sveltets_2_CustomEvents = {[K in KeysMatching]: T[K] extends CustomEvent ? T[K]['detail']: T[K]} + +declare function __sveltets_2_ensureRightProps(props: Props): {}; +declare function __sveltets_2_instanceOf(type: AConstructorTypeOf): T; +declare function __sveltets_2_allPropsType(): SvelteAllProps +declare function __sveltets_2_restPropsType(): SvelteRestProps +declare function __sveltets_2_slotsType(slots: Slots): Record; + +// Overload of the following two functions is necessary. +// An empty array of optionalProps makes OptionalProps type any, which means we lose the prop typing. +// optionalProps need to be first or its type cannot be infered correctly. + +declare function __sveltets_2_partial( + render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings } +): {props: Expand>, events: Events, slots: Expand>, exports?: Exports, bindings?: Bindings } +declare function __sveltets_2_partial( + optionalProps: OptionalProps[], + render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings } +): {props: Expand, OptionalProps>>, events: Events, slots: Expand>, exports?: Exports, bindings?: Bindings } + +declare function __sveltets_2_partial_with_any( + render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings } +): {props: Expand & SvelteAllProps>, events: Events, slots: Expand>, exports?: Exports, bindings?: Bindings } +declare function __sveltets_2_partial_with_any( + optionalProps: OptionalProps[], + render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings } +): {props: Expand, OptionalProps> & SvelteAllProps>, events: Events, slots: Expand>, exports?: Exports, bindings?: Bindings } + + +declare function __sveltets_2_with_any( + render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings } +): {props: Expand, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings } + +declare function __sveltets_2_with_any_event( + render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings } +): {props: Props, events: Events & {[evt: string]: CustomEvent;}, slots: Slots, exports?: Exports, bindings?: Bindings } + +declare function __sveltets_2_store_get(store: SvelteStore): T +declare function __sveltets_2_store_get | undefined | null>(store: Store): Store extends SvelteStore ? T : Store; +declare function __sveltets_2_any(dummy: any): any; +declare function __sveltets_2_invalidate(getValue: () => T): T + +declare function __sveltets_2_mapWindowEvent( + event: K +): HTMLBodyElementEventMap[K]; +declare function __sveltets_2_mapBodyEvent( + event: K +): WindowEventMap[K]; +declare function __sveltets_2_mapElementEvent( + event: K +): HTMLElementEventMap[K]; + +declare function __sveltets_2_bubbleEventDef( + events: Events, eventKey: K +): Events[K]; +declare function __sveltets_2_bubbleEventDef( + events: any, eventKey: string +): any; + +declare const __sveltets_2_customEvent: CustomEvent; +declare function __sveltets_2_toEventTypings(): {[Key in keyof Typings]: CustomEvent}; + +declare function __sveltets_2_unionType(t1: T1, t2: T2): T1 | T2; +declare function __sveltets_2_unionType(t1: T1, t2: T2, t3: T3): T1 | T2 | T3; +declare function __sveltets_2_unionType(t1: T1, t2: T2, t3: T3, t4: T4): T1 | T2 | T3 | T4; +declare function __sveltets_2_unionType(...types: any[]): any; + +declare function __sveltets_2_createSvelte2TsxComponent( + render: {props: Props, events: Events, slots: Slots } +): typeof import("svelte").SvelteComponent; + +declare function __sveltets_2_unwrapArr(arr: ArrayLike): T +declare function __sveltets_2_unwrapPromiseLike(promise: PromiseLike | T): T + +// v2 +declare function __sveltets_2_createCreateSlot>>(): (slotName: SlotName, attrs: Slots[SlotName]) => Record; +declare function __sveltets_2_createComponentAny(props: Record): import("svelte").SvelteComponent; + +declare function __sveltets_2_any(...dummy: any[]): any; +declare function __sveltets_2_empty(...dummy: any[]): {}; +declare function __sveltets_2_union(t1:T1,t2?:T2,t3?:T3,t4?:T4,t5?:T5,t6?:T6,t7?:T7,t8?:T8,t9?:T9,t10?:T10): T1 & T2 & T3 & T4 & T5 & T6 & T7 & T8 & T9 & T10; +declare function __sveltets_2_nonNullable(type: T): NonNullable; + +declare function __sveltets_2_cssProp(prop: Record): {}; + +// @ts-ignore Svelte v3/v4 don't have this +declare function __sveltets_2_ensureSnippet(val: ReturnType | undefined | null): any; + +/** @internal PRIVATE API, DO NOT USE */ +type __sveltets_2_SvelteAnimationReturnType = { + delay?: number, + duration?: number, + easing?: (t: number) => number, + css?: (t: number, u: number) => string, + tick?: (t: number, u: number) => void +} +declare var __sveltets_2_AnimationMove: { from: DOMRect, to: DOMRect } +declare function __sveltets_2_ensureAnimation(animationCall: __sveltets_2_SvelteAnimationReturnType): {}; + +/** @internal PRIVATE API, DO NOT USE */ +type __sveltets_2_SvelteActionReturnType = { + update?: (args: any) => void, + destroy?: () => void, + $$_attributes?: Record, +} | void +declare function __sveltets_2_ensureAction(actionCall: T): T extends {$$_attributes?: any} ? T['$$_attributes'] : {}; + +/** @internal PRIVATE API, DO NOT USE */ +type __sveltets_2_SvelteTransitionConfig = { + delay?: number, + duration?: number, + easing?: (t: number) => number, + css?: (t: number, u: number) => string, + tick?: (t: number, u: number) => void +} +/** @internal PRIVATE API, DO NOT USE */ +type __sveltets_2_SvelteTransitionReturnType = __sveltets_2_SvelteTransitionConfig | (() => __sveltets_2_SvelteTransitionConfig) +declare function __sveltets_2_ensureTransition(transitionCall: __sveltets_2_SvelteTransitionReturnType): {}; + +// Includes undefined and null for all types as all usages also allow these +declare function __sveltets_2_ensureType(type: AConstructorTypeOf, el: T | undefined | null): {}; +declare function __sveltets_2_ensureType(type1: AConstructorTypeOf, type2: AConstructorTypeOf, el: T1 | T2 | undefined | null): {}; + +// The following is necessary because there are two clashing errors that can't be solved at the same time +// when using Svelte2TsxComponent, more precisely the event typings in +// __sveltets_2_ensureComponent _SvelteComponent>(type: T): T; +// If we type it as "any", we have an error when using sth like {a: CustomEvent} +// If we type it as "{}", we have an error when using sth like {[evt: string]: CustomEvent} +// If we type it as "unknown", we get all kinds of follow up errors which we want to avoid +// Therefore introduce two more base classes just for this case. +/** + * Ambient type only used for intellisense, DO NOT USE IN YOUR PROJECT + */ +declare type ATypedSvelteComponent = { + /** + * @internal This is for type checking capabilities only + * and does not exist at runtime. Don't use this property. + */ + $$prop_def: any; + /** + * @internal This is for type checking capabilities only + * and does not exist at runtime. Don't use this property. + */ + $$events_def: any; + /** + * @internal This is for type checking capabilities only + * and does not exist at runtime. Don't use this property. + */ + $$slot_def: any; + + $on(event: string, handler: any): () => void; +} +/** + * Ambient type only used for intellisense, DO NOT USE IN YOUR PROJECT. + * + * If you're looking for the type of a Svelte Component, use `SvelteComponent` and `ComponentType` instead: + * + * ```ts + * import type { ComponentType, SvelteComponent } from "svelte"; + * let myComponentConstructor: ComponentType = ..; + * ``` + */ +declare type ConstructorOfATypedSvelteComponent = new (args: {target: any, props?: any}) => ATypedSvelteComponent +// Usage note: Cannot properly transform generic function components to class components due to TypeScript limitations +declare function __sveltets_2_ensureComponent< + T extends + | ConstructorOfATypedSvelteComponent + | (typeof import('svelte') extends { mount: any } + ? // @ts-ignore svelte.Component doesn't exist in Svelte 4 + import('svelte').Component + : never) + | null + | undefined +>( + type: T +): NonNullable< + T extends ConstructorOfATypedSvelteComponent + ? T + : typeof import('svelte') extends { mount: any } + ? // @ts-ignore svelte.Component doesn't exist in Svelte 4 + T extends import('svelte').Component< + infer Props extends Record, + infer Exports extends Record, + infer Bindings extends string + > + ? new ( + options: import('svelte').ComponentConstructorOptions + ) => import('svelte').SvelteComponent & + Exports & { $$bindings: Bindings } + : never + : never +>; + +declare function __sveltets_2_ensureArray | Iterable>(array: T): T extends ArrayLike ? U[] : T extends Iterable ? Iterable : any[]; + +type __sveltets_2_PropsWithChildren = Props & + (Slots extends { default: any } + // This is unfortunate because it means "accepts no props" turns into "accepts any prop" + // but the alternative is non-fixable type errors because of the way TypeScript index + // signatures work (they will always take precedence and make an impossible-to-satisfy children type). + ? Props extends Record + ? any + : { children?: any } + : {}); +declare function __sveltets_2_runes_constructor(render: {props: Props }): import("svelte").ComponentConstructorOptions; + +declare function __sveltets_2_get_set_binding(get: (() => T) | null | undefined, set: (t: T) => void): T; + +declare function __sveltets_$$bindings(...bindings: Bindings): Bindings[number]; + +declare function __sveltets_2_fn_component< + Props extends Record, Exports extends Record, Bindings extends string + // @ts-ignore Svelte 5 only +>(klass: {props: Props, exports?: Exports, bindings?: Bindings }): import('svelte').Component; + +interface __sveltets_2_IsomorphicComponent = any, Events extends Record = any, Slots extends Record = any, Exports = {}, Bindings = string> { + new (options: import('svelte').ComponentConstructorOptions): import('svelte').SvelteComponent & { $$bindings?: Bindings } & Exports; + (internal: unknown, props: Props extends Record ? {$$events?: Events, $$slots?: Slots} : Props & {$$events?: Events, $$slots?: Slots}): Exports & { $set?: any, $on?: any }; + z_$$bindings?: Bindings; +} + +declare function __sveltets_2_isomorphic_component< + Props extends Record, Events extends Record, Slots extends Record, Exports extends Record, Bindings extends string +>(klass: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }): __sveltets_2_IsomorphicComponent; + +declare function __sveltets_2_isomorphic_component_slots< + Props extends Record, Events extends Record, Slots extends Record, Exports extends Record, Bindings extends string +>(klass: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }): __sveltets_2_IsomorphicComponent<__sveltets_2_PropsWithChildren, Events, Slots, Exports, Bindings>; diff --git a/node_modules/@ampproject/remapping/LICENSE b/node_modules/@ampproject/remapping/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/node_modules/@ampproject/remapping/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@ampproject/remapping/README.md b/node_modules/@ampproject/remapping/README.md new file mode 100644 index 00000000..1463c9f6 --- /dev/null +++ b/node_modules/@ampproject/remapping/README.md @@ -0,0 +1,218 @@ +# @ampproject/remapping + +> Remap sequential sourcemaps through transformations to point at the original source code + +Remapping allows you to take the sourcemaps generated through transforming your code and "remap" +them to the original source locations. Think "my minified code, transformed with babel and bundled +with webpack", all pointing to the correct location in your original source code. + +With remapping, none of your source code transformations need to be aware of the input's sourcemap, +they only need to generate an output sourcemap. This greatly simplifies building custom +transformations (think a find-and-replace). + +## Installation + +```sh +npm install @ampproject/remapping +``` + +## Usage + +```typescript +function remapping( + map: SourceMap | SourceMap[], + loader: (file: string, ctx: LoaderContext) => (SourceMap | null | undefined), + options?: { excludeContent: boolean, decodedMappings: boolean } +): SourceMap; + +// LoaderContext gives the loader the importing sourcemap, tree depth, the ability to override the +// "source" location (where child sources are resolved relative to, or the location of original +// source), and the ability to override the "content" of an original source for inclusion in the +// output sourcemap. +type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +} +``` + +`remapping` takes the final output sourcemap, and a `loader` function. For every source file pointer +in the sourcemap, the `loader` will be called with the resolved path. If the path itself represents +a transformed file (it has a sourcmap associated with it), then the `loader` should return that +sourcemap. If not, the path will be treated as an original, untransformed source code. + +```js +// Babel transformed "helloworld.js" into "transformed.js" +const transformedMap = JSON.stringify({ + file: 'transformed.js', + // 1st column of 2nd line of output file translates into the 1st source + // file, line 3, column 2 + mappings: ';CAEE', + sources: ['helloworld.js'], + version: 3, +}); + +// Uglify minified "transformed.js" into "transformed.min.js" +const minifiedTransformedMap = JSON.stringify({ + file: 'transformed.min.js', + // 0th column of 1st line of output file translates into the 1st source + // file, line 2, column 1. + mappings: 'AACC', + names: [], + sources: ['transformed.js'], + version: 3, +}); + +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + // The "transformed.js" file is an transformed file. + if (file === 'transformed.js') { + // The root importer is empty. + console.assert(ctx.importer === ''); + // The depth in the sourcemap tree we're currently loading. + // The root `minifiedTransformedMap` is depth 0, and its source children are depth 1, etc. + console.assert(ctx.depth === 1); + + return transformedMap; + } + + // Loader will be called to load transformedMap's source file pointers as well. + console.assert(file === 'helloworld.js'); + // `transformed.js`'s sourcemap points into `helloworld.js`. + console.assert(ctx.importer === 'transformed.js'); + // This is a source child of `transformed`, which is a source child of `minifiedTransformedMap`. + console.assert(ctx.depth === 2); + return null; + } +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +In this example, `loader` will be called twice: + +1. `"transformed.js"`, the first source file pointer in the `minifiedTransformedMap`. We return the + associated sourcemap for it (its a transformed file, after all) so that sourcemap locations can + be traced through it into the source files it represents. +2. `"helloworld.js"`, our original, unmodified source code. This file does not have a sourcemap, so + we return `null`. + +The `remapped` sourcemap now points from `transformed.min.js` into locations in `helloworld.js`. If +you were to read the `mappings`, it says "0th column of the first line output line points to the 1st +column of the 2nd line of the file `helloworld.js`". + +### Multiple transformations of a file + +As a convenience, if you have multiple single-source transformations of a file, you may pass an +array of sourcemap files in the order of most-recent transformation sourcemap first. Note that this +changes the `importer` and `depth` of each call to our loader. So our above example could have been +written as: + +```js +const remapped = remapping( + [minifiedTransformedMap, transformedMap], + () => null +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +### Advanced control of the loading graph + +#### `source` + +The `source` property can overridden to any value to change the location of the current load. Eg, +for an original source file, it allows us to change the location to the original source regardless +of what the sourcemap source entry says. And for transformed files, it allows us to change the +relative resolving location for child sources of the loaded sourcemap. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // We pretend the transformed.js file actually exists in the 'src/' directory. When the nested + // source files are loaded, they will now be relative to `src/`. + ctx.source = 'src/transformed.js'; + return transformedMap; + } + + console.assert(file === 'src/helloworld.js'); + // We could futher change the source of this original file, eg, to be inside a nested directory + // itself. This will be reflected in the remapped sourcemap. + ctx.source = 'src/nested/transformed.js'; + return null; + } +); + +console.log(remapped); +// { +// …, +// sources: ['src/nested/helloworld.js'], +// }; +``` + + +#### `content` + +The `content` property can be overridden when we encounter an original source file. Eg, this allows +you to manually provide the source content of the original file regardless of whether the +`sourcesContent` field is present in the parent sourcemap. It can also be set to `null` to remove +the source content. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // transformedMap does not include a `sourcesContent` field, so usually the remapped sourcemap + // would not include any `sourcesContent` values. + return transformedMap; + } + + console.assert(file === 'helloworld.js'); + // We can read the file to provide the source content. + ctx.content = fs.readFileSync(file, 'utf8'); + return null; + } +); + +console.log(remapped); +// { +// …, +// sourcesContent: [ +// 'console.log("Hello world!")', +// ], +// }; +``` + +### Options + +#### excludeContent + +By default, `excludeContent` is `false`. Passing `{ excludeContent: true }` will exclude the +`sourcesContent` field from the returned sourcemap. This is mainly useful when you want to reduce +the size out the sourcemap. + +#### decodedMappings + +By default, `decodedMappings` is `false`. Passing `{ decodedMappings: true }` will leave the +`mappings` field in a [decoded state](https://github.com/rich-harris/sourcemap-codec) instead of +encoding into a VLQ string. diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs b/node_modules/@ampproject/remapping/dist/remapping.mjs new file mode 100644 index 00000000..f3875999 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs @@ -0,0 +1,197 @@ +import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping'; +import { GenMapping, maybeAddSegment, setSourceContent, setIgnore, toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping'; + +const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false); +const EMPTY_SOURCES = []; +function SegmentObject(source, line, column, name, content, ignore) { + return { source, line, column, name, content, ignore }; +} +function Source(map, sources, source, content, ignore) { + return { + map, + sources, + source, + content, + ignore, + }; +} +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +function MapSource(map, sources) { + return Source(map, sources, '', null, false); +} +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +function OriginalSource(source, content, ignore) { + return Source(null, EMPTY_SOURCES, source, content, ignore); +} +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source, ignore } = traced; + maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + setSourceContent(gen, source, content); + if (ignore) + setIgnore(gen, source, true); + } + } + return gen; +} +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content, source.ignore); + } + const segment = traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); +} + +function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; +} +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent, ignoreList } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + ignore: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content, ignore } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false; + return OriginalSource(source, sourceContent, ignored); + }); + return MapSource(map, children); +} + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.ignoreList = out.ignoreList; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} + +export { remapping as default }; +//# sourceMappingURL=remapping.mjs.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs.map b/node_modules/@ampproject/remapping/dist/remapping.mjs.map new file mode 100644 index 00000000..0eb007bf --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.mjs","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setIgnore, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n ignore: boolean;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n ignore: boolean;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n ignore: false;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null,\n ignore: boolean\n): SourceMapSegmentObject {\n return { source, line, column, name, content, ignore };\n}\n\nfunction Source(\n map: TraceMap,\n sources: Sources[],\n source: '',\n content: null,\n ignore: false\n): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null,\n ignore: boolean\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null,\n ignore: boolean\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n ignore,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null, false);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(\n source: string,\n content: string | null,\n ignore: boolean\n): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content, ignore);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source, ignore } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n if (ignore) setIgnore(gen, source, true);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content, source.ignore);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent, ignoreList } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n ignore: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content, ignore } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false;\n return OriginalSource(source, sourceContent, ignored);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n declare ignoreList: number[] | undefined;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n this.ignoreList = out.ignoreList as SourceMap['ignoreList'];\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\nexport type { SourceMap };\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":[],"mappings":";;;AAgCA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;AACtF,MAAM,aAAa,GAAc,EAAE,CAAC;AAEpC,SAAS,aAAa,CACpB,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IA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AAc,GAAG,GAAG,CAAC,cAA6C,CAAC;AACzE,SAAA;KACF;IAED,QAAQ,GAAA;AACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;KAC7B;AACF;;ACpBD;;;;;;;;;;;;;;AAcG;AACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;IAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;IAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClD;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js b/node_modules/@ampproject/remapping/dist/remapping.umd.js new file mode 100644 index 00000000..6b7b3bb5 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js @@ -0,0 +1,202 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@jridgewell/trace-mapping'), require('@jridgewell/gen-mapping')) : + typeof define === 'function' && define.amd ? define(['@jridgewell/trace-mapping', '@jridgewell/gen-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.remapping = factory(global.traceMapping, global.genMapping)); +})(this, (function (traceMapping, genMapping) { 'use strict'; + + const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false); + const EMPTY_SOURCES = []; + function SegmentObject(source, line, column, name, content, ignore) { + return { source, line, column, name, content, ignore }; + } + function Source(map, sources, source, content, ignore) { + return { + map, + sources, + source, + content, + ignore, + }; + } + /** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ + function MapSource(map, sources) { + return Source(map, sources, '', null, false); + } + /** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ + function OriginalSource(source, content, ignore) { + return Source(null, EMPTY_SOURCES, source, content, ignore); + } + /** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ + function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new genMapping.GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = traceMapping.decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source, ignore } = traced; + genMapping.maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + genMapping.setSourceContent(gen, source, content); + if (ignore) + genMapping.setIgnore(gen, source, true); + } + } + return gen; + } + /** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ + function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content, source.ignore); + } + const segment = traceMapping.traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); + } + + function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; + } + /** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ + function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new traceMapping.TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; + } + function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent, ignoreList } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + ignore: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content, ignore } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new traceMapping.TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false; + return OriginalSource(source, sourceContent, ignored); + }); + return MapSource(map, children); + } + + /** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ + class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? genMapping.toDecodedMap(map) : genMapping.toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.ignoreList = out.ignoreList; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } + } + + /** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ + function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); + } + + return remapping; + +})); +//# sourceMappingURL=remapping.umd.js.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js.map b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map new file mode 100644 index 00000000..d3f0f87d --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.umd.js","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setIgnore, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n ignore: boolean;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n ignore: boolean;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n ignore: false;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null,\n ignore: boolean\n): SourceMapSegmentObject {\n return { source, line, column, name, content, ignore };\n}\n\nfunction Source(\n map: TraceMap,\n sources: Sources[],\n source: '',\n content: null,\n ignore: false\n): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null,\n ignore: boolean\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null,\n ignore: boolean\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n ignore,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null, false);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(\n source: string,\n content: string | null,\n ignore: boolean\n): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content, ignore);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source, ignore } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n if (ignore) setIgnore(gen, source, true);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content, source.ignore);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent, ignoreList } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n ignore: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content, ignore } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false;\n return OriginalSource(source, sourceContent, ignored);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n declare ignoreList: number[] | undefined;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n this.ignoreList = out.ignoreList as SourceMap['ignoreList'];\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\nexport type { SourceMap };\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":["GenMapping","decodedMappings","maybeAddSegment","setSourceContent","setIgnore","traceSegment","TraceMap","toDecodedMap","toEncodedMap"],"mappings":";;;;;;IAgCA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IACtF,MAAM,aAAa,GAAc,EAAE,CAAC;IAEpC,SAAS,aAAa,CACpB,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAY,EACZ,OAAsB,EACtB,MAAe,EAAA;IAEf,IAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IACzD,CAAC;IAgBD,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAmB,EACnB,OAAsB,EACtB,MAAe,EAAA;QAEf,OAAO;YACL,GAAG;YACH,OAAO;YACP,MAAM;YACN,OAAO;YACP,MAAM;SACA,CAAC;IACX,CAAC;IAED;;;IAGG;IACa,SAAA,SAAS,CAAC,GAAa,EAAE,OAAkB,EAAA;IACzD,IAAA,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAC/C,CAAC;IAED;;;IAGG;aACa,cAAc,CAC5B,MAAc,EACd,OAAsB,EACtB,MAAe,EAAA;IAEf,IAAA,OAAO,MAAM,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAC9D,CAAC;IAED;;;IAGG;IACG,SAAU,aAAa,CAAC,IAAe,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AC,GAAGC,uBAAY,CAAC,GAAG,CAAC,CAAC;YAC5E,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;IAC3B,QAAA,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IACrB,QAAA,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAiC,CAAC;IACtD,QAAA,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,KAA2B,CAAC;IAC7C,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAqC,CAAC;IAC5D,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAEjC,QAAA,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAA+B,CAAC;IACnD,QAAA,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;IAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;IACzE,SAAA;SACF;QAED,QAAQ,GAAA;IACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;SAC7B;IACF;;ICpBD;;;;;;;;;;;;;;IAcG;IACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;QAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;QAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAClD;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts new file mode 100644 index 00000000..f87fceab --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts @@ -0,0 +1,14 @@ +import type { MapSource as MapSourceType } from './source-map-tree'; +import type { SourceMapInput, SourceMapLoader } from './types'; +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +export default function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType; diff --git a/node_modules/@ampproject/remapping/dist/types/remapping.d.ts b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts new file mode 100644 index 00000000..771fe307 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts @@ -0,0 +1,20 @@ +import SourceMap from './source-map'; +import type { SourceMapInput, SourceMapLoader, Options } from './types'; +export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types'; +export type { SourceMap }; +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +export default function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts new file mode 100644 index 00000000..935bc698 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts @@ -0,0 +1,45 @@ +import { GenMapping } from '@jridgewell/gen-mapping'; +import type { TraceMap } from '@jridgewell/trace-mapping'; +export declare type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; + ignore: boolean; +}; +export declare type OriginalSource = { + map: null; + sources: Sources[]; + source: string; + content: string | null; + ignore: boolean; +}; +export declare type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: null; + ignore: false; +}; +export declare type Sources = OriginalSource | MapSource; +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource; +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export declare function OriginalSource(source: string, content: string | null, ignore: boolean): OriginalSource; +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export declare function traceMappings(tree: MapSource): GenMapping; +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts new file mode 100644 index 00000000..cbd7f0af --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts @@ -0,0 +1,18 @@ +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types'; +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export default class SourceMap { + file?: string | null; + mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + sourceRoot?: string; + names: string[]; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList: number[] | undefined; + constructor(map: GenMapping, options: Options); + toString(): string; +} diff --git a/node_modules/@ampproject/remapping/dist/types/types.d.ts b/node_modules/@ampproject/remapping/dist/types/types.d.ts new file mode 100644 index 00000000..4d78c4bc --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/types.d.ts @@ -0,0 +1,15 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping'; +export type { SourceMapInput }; +export declare type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; + ignore: boolean | undefined; +}; +export declare type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void; +export declare type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; diff --git a/node_modules/@ampproject/remapping/package.json b/node_modules/@ampproject/remapping/package.json new file mode 100644 index 00000000..091224c6 --- /dev/null +++ b/node_modules/@ampproject/remapping/package.json @@ -0,0 +1,75 @@ +{ + "name": "@ampproject/remapping", + "version": "2.3.0", + "description": "Remap sequential sourcemaps through transformations to point at the original source code", + "keywords": [ + "source", + "map", + "remap" + ], + "main": "dist/remapping.umd.js", + "module": "dist/remapping.mjs", + "types": "dist/types/remapping.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/remapping.d.ts", + "browser": "./dist/remapping.umd.js", + "require": "./dist/remapping.umd.js", + "import": "./dist/remapping.mjs" + }, + "./dist/remapping.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/ampproject/remapping.git" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "jest --coverage", + "test:watch": "jest --coverage --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/jest": "27.4.1", + "@typescript-eslint/eslint-plugin": "5.20.0", + "@typescript-eslint/parser": "5.20.0", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "jest": "27.5.1", + "jest-config": "27.5.1", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "ts-jest": "27.1.4", + "tslib": "2.4.0", + "typescript": "4.6.3" + }, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } +} diff --git a/node_modules/@esbuild/win32-x64/README.md b/node_modules/@esbuild/win32-x64/README.md new file mode 100644 index 00000000..a99ee7cf --- /dev/null +++ b/node_modules/@esbuild/win32-x64/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is the Windows 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details. diff --git a/node_modules/@esbuild/win32-x64/esbuild.exe b/node_modules/@esbuild/win32-x64/esbuild.exe new file mode 100644 index 00000000..000370fe Binary files /dev/null and b/node_modules/@esbuild/win32-x64/esbuild.exe differ diff --git a/node_modules/@esbuild/win32-x64/package.json b/node_modules/@esbuild/win32-x64/package.json new file mode 100644 index 00000000..94abf8c9 --- /dev/null +++ b/node_modules/@esbuild/win32-x64/package.json @@ -0,0 +1,20 @@ +{ + "name": "@esbuild/win32-x64", + "version": "0.21.5", + "description": "The Windows 64-bit binary for esbuild, a JavaScript bundler.", + "repository": { + "type": "git", + "url": "git+https://github.com/evanw/esbuild.git" + }, + "license": "MIT", + "preferUnplugged": true, + "engines": { + "node": ">=12" + }, + "os": [ + "win32" + ], + "cpu": [ + "x64" + ] +} diff --git a/node_modules/@jridgewell/gen-mapping/LICENSE b/node_modules/@jridgewell/gen-mapping/LICENSE new file mode 100644 index 00000000..352f0715 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/gen-mapping/README.md b/node_modules/@jridgewell/gen-mapping/README.md new file mode 100644 index 00000000..4066cdbb --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/README.md @@ -0,0 +1,227 @@ +# @jridgewell/gen-mapping + +> Generate source maps + +`gen-mapping` allows you to generate a source map during transpilation or minification. +With a source map, you're able to trace the original location in the source file, either in Chrome's +DevTools or using a library like [`@jridgewell/trace-mapping`][trace-mapping]. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapGenerator`. This +provides the same `addMapping` and `setSourceContent` API. + +## Installation + +```sh +npm install @jridgewell/gen-mapping +``` + +## Usage + +```typescript +import { GenMapping, addMapping, setSourceContent, toEncodedMap, toDecodedMap } from '@jridgewell/gen-mapping'; + +const map = new GenMapping({ + file: 'output.js', + sourceRoot: 'https://example.com/', +}); + +setSourceContent(map, 'input.js', `function foo() {}`); + +addMapping(map, { + // Lines start at line 1, columns at column 0. + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +addMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 9 }, + name: 'foo', +}); + +assert.deepEqual(toDecodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: [ + [ [0, 0, 0, 0], [9, 0, 0, 9, 0] ] + ], +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: 'AAAA,SAASA', +}); +``` + +### Smaller Sourcemaps + +Not everything needs to be added to a sourcemap, and needless markings can cause signficantly +larger file sizes. `gen-mapping` exposes `maybeAddSegment`/`maybeAddMapping` APIs that will +intelligently determine if this marking adds useful information. If not, the marking will be +skipped. + +```typescript +import { maybeAddMapping } from '@jridgewell/gen-mapping'; + +const map = new GenMapping(); + +// Adding a sourceless marking at the beginning of a line isn't useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, +}); + +// Adding a new source marking is useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +// But adding another marking pointing to the exact same original location isn't, even if the +// generated column changed. +maybeAddMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + names: [], + sources: ['input.js'], + sourcesContent: [null], + mappings: 'AAAA', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map +Memory Usage: +gen-mapping: addSegment 5852872 bytes +gen-mapping: addMapping 7716042 bytes +source-map-js 6143250 bytes +source-map-0.6.1 6124102 bytes +source-map-0.8.0 6121173 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 441 ops/sec ±2.07% (90 runs sampled) +gen-mapping: addMapping x 350 ops/sec ±2.40% (86 runs sampled) +source-map-js: addMapping x 169 ops/sec ±2.42% (80 runs sampled) +source-map-0.6.1: addMapping x 167 ops/sec ±2.56% (80 runs sampled) +source-map-0.8.0: addMapping x 168 ops/sec ±2.52% (80 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 150,824,370 ops/sec ±0.07% (102 runs sampled) +gen-mapping: encoded output x 663 ops/sec ±0.22% (98 runs sampled) +source-map-js: encoded output x 197 ops/sec ±0.45% (84 runs sampled) +source-map-0.6.1: encoded output x 198 ops/sec ±0.33% (85 runs sampled) +source-map-0.8.0: encoded output x 197 ops/sec ±0.06% (93 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +babel.min.js.map +Memory Usage: +gen-mapping: addSegment 37578063 bytes +gen-mapping: addMapping 37212897 bytes +source-map-js 47638527 bytes +source-map-0.6.1 47690503 bytes +source-map-0.8.0 47470188 bytes +Smallest memory usage is gen-mapping: addMapping + +Adding speed: +gen-mapping: addSegment x 31.05 ops/sec ±8.31% (43 runs sampled) +gen-mapping: addMapping x 29.83 ops/sec ±7.36% (51 runs sampled) +source-map-js: addMapping x 20.73 ops/sec ±6.22% (38 runs sampled) +source-map-0.6.1: addMapping x 20.03 ops/sec ±10.51% (38 runs sampled) +source-map-0.8.0: addMapping x 19.30 ops/sec ±8.27% (37 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 381,379,234 ops/sec ±0.29% (96 runs sampled) +gen-mapping: encoded output x 95.15 ops/sec ±2.98% (72 runs sampled) +source-map-js: encoded output x 15.20 ops/sec ±7.41% (33 runs sampled) +source-map-0.6.1: encoded output x 16.36 ops/sec ±10.46% (31 runs sampled) +source-map-0.8.0: encoded output x 16.06 ops/sec ±6.45% (31 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +preact.js.map +Memory Usage: +gen-mapping: addSegment 416247 bytes +gen-mapping: addMapping 419824 bytes +source-map-js 1024619 bytes +source-map-0.6.1 1146004 bytes +source-map-0.8.0 1113250 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 13,755 ops/sec ±0.15% (98 runs sampled) +gen-mapping: addMapping x 13,013 ops/sec ±0.11% (101 runs sampled) +source-map-js: addMapping x 4,564 ops/sec ±0.21% (98 runs sampled) +source-map-0.6.1: addMapping x 4,562 ops/sec ±0.11% (99 runs sampled) +source-map-0.8.0: addMapping x 4,593 ops/sec ±0.11% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,864,020 ops/sec ±0.23% (93 runs sampled) +gen-mapping: encoded output x 14,368 ops/sec ±4.07% (82 runs sampled) +source-map-js: encoded output x 5,261 ops/sec ±0.21% (99 runs sampled) +source-map-0.6.1: encoded output x 5,124 ops/sec ±0.58% (99 runs sampled) +source-map-0.8.0: encoded output x 5,434 ops/sec ±0.33% (96 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +react.js.map +Memory Usage: +gen-mapping: addSegment 975096 bytes +gen-mapping: addMapping 1102981 bytes +source-map-js 2918836 bytes +source-map-0.6.1 2885435 bytes +source-map-0.8.0 2874336 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 4,772 ops/sec ±0.15% (100 runs sampled) +gen-mapping: addMapping x 4,456 ops/sec ±0.13% (97 runs sampled) +source-map-js: addMapping x 1,618 ops/sec ±0.24% (97 runs sampled) +source-map-0.6.1: addMapping x 1,622 ops/sec ±0.12% (99 runs sampled) +source-map-0.8.0: addMapping x 1,631 ops/sec ±0.12% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,107,695 ops/sec ±0.07% (99 runs sampled) +gen-mapping: encoded output x 5,421 ops/sec ±1.60% (89 runs sampled) +source-map-js: encoded output x 2,113 ops/sec ±1.81% (98 runs sampled) +source-map-0.6.1: encoded output x 2,126 ops/sec ±0.10% (100 runs sampled) +source-map-0.8.0: encoded output x 2,176 ops/sec ±0.39% (98 runs sampled) +Fastest is gen-mapping: decoded output +``` + +[source-map]: https://www.npmjs.com/package/source-map +[trace-mapping]: https://github.com/jridgewell/trace-mapping diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs new file mode 100644 index 00000000..5d38e383 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs @@ -0,0 +1,230 @@ +import { SetArray, put, remove } from '@jridgewell/set-array'; +import { encode } from '@jridgewell/sourcemap-codec'; +import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping'; + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; + +const NO_NAME = -1; +/** + * Provides the state to generate a sourcemap. + */ +class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + this._ignoreList = new SetArray(); + } +} +/** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ +function cast(map) { + return map; +} +function addSegment(map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); +} +function addMapping(map, mapping) { + return addMappingInternal(false, map, mapping); +} +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +const maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); +}; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +const maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); +}; +/** + * Adds/removes the content of the source file to the source map. + */ +function setSourceContent(map, source, content) { + const { _sources: sources, _sourcesContent: sourcesContent } = cast(map); + const index = put(sources, source); + sourcesContent[index] = content; +} +function setIgnore(map, source, ignore = true) { + const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map); + const index = put(sources, source); + if (index === sourcesContent.length) + sourcesContent[index] = null; + if (ignore) + put(ignoreList, index); + else + remove(ignoreList, index); +} +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +function toDecodedMap(map) { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList, } = cast(map); + removeEmptyFinalLines(mappings); + return { + version: 3, + file: map.file || undefined, + names: names.array, + sourceRoot: map.sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + ignoreList: ignoreList.array, + }; +} +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +function toEncodedMap(map) { + const decoded = toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) }); +} +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +function fromMap(input) { + const map = new TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(cast(gen)._names, map.names); + putAll(cast(gen)._sources, map.sources); + cast(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null); + cast(gen)._mappings = decodedMappings(map); + if (map.ignoreList) + putAll(cast(gen)._ignoreList, map.ignoreList); + return gen; +} +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +function allMappings(map) { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = cast(map); + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) + name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; +} +// This split declaration is only so that terser can elminiate the static initialization block. +function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = cast(map); + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert(line, index, name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]); +} +function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; +} +function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) + break; + } + return index; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) + break; + } + if (len < length) + mappings.length = len; +} +function putAll(setarr, array) { + for (let i = 0; i < array.length; i++) + put(setarr, array[i]); +} +function skipSourceless(line, index) { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) + return true; + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; +} +function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) + return false; + const prev = line[index - 1]; + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) + return false; + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return (sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); +} +function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null); + } + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, source, original.line - 1, original.column, name, content); +} + +export { GenMapping, addMapping, addSegment, allMappings, fromMap, maybeAddMapping, maybeAddSegment, setIgnore, setSourceContent, toDecodedMap, toEncodedMap }; +//# sourceMappingURL=gen-mapping.mjs.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map new file mode 100644 index 00000000..6290b970 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.mjs","sources":["../src/sourcemap-segment.ts","../src/gen-mapping.ts"],"sourcesContent":["type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n","import { SetArray, put, remove } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\nimport { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type { SourceMapInput } from '@jridgewell/trace-mapping';\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\nconst NO_NAME = -1;\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private declare _names: SetArray;\n private declare _sources: SetArray;\n private declare _sourcesContent: (string | null)[];\n private declare _mappings: SourceMapSegment[][];\n private declare _ignoreList: SetArray;\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this._names = new SetArray();\n this._sources = new SetArray();\n this._sourcesContent = [];\n this._mappings = [];\n this.file = file;\n this.sourceRoot = sourceRoot;\n this._ignoreList = new SetArray();\n }\n}\n\ninterface PublicMap {\n _names: GenMapping['_names'];\n _sources: GenMapping['_sources'];\n _sourcesContent: GenMapping['_sourcesContent'];\n _mappings: GenMapping['_mappings'];\n _ignoreList: GenMapping['_ignoreList'];\n}\n\n/**\n * Typescript doesn't allow friend access to private fields, so this just casts the map into a type\n * with public access modifiers.\n */\nfunction cast(map: unknown): PublicMap {\n return map as any;\n}\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport function addSegment(\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n content?: null,\n): void;\nexport function addSegment(\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n content?: string | null,\n): void;\nexport function addSegment(\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n content?: string | null,\n): void;\nexport function addSegment(\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: string | null,\n sourceLine?: number | null,\n sourceColumn?: number | null,\n name?: string | null,\n content?: string | null,\n): void {\n return addSegmentInternal(\n false,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n}\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport function addMapping(\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n content?: null;\n },\n): void;\nexport function addMapping(\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n content?: string | null;\n },\n): void;\nexport function addMapping(\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n content?: string | null;\n },\n): void;\nexport function addMapping(\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: string | null;\n original?: Pos | null;\n name?: string | null;\n content?: string | null;\n },\n): void {\n return addMappingInternal(false, map, mapping as Parameters[2]);\n}\n\n/**\n * Same as `addSegment`, but will only add the segment if it generates useful information in the\n * resulting map. This only works correctly if segments are added **in order**, meaning you should\n * not add a segment with a lower generated line/column than one that came before.\n */\nexport const maybeAddSegment: typeof addSegment = (\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n) => {\n return addSegmentInternal(\n true,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n};\n\n/**\n * Same as `addMapping`, but will only add the mapping if it generates useful information in the\n * resulting map. This only works correctly if mappings are added **in order**, meaning you should\n * not add a mapping with a lower generated line/column than one that came before.\n */\nexport const maybeAddMapping: typeof addMapping = (map, mapping) => {\n return addMappingInternal(true, map, mapping as Parameters[2]);\n};\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport function setSourceContent(map: GenMapping, source: string, content: string | null): void {\n const { _sources: sources, _sourcesContent: sourcesContent } = cast(map);\n const index = put(sources, source);\n sourcesContent[index] = content;\n}\n\nexport function setIgnore(map: GenMapping, source: string, ignore = true) {\n const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map);\n const index = put(sources, source);\n if (index === sourcesContent.length) sourcesContent[index] = null;\n if (ignore) put(ignoreList, index);\n else remove(ignoreList, index);\n}\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function toDecodedMap(map: GenMapping): DecodedSourceMap {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n _ignoreList: ignoreList,\n } = cast(map);\n removeEmptyFinalLines(mappings);\n\n return {\n version: 3,\n file: map.file || undefined,\n names: names.array,\n sourceRoot: map.sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n ignoreList: ignoreList.array,\n };\n}\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function toEncodedMap(map: GenMapping): EncodedSourceMap {\n const decoded = toDecodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n}\n\n/**\n * Constructs a new GenMapping, using the already present mappings of the input.\n */\nexport function fromMap(input: SourceMapInput): GenMapping {\n const map = new TraceMap(input);\n const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });\n\n putAll(cast(gen)._names, map.names);\n putAll(cast(gen)._sources, map.sources as string[]);\n cast(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null);\n cast(gen)._mappings = decodedMappings(map) as GenMapping['_mappings'];\n if (map.ignoreList) putAll(cast(gen)._ignoreList, map.ignoreList);\n\n return gen;\n}\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport function allMappings(map: GenMapping): Mapping[] {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = cast(map);\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[COLUMN] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[SOURCES_INDEX]];\n original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };\n\n if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n}\n\n// This split declaration is only so that terser can elminiate the static initialization block.\nfunction addSegmentInternal(\n skipable: boolean,\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: S,\n sourceLine: S extends string ? number : null | undefined,\n sourceColumn: S extends string ? number : null | undefined,\n name: S extends string ? string | null | undefined : null | undefined,\n content: S extends string ? string | null | undefined : null | undefined,\n): void {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = cast(map);\n const line = getLine(mappings, genLine);\n const index = getColumnIndex(line, genColumn);\n\n if (!source) {\n if (skipable && skipSourceless(line, index)) return;\n return insert(line, index, [genColumn]);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n\n const sourcesIndex = put(sources, source);\n const namesIndex = name ? put(names, name) : NO_NAME;\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;\n\n if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {\n return;\n }\n\n return insert(\n line,\n index,\n name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn],\n );\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], genColumn: number): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; index = i--) {\n const current = line[i];\n if (genColumn >= current[COLUMN]) break;\n }\n return index;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\nfunction removeEmptyFinalLines(mappings: SourceMapSegment[][]) {\n const { length } = mappings;\n let len = length;\n for (let i = len - 1; i >= 0; len = i, i--) {\n if (mappings[i].length > 0) break;\n }\n if (len < length) mappings.length = len;\n}\n\nfunction putAll(setarr: SetArray, array: T[]) {\n for (let i = 0; i < array.length; i++) put(setarr, array[i]);\n}\n\nfunction skipSourceless(line: SourceMapSegment[], index: number): boolean {\n // The start of a line is already sourceless, so adding a sourceless segment to the beginning\n // doesn't generate any useful information.\n if (index === 0) return true;\n\n const prev = line[index - 1];\n // If the previous segment is also sourceless, then adding another sourceless segment doesn't\n // genrate any new information. Else, this segment will end the source/named segment and point to\n // a sourceless position, which is useful.\n return prev.length === 1;\n}\n\nfunction skipSource(\n line: SourceMapSegment[],\n index: number,\n sourcesIndex: number,\n sourceLine: number,\n sourceColumn: number,\n namesIndex: number,\n): boolean {\n // A source/named segment at the start of a line gives position at that genColumn\n if (index === 0) return false;\n\n const prev = line[index - 1];\n\n // If the previous segment is sourceless, then we're transitioning to a source.\n if (prev.length === 1) return false;\n\n // If the previous segment maps to the exact same source position, then this segment doesn't\n // provide any new position information.\n return (\n sourcesIndex === prev[SOURCES_INDEX] &&\n sourceLine === prev[SOURCE_LINE] &&\n sourceColumn === prev[SOURCE_COLUMN] &&\n namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)\n );\n}\n\nfunction addMappingInternal(\n skipable: boolean,\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: S;\n original: S extends string ? Pos : null | undefined;\n name: S extends string ? string | null | undefined : null | undefined;\n content: S extends string ? string | null | undefined : null | undefined;\n },\n) {\n const { generated, source, original, name, content } = mapping;\n if (!source) {\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n null,\n null,\n null,\n null,\n null,\n );\n }\n assert(original);\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n source as string,\n original.line - 1,\n original.column,\n name,\n content,\n );\n}\n"],"names":[],"mappings":";;;;AAWO,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC;;ACQ5B,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC;AAEnB;;AAEG;MACU,UAAU,CAAA;AASrB,IAAA,WAAA,CAAY,EAAE,IAAI,EAAE,UAAU,KAAc,EAAE,EAAA;AAC5C,QAAA,IAAI,CAAC,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;AAC7B,QAAA,IAAI,CAAC,QAAQ,GAAG,IAAI,QAAQ,EAAE,CAAC;AAC/B,QAAA,IAAI,CAAC,eAAe,GAAG,EAAE,CAAC;AAC1B,QAAA,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;AACpB,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACjB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;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AI,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC,EAChE;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,QAAiB,EACjB,GAAe,EACf,OAMC,EAAA;AAED,IAAA,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IAC/D,IAAI,CAAC,MAAM,EAAE;QACX,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,CACL,CAAC;AACH,KAAA;AAED,IAAA,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,MAAgB,EAChB,QAAQ,CAAC,IAAI,GAAG,CAAC,EACjB,QAAQ,CAAC,MAAM,EACf,IAAI,EACJ,OAAO,CACR,CAAC;AACJ;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js new file mode 100644 index 00000000..3bf18f3a --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js @@ -0,0 +1,246 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/set-array'), require('@jridgewell/sourcemap-codec'), require('@jridgewell/trace-mapping')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/set-array', '@jridgewell/sourcemap-codec', '@jridgewell/trace-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.genMapping = {}, global.setArray, global.sourcemapCodec, global.traceMapping)); +})(this, (function (exports, setArray, sourcemapCodec, traceMapping) { 'use strict'; + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + + const NO_NAME = -1; + /** + * Provides the state to generate a sourcemap. + */ + class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new setArray.SetArray(); + this._sources = new setArray.SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + this._ignoreList = new setArray.SetArray(); + } + } + /** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ + function cast(map) { + return map; + } + function addSegment(map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + } + function addMapping(map, mapping) { + return addMappingInternal(false, map, mapping); + } + /** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ + const maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + /** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ + const maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); + }; + /** + * Adds/removes the content of the source file to the source map. + */ + function setSourceContent(map, source, content) { + const { _sources: sources, _sourcesContent: sourcesContent } = cast(map); + const index = setArray.put(sources, source); + sourcesContent[index] = content; + } + function setIgnore(map, source, ignore = true) { + const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map); + const index = setArray.put(sources, source); + if (index === sourcesContent.length) + sourcesContent[index] = null; + if (ignore) + setArray.put(ignoreList, index); + else + setArray.remove(ignoreList, index); + } + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + function toDecodedMap(map) { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList, } = cast(map); + removeEmptyFinalLines(mappings); + return { + version: 3, + file: map.file || undefined, + names: names.array, + sourceRoot: map.sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + ignoreList: ignoreList.array, + }; + } + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + function toEncodedMap(map) { + const decoded = toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: sourcemapCodec.encode(decoded.mappings) }); + } + /** + * Constructs a new GenMapping, using the already present mappings of the input. + */ + function fromMap(input) { + const map = new traceMapping.TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(cast(gen)._names, map.names); + putAll(cast(gen)._sources, map.sources); + cast(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null); + cast(gen)._mappings = traceMapping.decodedMappings(map); + if (map.ignoreList) + putAll(cast(gen)._ignoreList, map.ignoreList); + return gen; + } + /** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ + function allMappings(map) { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = cast(map); + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) + name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; + } + // This split declaration is only so that terser can elminiate the static initialization block. + function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = cast(map); + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = setArray.put(sources, source); + const namesIndex = name ? setArray.put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert(line, index, name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]); + } + function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; + } + function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) + break; + } + return index; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) + break; + } + if (len < length) + mappings.length = len; + } + function putAll(setarr, array) { + for (let i = 0; i < array.length; i++) + setArray.put(setarr, array[i]); + } + function skipSourceless(line, index) { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) + return true; + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; + } + function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) + return false; + const prev = line[index - 1]; + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) + return false; + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return (sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); + } + function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null); + } + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, source, original.line - 1, original.column, name, content); + } + + exports.GenMapping = GenMapping; + exports.addMapping = addMapping; + exports.addSegment = addSegment; + exports.allMappings = allMappings; + exports.fromMap = fromMap; + exports.maybeAddMapping = maybeAddMapping; + exports.maybeAddSegment = maybeAddSegment; + exports.setIgnore = setIgnore; + exports.setSourceContent = setSourceContent; + exports.toDecodedMap = toDecodedMap; + exports.toEncodedMap = toEncodedMap; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=gen-mapping.umd.js.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map new file mode 100644 index 00000000..72172ac7 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.umd.js","sources":["../src/sourcemap-segment.ts","../src/gen-mapping.ts"],"sourcesContent":["type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n","import { SetArray, put, remove } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\nimport { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type { SourceMapInput } from '@jridgewell/trace-mapping';\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\nconst NO_NAME = -1;\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private declare _names: SetArray;\n private declare _sources: SetArray;\n private declare _sourcesContent: (string | null)[];\n private declare _mappings: SourceMapSegment[][];\n private declare _ignoreList: SetArray;\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this._names = new SetArray();\n this._sources = new SetArray();\n this._sourcesContent = [];\n this._mappings = [];\n this.file = file;\n this.sourceRoot = sourceRoot;\n this._ignoreList = new SetArray();\n }\n}\n\ninterface PublicMap {\n _names: GenMapping['_names'];\n _sources: GenMapping['_sources'];\n _sourcesContent: GenMapping['_sourcesContent'];\n _mappings: GenMapping['_mappings'];\n _ignoreList: GenMapping['_ignoreList'];\n}\n\n/**\n * Typescript doesn't allow friend access to private fields, so this just casts the map into a type\n * with public access modifiers.\n */\nfunction cast(map: unknown): PublicMap {\n return map as any;\n}\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport function addSegment(\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n content?: null,\n): void;\nexport function addSegment(\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n content?: string | null,\n): void;\nexport function addSegment(\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n content?: string | null,\n): void;\nexport function addSegment(\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: string | null,\n sourceLine?: number | null,\n sourceColumn?: number | null,\n name?: string | null,\n content?: string | null,\n): void {\n return addSegmentInternal(\n false,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n}\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport function addMapping(\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n content?: null;\n },\n): void;\nexport function addMapping(\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n content?: string | null;\n },\n): void;\nexport function addMapping(\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n content?: string | null;\n },\n): void;\nexport function addMapping(\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: string | null;\n original?: Pos | null;\n name?: string | null;\n content?: string | null;\n },\n): void {\n return addMappingInternal(false, map, mapping as Parameters[2]);\n}\n\n/**\n * Same as `addSegment`, but will only add the segment if it generates useful information in the\n * resulting map. This only works correctly if segments are added **in order**, meaning you should\n * not add a segment with a lower generated line/column than one that came before.\n */\nexport const maybeAddSegment: typeof addSegment = (\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n) => {\n return addSegmentInternal(\n true,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n};\n\n/**\n * Same as `addMapping`, but will only add the mapping if it generates useful information in the\n * resulting map. This only works correctly if mappings are added **in order**, meaning you should\n * not add a mapping with a lower generated line/column than one that came before.\n */\nexport const maybeAddMapping: typeof addMapping = (map, mapping) => {\n return addMappingInternal(true, map, mapping as Parameters[2]);\n};\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport function setSourceContent(map: GenMapping, source: string, content: string | null): void {\n const { _sources: sources, _sourcesContent: sourcesContent } = cast(map);\n const index = put(sources, source);\n sourcesContent[index] = content;\n}\n\nexport function setIgnore(map: GenMapping, source: string, ignore = true) {\n const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map);\n const index = put(sources, source);\n if (index === sourcesContent.length) sourcesContent[index] = null;\n if (ignore) put(ignoreList, index);\n else remove(ignoreList, index);\n}\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function toDecodedMap(map: GenMapping): DecodedSourceMap {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n _ignoreList: ignoreList,\n } = cast(map);\n removeEmptyFinalLines(mappings);\n\n return {\n version: 3,\n file: map.file || undefined,\n names: names.array,\n sourceRoot: map.sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n ignoreList: ignoreList.array,\n };\n}\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function toEncodedMap(map: GenMapping): EncodedSourceMap {\n const decoded = toDecodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n}\n\n/**\n * Constructs a new GenMapping, using the already present mappings of the input.\n */\nexport function fromMap(input: SourceMapInput): GenMapping {\n const map = new TraceMap(input);\n const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });\n\n putAll(cast(gen)._names, map.names);\n putAll(cast(gen)._sources, map.sources as string[]);\n cast(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null);\n cast(gen)._mappings = decodedMappings(map) as GenMapping['_mappings'];\n if (map.ignoreList) putAll(cast(gen)._ignoreList, map.ignoreList);\n\n return gen;\n}\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport function allMappings(map: GenMapping): Mapping[] {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = cast(map);\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[COLUMN] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[SOURCES_INDEX]];\n original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };\n\n if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n}\n\n// This split declaration is only so that terser can elminiate the static initialization block.\nfunction addSegmentInternal(\n skipable: boolean,\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: S,\n sourceLine: S extends string ? number : null | undefined,\n sourceColumn: S extends string ? number : null | undefined,\n name: S extends string ? string | null | undefined : null | undefined,\n content: S extends string ? string | null | undefined : null | undefined,\n): void {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = cast(map);\n const line = getLine(mappings, genLine);\n const index = getColumnIndex(line, genColumn);\n\n if (!source) {\n if (skipable && skipSourceless(line, index)) return;\n return insert(line, index, [genColumn]);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n\n const sourcesIndex = put(sources, source);\n const namesIndex = name ? put(names, name) : NO_NAME;\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;\n\n if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {\n return;\n }\n\n return insert(\n line,\n index,\n name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn],\n );\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], genColumn: number): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; index = i--) {\n const current = line[i];\n if (genColumn >= current[COLUMN]) break;\n }\n return index;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\nfunction removeEmptyFinalLines(mappings: SourceMapSegment[][]) {\n const { length } = mappings;\n let len = length;\n for (let i = len - 1; i >= 0; len = i, i--) {\n if (mappings[i].length > 0) break;\n }\n if (len < length) mappings.length = len;\n}\n\nfunction putAll(setarr: SetArray, array: T[]) {\n for (let i = 0; i < array.length; i++) put(setarr, array[i]);\n}\n\nfunction skipSourceless(line: SourceMapSegment[], index: number): boolean {\n // The start of a line is already sourceless, so adding a sourceless segment to the beginning\n // doesn't generate any useful information.\n if (index === 0) return true;\n\n const prev = line[index - 1];\n // If the previous segment is also sourceless, then adding another sourceless segment doesn't\n // genrate any new information. Else, this segment will end the source/named segment and point to\n // a sourceless position, which is useful.\n return prev.length === 1;\n}\n\nfunction skipSource(\n line: SourceMapSegment[],\n index: number,\n sourcesIndex: number,\n sourceLine: number,\n sourceColumn: number,\n namesIndex: number,\n): boolean {\n // A source/named segment at the start of a line gives position at that genColumn\n if (index === 0) return false;\n\n const prev = line[index - 1];\n\n // If the previous segment is sourceless, then we're transitioning to a source.\n if (prev.length === 1) return false;\n\n // If the previous segment maps to the exact same source position, then this segment doesn't\n // provide any new position information.\n return (\n sourcesIndex === prev[SOURCES_INDEX] &&\n sourceLine === prev[SOURCE_LINE] &&\n sourceColumn === prev[SOURCE_COLUMN] &&\n namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)\n );\n}\n\nfunction addMappingInternal(\n skipable: boolean,\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: S;\n original: S extends string ? Pos : null | undefined;\n name: S extends string ? string | null | undefined : null | undefined;\n content: S extends string ? string | null | undefined : null | undefined;\n },\n) {\n const { generated, source, original, name, content } = mapping;\n if (!source) {\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n null,\n null,\n null,\n null,\n null,\n );\n }\n assert(original);\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n source as string,\n original.line - 1,\n original.column,\n name,\n content,\n );\n}\n"],"names":["SetArray","put","remove","encode","TraceMap","decodedMappings"],"mappings":";;;;;;IAWO,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IACtB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC;;ICQ5B,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC;IAEnB;;IAEG;UACU,UAAU,CAAA;IASrB,IAAA,WAAA,CAAY,EAAE,IAAI,EAAE,UAAU,KAAc,EAAE,EAAA;IAC5C,QAAA,IAAI,CAAC,MAAM,GAAG,IAAIA,iBAAQ,EAAE,CAAC;IAC7B,QAAA,IAAI,CAAC,QAAQ,GAAG,IAAIA,iBAAQ,EAAE,CAAC;IAC/B,QAAA,IAAI,CAAC,eAAe,GAAG,EAAE,CAAC;IAC1B,QAAA,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACpB,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACjB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC7B,QAAA,IAAI,CAAC,WAAW,GAAG,IAAIA,iBAAQ,EAAE,CAAC;SACnC;IACF,CAAA;IAUD;;;IAGG;IACH,SAAS,IAAI,CAAC,GAAY,EAAA;IACxB,IAAA,OAAO,GAAU,CAAC;IACpB,CAAC;aAoCe,UAAU,CACxB,GAAe,EACf,OAAe,EACf,SAAiB,EACjB,MAAsB,EACtB,UAA0B,EAC1B,YAA4B,EAC5B,IAAoB,E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;YACX,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,CACL,CAAC;IACH,KAAA;IAED,IAAA,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,MAAgB,EAChB,QAAQ,CAAC,IAAI,GAAG,CAAC,EACjB,QAAQ,CAAC,MAAM,EACf,IAAI,EACJ,OAAO,CACR,CAAC;IACJ;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts new file mode 100644 index 00000000..398a6956 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts @@ -0,0 +1,88 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export declare type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + private _ignoreList; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; +}): void; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare const maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare const maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare function setSourceContent(map: GenMapping, source: string, content: string | null): void; +export declare function setIgnore(map: GenMapping, source: string, ignore?: boolean): void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toDecodedMap(map: GenMapping): DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toEncodedMap(map: GenMapping): EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare function fromMap(input: SourceMapInput): GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare function allMappings(map: GenMapping): Mapping[]; diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 00000000..e187ba98 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,12 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts new file mode 100644 index 00000000..7f0ab15f --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts @@ -0,0 +1,36 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; + ignoreList?: readonly number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export declare type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; diff --git a/node_modules/@jridgewell/gen-mapping/package.json b/node_modules/@jridgewell/gen-mapping/package.json new file mode 100644 index 00000000..f2e7fe0e --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/package.json @@ -0,0 +1,76 @@ +{ + "name": "@jridgewell/gen-mapping", + "version": "0.3.5", + "description": "Generate source maps", + "keywords": [ + "source", + "map" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/gen-mapping", + "main": "dist/gen-mapping.umd.js", + "module": "dist/gen-mapping.mjs", + "types": "dist/types/gen-mapping.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/gen-mapping.d.ts", + "browser": "./dist/gen-mapping.umd.js", + "require": "./dist/gen-mapping.umd.js", + "import": "./dist/gen-mapping.mjs" + }, + "./dist/gen-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node benchmark/index.mjs", + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/mocha": "9.1.1", + "@types/node": "17.0.29", + "@typescript-eslint/eslint-plugin": "5.21.0", + "@typescript-eslint/parser": "5.21.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "mocha": "9.2.2", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "tsx": "4.7.1", + "typescript": "4.6.3" + }, + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + } +} diff --git a/node_modules/@jridgewell/resolve-uri/LICENSE b/node_modules/@jridgewell/resolve-uri/LICENSE new file mode 100644 index 00000000..0a81b2ad --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/LICENSE @@ -0,0 +1,19 @@ +Copyright 2019 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/README.md b/node_modules/@jridgewell/resolve-uri/README.md new file mode 100644 index 00000000..2fe70df7 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/README.md @@ -0,0 +1,40 @@ +# @jridgewell/resolve-uri + +> Resolve a URI relative to an optional base URI + +Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths. + +## Installation + +```sh +npm install @jridgewell/resolve-uri +``` + +## Usage + +```typescript +function resolve(input: string, base?: string): string; +``` + +```js +import resolve from '@jridgewell/resolve-uri'; + +resolve('foo', 'https://example.com'); // => 'https://example.com/foo' +``` + +| Input | Base | Resolution | Explanation | +|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------| +| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only | +| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol | +| `//example.com` | _rest_ | `//example.com/` | Input is normalized only | +| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin | +| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative | +| `/example` | _rest_ | `/example` | Input is normalized only | +| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base | +| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file | +| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory | +| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file | +| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory | +| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file | +| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory | +| `example` | `base/file` | `base/example` | Input is joined with the base without its file | diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 00000000..e958e881 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,232 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 00000000..1de97d01 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":"AAAA;AACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC;;;;;;;;;;AAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;AAE5F;;;;;;;;;AASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;AAuBpF,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAa;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;IACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK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C,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAE/B,IAAI,CAAC,IAAI;gBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;YAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;gBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;aAChC;YAED,OAAO,IAAI,GAAG,SAAS,CAAC;SACzB;QAED;YACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;QAE9B;YACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 00000000..a783049b --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,240 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 00000000..70a37f21 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":";;;;;;IAAA;IACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;IAErC;;;;;;;;;;IAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;IAE5F;;;;;;;;;IASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;IAuBpF,SAAS,aAAa,CAAC,KAAa;QAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,SAAS,mBAAmB,CAAC,KAAa;QACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,SAAS,cAAc,CAAC,KAAa;QACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,SAAS,CAAC,KAAa;QAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACnC,CAAC;IA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E,SAAS,GAAG,QAAQ,CAAC;SAChD;QAED,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAE9B,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC;QACvC,QAAQ,SAAS;;;YAIf,kBAAkB;YAClB;gBACE,OAAO,SAAS,CAAC;YAEnB,2BAA2B;;gBAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE/B,IAAI,CAAC,IAAI;oBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;gBAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;oBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;iBAChC;gBAED,OAAO,IAAI,GAAG,SAAS,CAAC;aACzB;YAED;gBACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;YAE9B;gBACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 00000000..b7f0b3b2 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/resolve-uri/package.json b/node_modules/@jridgewell/resolve-uri/package.json new file mode 100644 index 00000000..02a4c518 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/package.json @@ -0,0 +1,69 @@ +{ + "name": "@jridgewell/resolve-uri", + "version": "3.1.2", + "description": "Resolve a URI relative to an optional base URI", + "keywords": [ + "resolve", + "uri", + "url", + "path" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/resolve-uri", + "main": "dist/resolve-uri.umd.js", + "module": "dist/resolve-uri.mjs", + "types": "dist/types/resolve-uri.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/resolve-uri.d.ts", + "browser": "./dist/resolve-uri.umd.js", + "require": "./dist/resolve-uri.umd.js", + "import": "./dist/resolve-uri.mjs" + }, + "./dist/resolve-uri.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*", + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/set-array/LICENSE b/node_modules/@jridgewell/set-array/LICENSE new file mode 100644 index 00000000..352f0715 --- /dev/null +++ b/node_modules/@jridgewell/set-array/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/set-array/README.md b/node_modules/@jridgewell/set-array/README.md new file mode 100644 index 00000000..2ed155ff --- /dev/null +++ b/node_modules/@jridgewell/set-array/README.md @@ -0,0 +1,37 @@ +# @jridgewell/set-array + +> Like a Set, but provides the index of the `key` in the backing array + +This is designed to allow synchronizing a second array with the contents of the backing array, like +how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, and there +are never duplicates. + +## Installation + +```sh +npm install @jridgewell/set-array +``` + +## Usage + +```js +import { SetArray, get, put, pop } from '@jridgewell/set-array'; + +const sa = new SetArray(); + +let index = put(sa, 'first'); +assert.strictEqual(index, 0); + +index = put(sa, 'second'); +assert.strictEqual(index, 1); + +assert.deepEqual(sa.array, [ 'first', 'second' ]); + +index = get(sa, 'first'); +assert.strictEqual(index, 0); + +pop(sa); +index = get(sa, 'second'); +assert.strictEqual(index, undefined); +assert.deepEqual(sa.array, [ 'first' ]); +``` diff --git a/node_modules/@jridgewell/set-array/dist/set-array.mjs b/node_modules/@jridgewell/set-array/dist/set-array.mjs new file mode 100644 index 00000000..8a2d60b8 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.mjs @@ -0,0 +1,69 @@ +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +} +/** + * Typescript doesn't allow friend access to private fields, so this just casts the set into a type + * with public access modifiers. + */ +function cast(set) { + return set; +} +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +function get(setarr, key) { + return cast(setarr)._indexes[key]; +} +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +function put(setarr, key) { + // The key may or may not be present. If it is present, it's a number. + const index = get(setarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = cast(setarr); + const length = array.push(key); + return (indexes[key] = length - 1); +} +/** + * Pops the last added item out of the SetArray. + */ +function pop(setarr) { + const { array, _indexes: indexes } = cast(setarr); + if (array.length === 0) + return; + const last = array.pop(); + indexes[last] = undefined; +} +/** + * Removes the key, if it exists in the set. + */ +function remove(setarr, key) { + const index = get(setarr, key); + if (index === undefined) + return; + const { array, _indexes: indexes } = cast(setarr); + for (let i = index + 1; i < array.length; i++) { + const k = array[i]; + array[i - 1] = k; + indexes[k]--; + } + indexes[key] = undefined; + array.pop(); +} + +export { SetArray, get, pop, put, remove }; +//# sourceMappingURL=set-array.mjs.map diff --git a/node_modules/@jridgewell/set-array/dist/set-array.mjs.map b/node_modules/@jridgewell/set-array/dist/set-array.mjs.map new file mode 100644 index 00000000..9276dfa2 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.mjs","sources":["../src/set-array.ts"],"sourcesContent":["type Key = string | number | symbol;\n\n/**\n * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the\n * index of the `key` in the backing array.\n *\n * This is designed to allow synchronizing a second array with the contents of the backing array,\n * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,\n * and there are never duplicates.\n */\nexport class SetArray {\n private declare _indexes: Record;\n declare array: readonly T[];\n\n constructor() {\n this._indexes = { __proto__: null } as any;\n this.array = [];\n }\n}\n\ninterface PublicSet {\n array: T[];\n _indexes: SetArray['_indexes'];\n}\n\n/**\n * Typescript doesn't allow friend access to private fields, so this just casts the set into a type\n * with public access modifiers.\n */\nfunction cast(set: SetArray): PublicSet {\n return set as any;\n}\n\n/**\n * Gets the index associated with `key` in the backing array, if it is already present.\n */\nexport function get(setarr: SetArray, key: T): number | undefined {\n return cast(setarr)._indexes[key];\n}\n\n/**\n * Puts `key` into the backing array, if it is not already present. Returns\n * the index of the `key` in the backing array.\n */\nexport function put(setarr: SetArray, key: T): number {\n // The key may or may not be present. If it is present, it's a number.\n const index = get(setarr, key);\n if (index !== undefined) return index;\n\n const { array, _indexes: indexes } = cast(setarr);\n\n const length = array.push(key);\n return (indexes[key] = length - 1);\n}\n\n/**\n * Pops the last added item out of the SetArray.\n */\nexport function pop(setarr: SetArray): void {\n const { array, _indexes: indexes } = cast(setarr);\n if (array.length === 0) return;\n\n const last = array.pop()!;\n indexes[last] = undefined;\n}\n\n/**\n * Removes the key, if it exists in the set.\n */\nexport function remove(setarr: SetArray, key: T): void {\n const index = get(setarr, key);\n if (index === undefined) return;\n\n const { array, _indexes: indexes } = cast(setarr);\n for (let i = index + 1; i < array.length; i++) {\n const k = array[i];\n array[i - 1] = k;\n indexes[k]!--;\n }\n indexes[key] = undefined;\n array.pop();\n}\n"],"names":[],"mappings":"AAEA;;;;;;;;MAQa,QAAQ;IAInB;QACE,IAAI,CAAC,QAAQ,GAAG,EAAE,SAA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AC,MAAM,CAAC,CAAC;IAClD,KAAK,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAC7C,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACnB,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;QACjB,OAAO,CAAC,CAAC,CAAE,EAAE,CAAC;KACf;IACD,OAAO,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IACzB,KAAK,CAAC,GAAG,EAAE,CAAC;AACd;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/set-array/dist/set-array.umd.js b/node_modules/@jridgewell/set-array/dist/set-array.umd.js new file mode 100644 index 00000000..ab498cc1 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.umd.js @@ -0,0 +1,83 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.setArray = {})); +})(this, (function (exports) { 'use strict'; + + /** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ + class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } + } + /** + * Typescript doesn't allow friend access to private fields, so this just casts the set into a type + * with public access modifiers. + */ + function cast(set) { + return set; + } + /** + * Gets the index associated with `key` in the backing array, if it is already present. + */ + function get(setarr, key) { + return cast(setarr)._indexes[key]; + } + /** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ + function put(setarr, key) { + // The key may or may not be present. If it is present, it's a number. + const index = get(setarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = cast(setarr); + const length = array.push(key); + return (indexes[key] = length - 1); + } + /** + * Pops the last added item out of the SetArray. + */ + function pop(setarr) { + const { array, _indexes: indexes } = cast(setarr); + if (array.length === 0) + return; + const last = array.pop(); + indexes[last] = undefined; + } + /** + * Removes the key, if it exists in the set. + */ + function remove(setarr, key) { + const index = get(setarr, key); + if (index === undefined) + return; + const { array, _indexes: indexes } = cast(setarr); + for (let i = index + 1; i < array.length; i++) { + const k = array[i]; + array[i - 1] = k; + indexes[k]--; + } + indexes[key] = undefined; + array.pop(); + } + + exports.SetArray = SetArray; + exports.get = get; + exports.pop = pop; + exports.put = put; + exports.remove = remove; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=set-array.umd.js.map diff --git a/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map b/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map new file mode 100644 index 00000000..9edb8bc5 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.umd.js","sources":["../src/set-array.ts"],"sourcesContent":["type Key = string | number | symbol;\n\n/**\n * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the\n * index of the `key` in the backing array.\n *\n * This is designed to allow synchronizing a second array with the contents of the backing array,\n * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,\n * and there are never duplicates.\n */\nexport class SetArray {\n private declare _indexes: Record;\n declare array: readonly T[];\n\n constructor() {\n this._indexes = { __proto__: null } as any;\n this.array = [];\n }\n}\n\ninterface PublicSet {\n array: T[];\n _indexes: SetArray['_indexes'];\n}\n\n/**\n * Typescript doesn't allow friend access to private fields, so this just casts the set into a type\n * with public access modifiers.\n */\nfunction cast(set: SetArray): PublicSet {\n return set as any;\n}\n\n/**\n * Gets the index associated with `key` in the backing array, if it is already present.\n */\nexport function get(setarr: SetArray, key: T): number | undefined {\n return cast(setarr)._indexes[key];\n}\n\n/**\n * Puts `key` into the backing array, if it is not already present. Returns\n * the index of the `key` in the backing array.\n */\nexport function put(setarr: SetArray, key: T): number {\n // The key may or may not be present. If it is present, it's a number.\n const index = get(setarr, key);\n if (index !== undefined) return index;\n\n const { array, _indexes: indexes } = cast(setarr);\n\n const length = array.push(key);\n return (indexes[key] = length - 1);\n}\n\n/**\n * Pops the last added item out of the SetArray.\n */\nexport function pop(setarr: SetArray): void {\n const { array, _indexes: indexes } = cast(setarr);\n if (array.length === 0) return;\n\n const last = array.pop()!;\n indexes[last] = undefined;\n}\n\n/**\n * Removes the key, if it exists in the set.\n */\nexport function remove(setarr: SetArray, key: T): void {\n const index = get(setarr, key);\n if (index === undefined) return;\n\n const { array, _indexes: indexes } = cast(setarr);\n for (let i = index + 1; i < array.length; i++) {\n const k = array[i];\n array[i - 1] = k;\n indexes[k]!--;\n }\n indexes[key] = undefined;\n array.pop();\n}\n"],"names":[],"mappings":";;;;;;IAEA;;;;;;;;UAQa,QAAQ;QAInB;YACE,IAAI,CAAC,QAAQ,GAAG,EAAE,SAAS,EAAE,IAAI,EAAS,CAAC;YAC3C,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;SACjB;KACF;IAOD;;;;IAIA,SAAS,IAAI,CAAgB,GAAgB;QAC3C,OAAO,GAAU,CAAC;IACpB,CAAC;IAED;;;aAGgB,GAAG,CAAgB,MAAmB,EAAE,GAAM;QAC5D,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IACpC,CAAC;IAED;;;;aAIgB,GAAG,CAAgB,MAAmB,EAAE,GAAM;;QAE5D,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QAEtC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;QAElD,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/B,QAAQ,OAAO,CAAC,GAAG,CAAC,GAAG,MAAM,GAAG,CAAC,EAAE;IACrC,CAAC;IAED;;;aAGgB,GAAG,CAAgB,MAAmB;QACpD,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;QAClD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAE/B,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,EAAG,CAAC;QAC1B,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;IAC5B,CAAC;IAED;;;aAGgB,MAAM,CAAgB,MAAmB,EAAE,GAAM;QAC/D,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO;QAEhC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;QAClD,KAAK,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC7C,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YACnB,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;YACjB,OAAO,CAAC,CAAC,CAAE,EAAE,CAAC;SACf;QACD,OAAO,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;QACzB,KAAK,CAAC,GAAG,EAAE,CAAC;IACd;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts b/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts new file mode 100644 index 00000000..5f68e5db --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts @@ -0,0 +1,32 @@ +declare type Key = string | number | symbol; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly T[]; + constructor(); +} +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare function get(setarr: SetArray, key: T): number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare function put(setarr: SetArray, key: T): number; +/** + * Pops the last added item out of the SetArray. + */ +export declare function pop(setarr: SetArray): void; +/** + * Removes the key, if it exists in the set. + */ +export declare function remove(setarr: SetArray, key: T): void; +export {}; diff --git a/node_modules/@jridgewell/set-array/package.json b/node_modules/@jridgewell/set-array/package.json new file mode 100644 index 00000000..f652ca59 --- /dev/null +++ b/node_modules/@jridgewell/set-array/package.json @@ -0,0 +1,65 @@ +{ + "name": "@jridgewell/set-array", + "version": "1.2.1", + "description": "Like a Set, but provides the index of the `key` in the backing array", + "keywords": [], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/set-array", + "main": "dist/set-array.umd.js", + "module": "dist/set-array.mjs", + "typings": "dist/types/set-array.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/set-array.d.ts", + "browser": "./dist/set-array.umd.js", + "require": "./dist/set-array.umd.js", + "import": "./dist/set-array.mjs" + }, + "./dist/set-array.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/mocha": "9.1.1", + "@types/node": "17.0.29", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "tsx": "4.7.1", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 00000000..a331065a --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2015 Rich Harris + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@jridgewell/sourcemap-codec/README.md b/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 00000000..b3e0708b --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,264 @@ +# @jridgewell/sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install @jridgewell/sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v20.10.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +local code 5815135 bytes +@jridgewell/sourcemap-codec 1.4.15 5868160 bytes +sourcemap-codec 5492584 bytes +source-map-0.6.1 13569984 bytes +source-map-0.8.0 6390584 bytes +chrome dev tools 8011136 bytes +Smallest memory usage is sourcemap-codec + +Decode speed: +decode: local code x 492 ops/sec ±1.22% (90 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled) +decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled) +decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled) +decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled) +chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 444248 bytes +@jridgewell/sourcemap-codec 1.4.15 623024 bytes +sourcemap-codec 8696280 bytes +source-map-0.6.1 8745176 bytes +source-map-0.8.0 8736624 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 796 ops/sec ±0.11% (97 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled) +encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled) +encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled) +encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled) +Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +local code 35424960 bytes +@jridgewell/sourcemap-codec 1.4.15 35424696 bytes +sourcemap-codec 36033464 bytes +source-map-0.6.1 62253704 bytes +source-map-0.8.0 43843920 bytes +chrome dev tools 45111400 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Decode speed: +decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled) +decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled) +decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled) +decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled) +chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 2606016 bytes +@jridgewell/sourcemap-codec 1.4.15 2626440 bytes +sourcemap-codec 21152576 bytes +source-map-0.6.1 25023928 bytes +source-map-0.8.0 25256448 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 127 ops/sec ±0.18% (83 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled) +encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled) +encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled) +encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +local code 261696 bytes +@jridgewell/sourcemap-codec 1.4.15 244296 bytes +sourcemap-codec 302816 bytes +source-map-0.6.1 939176 bytes +source-map-0.8.0 336 bytes +chrome dev tools 587368 bytes +Smallest memory usage is source-map-0.8.0 + +Decode speed: +decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled) +decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled) +decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled) +decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled) +chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 262944 bytes +@jridgewell/sourcemap-codec 1.4.15 25544 bytes +sourcemap-codec 323048 bytes +source-map-0.6.1 507808 bytes +source-map-0.8.0 507480 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Encode speed: +encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled) +encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled) +encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +local code 678816 bytes +@jridgewell/sourcemap-codec 1.4.15 678816 bytes +sourcemap-codec 816400 bytes +source-map-0.6.1 2288864 bytes +source-map-0.8.0 721360 bytes +chrome dev tools 1012512 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled) +decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled) +decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled) +decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled) +chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 140960 bytes +@jridgewell/sourcemap-codec 1.4.15 159808 bytes +sourcemap-codec 969304 bytes +source-map-0.6.1 930520 bytes +source-map-0.8.0 930248 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled) +encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled) +encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled) +Fastest is encode: local code + + +*** + + +vscode.map - 2141001 segments + +Decode Memory Usage: +local code 198955264 bytes +@jridgewell/sourcemap-codec 1.4.15 199175352 bytes +sourcemap-codec 199102688 bytes +source-map-0.6.1 386323432 bytes +source-map-0.8.0 244116432 bytes +chrome dev tools 293734280 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled) +decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled) +decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled) +decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled) +chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 13509880 bytes +@jridgewell/sourcemap-codec 1.4.15 13537648 bytes +sourcemap-codec 32540104 bytes +source-map-0.6.1 127531040 bytes +source-map-0.8.0 127535312 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled) +encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled) +encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled) +encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 +``` + +# License + +MIT diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 00000000..60e17b3d --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,424 @@ +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + return relative + value; +} +function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? (-delta << 1) | 1 : delta << 1; + do { + let clamped = delta & 0b011111; + delta >>>= 5; + if (delta > 0) + clamped |= 0b100000; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) + return false; + return reader.peek() !== comma; +} + +const bufLength = 1024 * 16; +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +class StringWriter { + constructor() { + this.pos = 0; + this.out = ''; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +} +class StringReader { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +} + +const EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 0b0001; + const scope = (hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]); + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length;) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) + writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 0b0001 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) + encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length;) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(';'); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 0b0001; + const hasCallsite = fields & 0b0010; + const hasScope = fields & 0b0100; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger(reader, definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } + else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger(reader, sameSource && prevLine === callsiteLine ? callsiteColumn : 0); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } + else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) + return ''; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length;) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, isScope, callsite, bindings, } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } + else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } + else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) + encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length;) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } + else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(';'); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) + sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } + else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } + else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) + sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) + writer.write(semicolon); + if (line.length === 0) + continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) + writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) + continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) + continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); +} + +export { decode, decodeGeneratedRanges, decodeOriginalScopes, encode, encodeGeneratedRanges, encodeOriginalScopes }; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 00000000..73882288 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.mjs","sources":["../src/vlq.ts","../src/strings.ts","../src/scopes.ts","../src/sourcemap-codec.ts"],"sourcesContent":["import type { StringReader, StringWriter } from './strings';\n\nexport const comma = ','.charCodeAt(0);\nexport const semicolon = ';'.charCodeAt(0);\n\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\nexport function decodeInteger(reader: StringReader, relative: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = reader.next();\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n return relative + value;\n}\n\nexport function encodeInteger(builder: StringWriter, num: number, relative: number): number {\n let delta = num - relative;\n\n delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;\n do {\n let clamped = delta & 0b011111;\n delta >>>= 5;\n if (delta > 0) clamped |= 0b100000;\n builder.write(intToChar[clamped]);\n } while (delta > 0);\n\n return num;\n}\n\nexport function hasMoreVlq(reader: StringReader, max: number) {\n if (reader.pos >= max) return false;\n return reader.peek() !== comma;\n}\n","const bufLength = 1024 * 16;\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array): string {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array): string {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport class StringWriter {\n pos = 0;\n private out = '';\n private buffer = new Uint8Array(bufLength);\n\n write(v: number): void {\n const { buffer } = this;\n buffer[this.pos++] = v;\n if (this.pos === bufLength) {\n this.out += td.decode(buffer);\n this.pos = 0;\n }\n }\n\n flush(): string {\n const { buffer, out, pos } = this;\n return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;\n }\n}\n\nexport class StringReader {\n pos = 0;\n private declare buffer: string;\n\n constructor(buffer: string) {\n this.buffer = buffer;\n }\n\n next(): number {\n return this.buffer.charCodeAt(this.pos++);\n }\n\n peek(): number {\n return this.buffer.charCodeAt(this.pos);\n }\n\n indexOf(char: string): number {\n const { buffer, pos } = this;\n const idx = buffer.indexOf(char, pos);\n return idx === -1 ? buffer.length : idx;\n }\n}\n","import { StringReader, StringWriter } from './strings';\nimport { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';\n\nconst EMPTY: any[] = [];\n\ntype Line = number;\ntype Column = number;\ntype Kind = number;\ntype Name = number;\ntype Var = number;\ntype SourcesIndex = number;\ntype ScopesIndex = number;\n\ntype Mix = (A & O) | (B & O);\n\nexport type OriginalScope = Mix<\n [Line, Column, Line, Column, Kind],\n [Line, Column, Line, Column, Kind, Name],\n { vars: Var[] }\n>;\n\nexport type GeneratedRange = Mix<\n [Line, Column, Line, Column],\n [Line, Column, Line, Column, SourcesIndex, ScopesIndex],\n {\n callsite: CallSite | null;\n bindings: Binding[];\n isScope: boolean;\n }\n>;\nexport type CallSite = [SourcesIndex, Line, Column];\ntype Binding = BindingExpressionRange[];\nexport type BindingExpressionRange = [Name] | [Name, Line, Column];\n\nexport function decodeOriginalScopes(input: string): OriginalScope[] {\n const { length } = input;\n const reader = new StringReader(input);\n const scopes: OriginalScope[] = [];\n const stack: OriginalScope[] = [];\n let line = 0;\n\n for (; reader.pos < length; reader.pos++) {\n line = decodeInteger(reader, line);\n const column = decodeInteger(reader, 0);\n\n if (!hasMoreVlq(reader, length)) {\n const last = stack.pop()!;\n last[2] = line;\n last[3] = column;\n continue;\n }\n\n const kind = decodeInteger(reader, 0);\n const fields = decodeInteger(reader, 0);\n const hasName = fields & 0b0001;\n\n const scope: OriginalScope = (\n hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]\n ) as OriginalScope;\n\n let vars: Var[] = EMPTY;\n if (hasMoreVlq(reader, length)) {\n vars = [];\n do {\n const varsIndex = decodeInteger(reader, 0);\n vars.push(varsIndex);\n } while (hasMoreVlq(reader, length));\n }\n scope.vars = vars;\n\n scopes.push(scope);\n stack.push(scope);\n }\n\n return scopes;\n}\n\nexport function encodeOriginalScopes(scopes: OriginalScope[]): string {\n const writer = new StringWriter();\n\n for (let i = 0; i < scopes.length; ) {\n i = _encodeOriginalScopes(scopes, i, writer, [0]);\n }\n\n return writer.flush();\n}\n\nfunction _encodeOriginalScopes(\n scopes: OriginalScope[],\n index: number,\n writer: StringWriter,\n state: [\n number, // GenColumn\n ],\n): number {\n const scope = scopes[index];\n const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;\n\n if (index > 0) writer.write(comma);\n\n state[0] = encodeInteger(writer, startLine, state[0]);\n encodeInteger(writer, startColumn, 0);\n encodeInteger(writer, kind, 0);\n\n const fields = scope.length === 6 ? 0b0001 : 0;\n encodeInteger(writer, fields, 0);\n if (scope.length === 6) encodeInteger(writer, scope[5], 0);\n\n for (const v of vars) {\n encodeInteger(writer, v, 0);\n }\n\n for (index++; index < scopes.length; ) {\n const next = scopes[index];\n const { 0: l, 1: c } = next;\n if (l > endLine || (l === endLine && c >= endColumn)) {\n break;\n }\n index = _encodeOriginalScopes(scopes, index, writer, state);\n }\n\n writer.write(comma);\n state[0] = encodeInteger(writer, endLine, state[0]);\n encodeInteger(writer, endColumn, 0);\n\n return index;\n}\n\nexport function decodeGeneratedRanges(input: string): GeneratedRange[] {\n const { length } = input;\n const reader = new StringReader(input);\n const ranges: GeneratedRange[] = [];\n const stack: GeneratedRange[] = [];\n\n let genLine = 0;\n let definitionSourcesIndex = 0;\n let definitionScopeIndex = 0;\n let callsiteSourcesIndex = 0;\n let callsiteLine = 0;\n let callsiteColumn = 0;\n let bindingLine = 0;\n let bindingColumn = 0;\n\n do {\n const semi = reader.indexOf(';');\n let genColumn = 0;\n\n for (; reader.pos < semi; reader.pos++) {\n genColumn = decodeInteger(reader, genColumn);\n\n if (!hasMoreVlq(reader, semi)) {\n const last = stack.pop()!;\n last[2] = genLine;\n last[3] = genColumn;\n continue;\n }\n\n const fields = decodeInteger(reader, 0);\n const hasDefinition = fields & 0b0001;\n const hasCallsite = fields & 0b0010;\n const hasScope = fields & 0b0100;\n\n let callsite: CallSite | null = null;\n let bindings: Binding[] = EMPTY;\n let range: GeneratedRange;\n if (hasDefinition) {\n const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);\n definitionScopeIndex = decodeInteger(\n reader,\n definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0,\n );\n\n definitionSourcesIndex = defSourcesIndex;\n range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange;\n } else {\n range = [genLine, genColumn, 0, 0] as GeneratedRange;\n }\n\n range.isScope = !!hasScope;\n\n if (hasCallsite) {\n const prevCsi = callsiteSourcesIndex;\n const prevLine = callsiteLine;\n callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);\n const sameSource = prevCsi === callsiteSourcesIndex;\n callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);\n callsiteColumn = decodeInteger(\n reader,\n sameSource && prevLine === callsiteLine ? callsiteColumn : 0,\n );\n\n callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];\n }\n range.callsite = callsite;\n\n if (hasMoreVlq(reader, semi)) {\n bindings = [];\n do {\n bindingLine = genLine;\n bindingColumn = genColumn;\n const expressionsCount = decodeInteger(reader, 0);\n let expressionRanges: BindingExpressionRange[];\n if (expressionsCount < -1) {\n expressionRanges = [[decodeInteger(reader, 0)]];\n for (let i = -1; i > expressionsCount; i--) {\n const prevBl = bindingLine;\n bindingLine = decodeInteger(reader, bindingLine);\n bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);\n const expression = decodeInteger(reader, 0);\n expressionRanges.push([expression, bindingLine, bindingColumn]);\n }\n } else {\n expressionRanges = [[expressionsCount]];\n }\n bindings.push(expressionRanges);\n } while (hasMoreVlq(reader, semi));\n }\n range.bindings = bindings;\n\n ranges.push(range);\n stack.push(range);\n }\n\n genLine++;\n reader.pos = semi + 1;\n } while (reader.pos < length);\n\n return ranges;\n}\n\nexport function encodeGeneratedRanges(ranges: GeneratedRange[]): string {\n if (ranges.length === 0) return '';\n\n const writer = new StringWriter();\n\n for (let i = 0; i < ranges.length; ) {\n i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);\n }\n\n return writer.flush();\n}\n\nfunction _encodeGeneratedRanges(\n ranges: GeneratedRange[],\n index: number,\n writer: StringWriter,\n state: [\n number, // GenLine\n number, // GenColumn\n number, // DefSourcesIndex\n number, // DefScopesIndex\n number, // CallSourcesIndex\n number, // CallLine\n number, // CallColumn\n ],\n): number {\n const range = ranges[index];\n const {\n 0: startLine,\n 1: startColumn,\n 2: endLine,\n 3: endColumn,\n isScope,\n callsite,\n bindings,\n } = range;\n\n if (state[0] < startLine) {\n catchupLine(writer, state[0], startLine);\n state[0] = startLine;\n state[1] = 0;\n } else if (index > 0) {\n writer.write(comma);\n }\n\n state[1] = encodeInteger(writer, range[1], state[1]);\n\n const fields =\n (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);\n encodeInteger(writer, fields, 0);\n\n if (range.length === 6) {\n const { 4: sourcesIndex, 5: scopesIndex } = range;\n if (sourcesIndex !== state[2]) {\n state[3] = 0;\n }\n state[2] = encodeInteger(writer, sourcesIndex, state[2]);\n state[3] = encodeInteger(writer, scopesIndex, state[3]);\n }\n\n if (callsite) {\n const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!;\n if (sourcesIndex !== state[4]) {\n state[5] = 0;\n state[6] = 0;\n } else if (callLine !== state[5]) {\n state[6] = 0;\n }\n state[4] = encodeInteger(writer, sourcesIndex, state[4]);\n state[5] = encodeInteger(writer, callLine, state[5]);\n state[6] = encodeInteger(writer, callColumn, state[6]);\n }\n\n if (bindings) {\n for (const binding of bindings) {\n if (binding.length > 1) encodeInteger(writer, -binding.length, 0);\n const expression = binding[0][0];\n encodeInteger(writer, expression, 0);\n let bindingStartLine = startLine;\n let bindingStartColumn = startColumn;\n for (let i = 1; i < binding.length; i++) {\n const expRange = binding[i];\n bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine);\n bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn);\n encodeInteger(writer, expRange[0]!, 0);\n }\n }\n }\n\n for (index++; index < ranges.length; ) {\n const next = ranges[index];\n const { 0: l, 1: c } = next;\n if (l > endLine || (l === endLine && c >= endColumn)) {\n break;\n }\n index = _encodeGeneratedRanges(ranges, index, writer, state);\n }\n\n if (state[0] < endLine) {\n catchupLine(writer, state[0], endLine);\n state[0] = endLine;\n state[1] = 0;\n } else {\n writer.write(comma);\n }\n state[1] = encodeInteger(writer, endColumn, state[1]);\n\n return index;\n}\n\nfunction catchupLine(writer: StringWriter, lastLine: number, line: number) {\n do {\n writer.write(semicolon);\n } while (++lastLine < line);\n}\n","import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';\nimport { StringWriter, StringReader } from './strings';\n\nexport {\n decodeOriginalScopes,\n encodeOriginalScopes,\n decodeGeneratedRanges,\n encodeGeneratedRanges,\n} from './scopes';\nexport type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes';\n\nexport type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nexport function decode(mappings: string): SourceMapMappings {\n const { length } = mappings;\n const reader = new StringReader(mappings);\n const decoded: SourceMapMappings = [];\n let genColumn = 0;\n let sourcesIndex = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let namesIndex = 0;\n\n do {\n const semi = reader.indexOf(';');\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n genColumn = 0;\n\n while (reader.pos < semi) {\n let seg: SourceMapSegment;\n\n genColumn = decodeInteger(reader, genColumn);\n if (genColumn < lastCol) sorted = false;\n lastCol = genColumn;\n\n if (hasMoreVlq(reader, semi)) {\n sourcesIndex = decodeInteger(reader, sourcesIndex);\n sourceLine = decodeInteger(reader, sourceLine);\n sourceColumn = decodeInteger(reader, sourceColumn);\n\n if (hasMoreVlq(reader, semi)) {\n namesIndex = decodeInteger(reader, namesIndex);\n seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];\n } else {\n seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];\n }\n } else {\n seg = [genColumn];\n }\n\n line.push(seg);\n reader.pos++;\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n reader.pos = semi + 1;\n } while (reader.pos <= length);\n\n return decoded;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const writer = new StringWriter();\n let sourcesIndex = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let namesIndex = 0;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) writer.write(semicolon);\n if (line.length === 0) continue;\n\n let genColumn = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n if (j > 0) writer.write(comma);\n\n genColumn = encodeInteger(writer, segment[0], genColumn);\n\n if (segment.length === 1) continue;\n sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);\n sourceLine = encodeInteger(writer, segment[2], sourceLine);\n sourceColumn = encodeInteger(writer, segment[3], sourceColumn);\n\n if (segment.length === 4) continue;\n namesIndex = encodeInteger(writer, segment[4], namesIndex);\n }\n }\n\n return writer.flush();\n}\n"],"names":[],"mappings":"AAEO,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAE3C,MAAM,KAAK,GAAG,kEAAkE,CAAC;AACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACjB,SAAS,CAAC,C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AAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,GAAG,CAAC;YAAE,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACnC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QAEhC,IAAI,SAAS,GAAG,CAAC,CAAC;QAElB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACpC,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YACxB,IAAI,CAAC,GAAG,CAAC;gBAAE,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAE/B,SAAS,GAAG,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;YAEzD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YACnC,YAAY,GAAG,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC;YAC/D,UAAU,GAAG,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;YAC3D,YAAY,GAAG,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC;YAE/D,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YACnC,UAAU,GAAG,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;SAC5D;KACF;IAED,OAAO,MAAM,CAAC,KAAK,EAAE,CAAC;AACxB;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 00000000..93caf176 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,439 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sourcemapCodec = {})); +})(this, (function (exports) { 'use strict'; + + const comma = ','.charCodeAt(0); + const semicolon = ';'.charCodeAt(0); + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const intToChar = new Uint8Array(64); // 64 possible chars. + const charToInt = new Uint8Array(128); // z is 122 in ASCII + for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; + } + function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + return relative + value; + } + function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? (-delta << 1) | 1 : delta << 1; + do { + let clamped = delta & 0b011111; + delta >>>= 5; + if (delta > 0) + clamped |= 0b100000; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; + } + function hasMoreVlq(reader, max) { + if (reader.pos >= max) + return false; + return reader.peek() !== comma; + } + + const bufLength = 1024 * 16; + // Provide a fallback for older environments. + const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + class StringWriter { + constructor() { + this.pos = 0; + this.out = ''; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } + } + class StringReader { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } + } + + const EMPTY = []; + function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 0b0001; + const scope = (hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]); + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; + } + function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length;) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); + } + function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) + writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 0b0001 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) + encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length;) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; + } + function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(';'); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 0b0001; + const hasCallsite = fields & 0b0010; + const hasScope = fields & 0b0100; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger(reader, definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } + else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger(reader, sameSource && prevLine === callsiteLine ? callsiteColumn : 0); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } + else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; + } + function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) + return ''; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length;) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); + } + function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, isScope, callsite, bindings, } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } + else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } + else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) + encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length;) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } + else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; + } + function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); + } + + function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(';'); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) + sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } + else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } + else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) + sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; + } + function sort(line) { + line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[0] - b[0]; + } + function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) + writer.write(semicolon); + if (line.length === 0) + continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) + writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) + continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) + continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); + } + + exports.decode = decode; + exports.decodeGeneratedRanges = decodeGeneratedRanges; + exports.decodeOriginalScopes = decodeOriginalScopes; + exports.encode = encode; + exports.encodeGeneratedRanges = encodeGeneratedRanges; + exports.encodeOriginalScopes = encodeOriginalScopes; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 00000000..65b36746 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.umd.js","sources":["../src/vlq.ts","../src/strings.ts","../src/scopes.ts","../src/sourcemap-codec.ts"],"sourcesContent":["import type { StringReader, StringWriter } from './strings';\n\nexport const comma = ','.charCodeAt(0);\nexport const semicolon = ';'.charCodeAt(0);\n\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\nexport function decodeInteger(reader: StringReader, relative: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = reader.next();\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n return relative + value;\n}\n\nexport function encodeInteger(builder: StringWriter, num: number, relative: number): number {\n let delta = num - relative;\n\n delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;\n do {\n let clamped = delta & 0b011111;\n delta >>>= 5;\n if (delta > 0) clamped |= 0b100000;\n builder.write(intToChar[clamped]);\n } while (delta > 0);\n\n return num;\n}\n\nexport function hasMoreVlq(reader: StringReader, max: number) {\n if (reader.pos >= max) return false;\n return reader.peek() !== comma;\n}\n","const bufLength = 1024 * 16;\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array): string {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array): string {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport class StringWriter {\n pos = 0;\n private out = '';\n private buffer = new Uint8Array(bufLength);\n\n write(v: number): void {\n const { buffer } = this;\n buffer[this.pos++] = v;\n if (this.pos === bufLength) {\n this.out += td.decode(buffer);\n this.pos = 0;\n }\n }\n\n flush(): string {\n const { buffer, out, pos } = this;\n return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;\n }\n}\n\nexport class StringReader {\n pos = 0;\n private declare buffer: string;\n\n constructor(buffer: string) {\n this.buffer = buffer;\n }\n\n next(): number {\n return this.buffer.charCodeAt(this.pos++);\n }\n\n peek(): number {\n return this.buffer.charCodeAt(this.pos);\n }\n\n indexOf(char: string): number {\n const { buffer, pos } = this;\n const idx = buffer.indexOf(char, pos);\n return idx === -1 ? buffer.length : idx;\n }\n}\n","import { StringReader, StringWriter } from './strings';\nimport { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';\n\nconst EMPTY: any[] = [];\n\ntype Line = number;\ntype Column = number;\ntype Kind = number;\ntype Name = number;\ntype Var = number;\ntype SourcesIndex = number;\ntype ScopesIndex = number;\n\ntype Mix = (A & O) | (B & O);\n\nexport type OriginalScope = Mix<\n [Line, Column, Line, Column, Kind],\n [Line, Column, Line, Column, Kind, Name],\n { vars: Var[] }\n>;\n\nexport type GeneratedRange = Mix<\n [Line, Column, Line, Column],\n [Line, Column, Line, Column, SourcesIndex, ScopesIndex],\n {\n callsite: CallSite | null;\n bindings: Binding[];\n isScope: boolean;\n }\n>;\nexport type CallSite = [SourcesIndex, Line, Column];\ntype Binding = BindingExpressionRange[];\nexport type BindingExpressionRange = [Name] | [Name, Line, Column];\n\nexport function decodeOriginalScopes(input: string): OriginalScope[] {\n const { length } = input;\n const reader = new StringReader(input);\n const scopes: OriginalScope[] = [];\n const stack: OriginalScope[] = [];\n let line = 0;\n\n for (; reader.pos < length; reader.pos++) {\n line = decodeInteger(reader, line);\n const column = decodeInteger(reader, 0);\n\n if (!hasMoreVlq(reader, length)) {\n const last = stack.pop()!;\n last[2] = line;\n last[3] = column;\n continue;\n }\n\n const kind = decodeInteger(reader, 0);\n const fields = decodeInteger(reader, 0);\n const hasName = fields & 0b0001;\n\n const scope: OriginalScope = (\n hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]\n ) as OriginalScope;\n\n let vars: Var[] = EMPTY;\n if (hasMoreVlq(reader, length)) {\n vars = [];\n do {\n const varsIndex = decodeInteger(reader, 0);\n vars.push(varsIndex);\n } while (hasMoreVlq(reader, length));\n }\n scope.vars = vars;\n\n scopes.push(scope);\n stack.push(scope);\n }\n\n return scopes;\n}\n\nexport function encodeOriginalScopes(scopes: OriginalScope[]): string {\n const writer = new StringWriter();\n\n for (let i = 0; i < scopes.length; ) {\n i = _encodeOriginalScopes(scopes, i, writer, [0]);\n }\n\n return writer.flush();\n}\n\nfunction _encodeOriginalScopes(\n scopes: OriginalScope[],\n index: number,\n writer: StringWriter,\n state: [\n number, // GenColumn\n ],\n): number {\n const scope = scopes[index];\n const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;\n\n if (index > 0) writer.write(comma);\n\n state[0] = encodeInteger(writer, startLine, state[0]);\n encodeInteger(writer, startColumn, 0);\n encodeInteger(writer, kind, 0);\n\n const fields = scope.length === 6 ? 0b0001 : 0;\n encodeInteger(writer, fields, 0);\n if (scope.length === 6) encodeInteger(writer, scope[5], 0);\n\n for (const v of vars) {\n encodeInteger(writer, v, 0);\n }\n\n for (index++; index < scopes.length; ) {\n const next = scopes[index];\n const { 0: l, 1: c } = next;\n if (l > endLine || (l === endLine && c >= endColumn)) {\n break;\n }\n index = _encodeOriginalScopes(scopes, index, writer, state);\n }\n\n writer.write(comma);\n state[0] = encodeInteger(writer, endLine, state[0]);\n encodeInteger(writer, endColumn, 0);\n\n return index;\n}\n\nexport function decodeGeneratedRanges(input: string): GeneratedRange[] {\n const { length } = input;\n const reader = new StringReader(input);\n const ranges: GeneratedRange[] = [];\n const stack: GeneratedRange[] = [];\n\n let genLine = 0;\n let definitionSourcesIndex = 0;\n let definitionScopeIndex = 0;\n let callsiteSourcesIndex = 0;\n let callsiteLine = 0;\n let callsiteColumn = 0;\n let bindingLine = 0;\n let bindingColumn = 0;\n\n do {\n const semi = reader.indexOf(';');\n let genColumn = 0;\n\n for (; reader.pos < semi; reader.pos++) {\n genColumn = decodeInteger(reader, genColumn);\n\n if (!hasMoreVlq(reader, semi)) {\n const last = stack.pop()!;\n last[2] = genLine;\n last[3] = genColumn;\n continue;\n }\n\n const fields = decodeInteger(reader, 0);\n const hasDefinition = fields & 0b0001;\n const hasCallsite = fields & 0b0010;\n const hasScope = fields & 0b0100;\n\n let callsite: CallSite | null = null;\n let bindings: Binding[] = EMPTY;\n let range: GeneratedRange;\n if (hasDefinition) {\n const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);\n definitionScopeIndex = decodeInteger(\n reader,\n definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0,\n );\n\n definitionSourcesIndex = defSourcesIndex;\n range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange;\n } else {\n range = [genLine, genColumn, 0, 0] as GeneratedRange;\n }\n\n range.isScope = !!hasScope;\n\n if (hasCallsite) {\n const prevCsi = callsiteSourcesIndex;\n const prevLine = callsiteLine;\n callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);\n const sameSource = prevCsi === callsiteSourcesIndex;\n callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);\n callsiteColumn = decodeInteger(\n reader,\n sameSource && prevLine === callsiteLine ? callsiteColumn : 0,\n );\n\n callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];\n }\n range.callsite = callsite;\n\n if (hasMoreVlq(reader, semi)) {\n bindings = [];\n do {\n bindingLine = genLine;\n bindingColumn = genColumn;\n const expressionsCount = decodeInteger(reader, 0);\n let expressionRanges: BindingExpressionRange[];\n if (expressionsCount < -1) {\n expressionRanges = [[decodeInteger(reader, 0)]];\n for (let i = -1; i > expressionsCount; i--) {\n const prevBl = bindingLine;\n bindingLine = decodeInteger(reader, bindingLine);\n bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);\n const expression = decodeInteger(reader, 0);\n expressionRanges.push([expression, bindingLine, bindingColumn]);\n }\n } else {\n expressionRanges = [[expressionsCount]];\n }\n bindings.push(expressionRanges);\n } while (hasMoreVlq(reader, semi));\n }\n range.bindings = bindings;\n\n ranges.push(range);\n stack.push(range);\n }\n\n genLine++;\n reader.pos = semi + 1;\n } while (reader.pos < length);\n\n return ranges;\n}\n\nexport function encodeGeneratedRanges(ranges: GeneratedRange[]): string {\n if (ranges.length === 0) return '';\n\n const writer = new StringWriter();\n\n for (let i = 0; i < ranges.length; ) {\n i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);\n }\n\n return writer.flush();\n}\n\nfunction _encodeGeneratedRanges(\n ranges: GeneratedRange[],\n index: number,\n writer: StringWriter,\n state: [\n number, // GenLine\n number, // GenColumn\n number, // DefSourcesIndex\n number, // DefScopesIndex\n number, // CallSourcesIndex\n number, // CallLine\n number, // CallColumn\n ],\n): number {\n const range = ranges[index];\n const {\n 0: startLine,\n 1: startColumn,\n 2: endLine,\n 3: endColumn,\n isScope,\n callsite,\n bindings,\n } = range;\n\n if (state[0] < startLine) {\n catchupLine(writer, state[0], startLine);\n state[0] = startLine;\n state[1] = 0;\n } else if (index > 0) {\n writer.write(comma);\n }\n\n state[1] = encodeInteger(writer, range[1], state[1]);\n\n const fields =\n (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);\n encodeInteger(writer, fields, 0);\n\n if (range.length === 6) {\n const { 4: sourcesIndex, 5: scopesIndex } = range;\n if (sourcesIndex !== state[2]) {\n state[3] = 0;\n }\n state[2] = encodeInteger(writer, sourcesIndex, state[2]);\n state[3] = encodeInteger(writer, scopesIndex, state[3]);\n }\n\n if (callsite) {\n const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!;\n if (sourcesIndex !== state[4]) {\n state[5] = 0;\n state[6] = 0;\n } else if (callLine !== state[5]) {\n state[6] = 0;\n }\n state[4] = encodeInteger(writer, sourcesIndex, state[4]);\n state[5] = encodeInteger(writer, callLine, state[5]);\n state[6] = encodeInteger(writer, callColumn, state[6]);\n }\n\n if (bindings) {\n for (const binding of bindings) {\n if (binding.length > 1) encodeInteger(writer, -binding.length, 0);\n const expression = binding[0][0];\n encodeInteger(writer, expression, 0);\n let bindingStartLine = startLine;\n let bindingStartColumn = startColumn;\n for (let i = 1; i < binding.length; i++) {\n const expRange = binding[i];\n bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine);\n bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn);\n encodeInteger(writer, expRange[0]!, 0);\n }\n }\n }\n\n for (index++; index < ranges.length; ) {\n const next = ranges[index];\n const { 0: l, 1: c } = next;\n if (l > endLine || (l === endLine && c >= endColumn)) {\n break;\n }\n index = _encodeGeneratedRanges(ranges, index, writer, state);\n }\n\n if (state[0] < endLine) {\n catchupLine(writer, state[0], endLine);\n state[0] = endLine;\n state[1] = 0;\n } else {\n writer.write(comma);\n }\n state[1] = encodeInteger(writer, endColumn, state[1]);\n\n return index;\n}\n\nfunction catchupLine(writer: StringWriter, lastLine: number, line: number) {\n do {\n writer.write(semicolon);\n } while (++lastLine < line);\n}\n","import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';\nimport { StringWriter, StringReader } from './strings';\n\nexport {\n decodeOriginalScopes,\n encodeOriginalScopes,\n decodeGeneratedRanges,\n encodeGeneratedRanges,\n} from './scopes';\nexport type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes';\n\nexport type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nexport function decode(mappings: string): SourceMapMappings {\n const { length } = mappings;\n const reader = new StringReader(mappings);\n const decoded: SourceMapMappings = [];\n let genColumn = 0;\n let sourcesIndex = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let namesIndex = 0;\n\n do {\n const semi = reader.indexOf(';');\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n genColumn = 0;\n\n while (reader.pos < semi) {\n let seg: SourceMapSegment;\n\n genColumn = decodeInteger(reader, genColumn);\n if (genColumn < lastCol) sorted = false;\n lastCol = genColumn;\n\n if (hasMoreVlq(reader, semi)) {\n sourcesIndex = decodeInteger(reader, sourcesIndex);\n sourceLine = decodeInteger(reader, sourceLine);\n sourceColumn = decodeInteger(reader, sourceColumn);\n\n if (hasMoreVlq(reader, semi)) {\n namesIndex = decodeInteger(reader, namesIndex);\n seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];\n } else {\n seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];\n }\n } else {\n seg = [genColumn];\n }\n\n line.push(seg);\n reader.pos++;\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n reader.pos = semi + 1;\n } while (reader.pos <= length);\n\n return decoded;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const writer = new StringWriter();\n let sourcesIndex = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let namesIndex = 0;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) writer.write(semicolon);\n if (line.length === 0) continue;\n\n let genColumn = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n if (j > 0) writer.write(comma);\n\n genColumn = encodeInteger(writer, segment[0], genColumn);\n\n if (segment.length === 1) continue;\n sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);\n sourceLine = encodeInteger(writer, segment[2], sourceLine);\n sourceColumn = encodeInteger(writer, segment[3], sourceColumn);\n\n if (segment.length === 4) continue;\n namesIndex = encodeInteger(writer, segment[4], namesIndex);\n }\n }\n\n return writer.flush();\n}\n"],"names":[],"mappings":";;;;;;IAEO,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;I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AAU,GAAG,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;gBAC3D,YAAY,GAAG,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC;gBAE/D,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;oBAAE,SAAS;gBACnC,UAAU,GAAG,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;aAC5D;SACF;QAED,OAAO,MAAM,CAAC,KAAK,EAAE,CAAC;IACxB;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/types/scopes.d.ts b/node_modules/@jridgewell/sourcemap-codec/dist/types/scopes.d.ts new file mode 100644 index 00000000..d156fabd --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/types/scopes.d.ts @@ -0,0 +1,49 @@ +declare type Line = number; +declare type Column = number; +declare type Kind = number; +declare type Name = number; +declare type Var = number; +declare type SourcesIndex = number; +declare type ScopesIndex = number; +declare type Mix = (A & O) | (B & O); +export declare type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export declare type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export declare type CallSite = [SourcesIndex, Line, Column]; +declare type Binding = BindingExpressionRange[]; +export declare type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 00000000..336e658f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,8 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes'; +export declare type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export declare type SourceMapLine = SourceMapSegment[]; +export declare type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/types/strings.d.ts b/node_modules/@jridgewell/sourcemap-codec/dist/types/strings.d.ts new file mode 100644 index 00000000..78bd88eb --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/types/strings.d.ts @@ -0,0 +1,15 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/types/vlq.d.ts b/node_modules/@jridgewell/sourcemap-codec/dist/types/vlq.d.ts new file mode 100644 index 00000000..450ee572 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/types/vlq.d.ts @@ -0,0 +1,6 @@ +import type { StringReader, StringWriter } from './strings'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; diff --git a/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 00000000..7168efca --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,75 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.5.0", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "dist/types/sourcemap-codec.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": [ + { + "types": "./dist/types/sourcemap-codec.d.ts", + "browser": "./dist/sourcemap-codec.umd.js", + "require": "./dist/sourcemap-codec.umd.js", + "import": "./dist/sourcemap-codec.mjs" + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemap-codec.git" + }, + "author": "Rich Harris", + "license": "MIT", + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/mocha": "10.0.6", + "@types/node": "17.0.15", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.64.0", + "source-map": "0.6.1", + "source-map-js": "1.0.2", + "sourcemap-codec": "1.4.8", + "tsx": "4.7.1", + "typescript": "4.5.4" + } +} diff --git a/node_modules/@jridgewell/trace-mapping/LICENSE b/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 00000000..37bb488f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/trace-mapping/README.md b/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 00000000..969558d7 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,257 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { + TraceMap, + originalPositionFor, + generatedPositionFor, + sourceContentFor, + isIgnored, +} from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + sourcesContent: ['content of input.js'], + names: ['foo'], + mappings: 'KAyCIA', + ignoreList: [], +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const content = sourceContentFor(tracer, traced.source); +assert.strictEqual(content, 'content for input.js'); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); + +const ignored = isIgnored(tracer, 'input.js'); +assert.equal(ignored, false); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map - 45120 segments + +Memory Usage: +trace-mapping decoded 562400 bytes +trace-mapping encoded 5706544 bytes +source-map-js 10717664 bytes +source-map-0.6.1 17446384 bytes +source-map-0.8.0 9701757 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 180 ops/sec ±0.34% (85 runs sampled) +trace-mapping: encoded JSON input x 364 ops/sec ±1.77% (89 runs sampled) +trace-mapping: decoded Object input x 3,116 ops/sec ±0.50% (96 runs sampled) +trace-mapping: encoded Object input x 410 ops/sec ±2.62% (85 runs sampled) +source-map-js: encoded Object input x 84.23 ops/sec ±0.91% (73 runs sampled) +source-map-0.6.1: encoded Object input x 37.21 ops/sec ±2.08% (51 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 3,952,212 ops/sec ±0.17% (98 runs sampled) +trace-mapping: encoded originalPositionFor x 3,487,468 ops/sec ±1.58% (90 runs sampled) +source-map-js: encoded originalPositionFor x 827,730 ops/sec ±0.78% (97 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 748,991 ops/sec ±0.53% (94 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 2,532,894 ops/sec ±0.57% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +babel.min.js.map - 347793 segments + +Memory Usage: +trace-mapping decoded 89832 bytes +trace-mapping encoded 35474640 bytes +source-map-js 51257176 bytes +source-map-0.6.1 63515664 bytes +source-map-0.8.0 42933752 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 15.41 ops/sec ±8.65% (34 runs sampled) +trace-mapping: encoded JSON input x 28.20 ops/sec ±12.87% (42 runs sampled) +trace-mapping: decoded Object input x 964 ops/sec ±0.36% (99 runs sampled) +trace-mapping: encoded Object input x 31.77 ops/sec ±13.79% (45 runs sampled) +source-map-js: encoded Object input x 6.45 ops/sec ±5.16% (21 runs sampled) +source-map-0.6.1: encoded Object input x 4.07 ops/sec ±5.24% (15 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 7,183,038 ops/sec ±0.58% (95 runs sampled) +trace-mapping: encoded originalPositionFor x 5,192,185 ops/sec ±0.41% (100 runs sampled) +source-map-js: encoded originalPositionFor x 4,259,489 ops/sec ±0.79% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 3,742,629 ops/sec ±0.71% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 6,270,211 ops/sec ±0.64% (94 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +preact.js.map - 1992 segments + +Memory Usage: +trace-mapping decoded 37128 bytes +trace-mapping encoded 247280 bytes +source-map-js 1143536 bytes +source-map-0.6.1 1290992 bytes +source-map-0.8.0 96544 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 3,483 ops/sec ±0.30% (98 runs sampled) +trace-mapping: encoded JSON input x 6,092 ops/sec ±0.18% (97 runs sampled) +trace-mapping: decoded Object input x 249,076 ops/sec ±0.24% (98 runs sampled) +trace-mapping: encoded Object input x 14,555 ops/sec ±0.48% (100 runs sampled) +source-map-js: encoded Object input x 2,447 ops/sec ±0.36% (99 runs sampled) +source-map-0.6.1: encoded Object input x 1,201 ops/sec ±0.57% (96 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 7,620,192 ops/sec ±0.09% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 6,872,554 ops/sec ±0.30% (97 runs sampled) +source-map-js: encoded originalPositionFor x 2,489,570 ops/sec ±0.35% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 1,698,633 ops/sec ±0.28% (98 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 4,015,644 ops/sec ±0.22% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +react.js.map - 5726 segments + +Memory Usage: +trace-mapping decoded 16176 bytes +trace-mapping encoded 681552 bytes +source-map-js 2418352 bytes +source-map-0.6.1 2443672 bytes +source-map-0.8.0 111768 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1,720 ops/sec ±0.34% (98 runs sampled) +trace-mapping: encoded JSON input x 4,406 ops/sec ±0.35% (100 runs sampled) +trace-mapping: decoded Object input x 92,122 ops/sec ±0.10% (99 runs sampled) +trace-mapping: encoded Object input x 5,385 ops/sec ±0.37% (99 runs sampled) +source-map-js: encoded Object input x 794 ops/sec ±0.40% (98 runs sampled) +source-map-0.6.1: encoded Object input x 416 ops/sec ±0.54% (91 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 32,759,519 ops/sec ±0.33% (100 runs sampled) +trace-mapping: encoded originalPositionFor x 31,116,306 ops/sec ±0.33% (97 runs sampled) +source-map-js: encoded originalPositionFor x 17,458,435 ops/sec ±0.44% (97 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 12,687,097 ops/sec ±0.43% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 23,538,275 ops/sec ±0.38% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 00000000..8238e0ae --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,580 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; +import resolveUri from '@jridgewell/resolve-uri'; + +function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; +const REV_GENERATED_LINE = 1; +const REV_GENERATED_COLUMN = 2; + +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +let found = false; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + let index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + memo.lastIndex = ++index; + insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like +// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. +// Numeric properties on objects are magically sorted in ascending order by the engine regardless of +// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending +// order when iterating with for-in. +function buildNullArray() { + return { __proto__: null }; +} + +const AnyMap = function (map, mapUrl) { + const parsed = parse(map); + if (!('sections' in parsed)) { + return new TraceMap(parsed, mapUrl); + } + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const ignoreList = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, ignoreList, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList, + }; + return presortedDecodedMap(joined); +}; +function parse(map) { + return typeof map === 'string' ? JSON.parse(map) : map; +} +function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } +} +function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const parsed = parse(input); + if ('sections' in parsed) + return recurse(...arguments); + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + if (ignores) + for (let i = 0; i < ignores.length; i++) + ignoreList.push(ignores[i] + sourcesOffset); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); +} +function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; +} + +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || undefined; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +/** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ +function cast(map) { + return map; +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +function encodedMappings(map) { + var _a; + var _b; + return ((_a = (_b = cast(map))._encoded) !== null && _a !== void 0 ? _a : (_b._encoded = encode(cast(map)._decoded))); +} +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +function decodedMappings(map) { + var _a; + return ((_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded))); +} +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +function traceSegment(map, line, column) { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; +} +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); +} +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +function generatedPositionFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); +} +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +function allGeneratedPositionsFor(map, needle) { + const { source, line, column, bias } = needle; + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); +} +/** + * Iterates each mapping in generated position order. + */ +function eachMapping(map, cb) { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } +} +function sourceIndex(map, source) { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index; +} +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +function sourceContentFor(map, source) { + const { sourcesContent } = map; + if (sourcesContent == null) + return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; +} +/** + * Determines if the source is marked to ignore by the source map. + */ +function isIgnored(map, source) { + const { ignoreList } = map; + if (ignoreList == null) + return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); +} +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +function presortedDecodedMap(map, mapUrl) { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; +} +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +function decodedMap(map) { + return clone(map, decodedMappings(map)); +} +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +function encodedMap(map) { + return clone(map, encodedMappings(map)); +} +function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || map.x_google_ignoreList, + }; +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function GMapping(line, column) { + return { line, column }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; +} +function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} +function generatedPosition(map, source, line, column, bias, all) { + var _a; + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = ((_a = cast(map))._bySources || (_a._bySources = buildBySources(decodedMappings(map), (cast(map)._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = cast(map)._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); +} + +export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, allGeneratedPositionsFor, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, isIgnored, originalPositionFor, presortedDecodedMap, sourceContentFor, traceSegment }; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 00000000..016e4ee4 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.mjs","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n let index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n memo.lastIndex = ++index;\n insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n DecodedSourceMap,\n DecodedSourceMapXInput,\n EncodedSourceMapXInput,\n SectionedSourceMapXInput,\n SectionedSourceMapInput,\n SectionXInput,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed = parse(map);\n\n if (!('sections' in parsed)) {\n return new TraceMap(parsed as DecodedSourceMapXInput | EncodedSourceMapXInput, mapUrl);\n }\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n const ignoreList: number[] = [];\n\n recurse(\n parsed,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n ignoreList,\n 0,\n 0,\n Infinity,\n Infinity,\n );\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n ignoreList,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction parse(map: T): Exclude {\n return typeof map === 'string' ? JSON.parse(map) : map;\n}\n\nfunction recurse(\n input: SectionedSourceMapXInput,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n ignoreList: number[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n ignoreList,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: SectionXInput['map'],\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n ignoreList: number[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const parsed = parse(input);\n if ('sections' in parsed) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(parsed, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n XInput,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type {\n SourceMap,\n DecodedSourceMap,\n EncodedSourceMap,\n Section,\n SectionedSourceMap,\n SourceMapV3,\n Bias,\n EachMapping,\n GeneratedMapping,\n InvalidGeneratedMapping,\n InvalidOriginalMapping,\n Needle,\n OriginalMapping,\n OriginalMapping as Mapping,\n SectionedSourceMapInput,\n SourceMapInput,\n SourceNeedle,\n XInput,\n EncodedSourceMapXInput,\n DecodedSourceMapXInput,\n SectionedSourceMapXInput,\n SectionXInput,\n} from './types';\n\ninterface PublicMap {\n _encoded: TraceMap['_encoded'];\n _decoded: TraceMap['_decoded'];\n _decodedMemo: TraceMap['_decodedMemo'];\n _bySources: TraceMap['_bySources'];\n _bySourceMemos: TraceMap['_bySourceMemos'];\n}\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n declare ignoreList: SourceMapV3['ignoreList'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names || [];\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n this.ignoreList = parsed.ignoreList || (parsed as XInput).x_google_ignoreList || undefined;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n}\n\n/**\n * Typescript doesn't allow friend access to private fields, so this just casts the map into a type\n * with public access modifiers.\n */\nfunction cast(map: unknown): PublicMap {\n return map as any;\n}\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport function encodedMappings(map: TraceMap): EncodedSourceMap['mappings'] {\n return (cast(map)._encoded ??= encode(cast(map)._decoded!));\n}\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport function decodedMappings(map: TraceMap): Readonly {\n return (cast(map)._decoded ||= decode(cast(map)._encoded!));\n}\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport function traceSegment(\n map: TraceMap,\n line: number,\n column: number,\n): Readonly | null {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n cast(map)._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n}\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport function originalPositionFor(\n map: TraceMap,\n needle: Needle,\n): OriginalMapping | InvalidOriginalMapping {\n let { line, column, bias } = needle;\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n cast(map)._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n}\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport function generatedPositionFor(\n map: TraceMap,\n needle: SourceNeedle,\n): GeneratedMapping | InvalidGeneratedMapping {\n const { source, line, column, bias } = needle;\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n}\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[] {\n const { source, line, column, bias } = needle;\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n}\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n}\n\nfunction sourceIndex(map: TraceMap, source: string): number {\n const { sources, resolvedSources } = map;\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n return index;\n}\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport function sourceContentFor(map: TraceMap, source: string): string | null {\n const { sourcesContent } = map;\n if (sourcesContent == null) return null;\n const index = sourceIndex(map, source);\n return index === -1 ? null : sourcesContent[index];\n}\n\n/**\n * Determines if the source is marked to ignore by the source map.\n */\nexport function isIgnored(map: TraceMap, source: string): boolean {\n const { ignoreList } = map;\n if (ignoreList == null) return false;\n const index = sourceIndex(map, source);\n return index === -1 ? false : ignoreList.includes(index);\n}\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n cast(tracer)._decoded = map.mappings;\n return tracer;\n}\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function decodedMap(\n map: TraceMap,\n): Omit & { mappings: readonly SourceMapSegment[][] } {\n return clone(map, decodedMappings(map));\n}\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function encodedMap(map: TraceMap): EncodedSourceMap {\n return clone(map, encodedMappings(map));\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n ignoreList: map.ignoreList || (map as XInput).x_google_ignoreList,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n): GeneratedMapping | InvalidGeneratedMapping;\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n): GeneratedMapping[];\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (cast(map)._bySources ||= buildBySources(\n decodedMappings(map),\n (cast(map)._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = cast(map)._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n}\n"],"names":["bsFound"],"mappings":";;;AAEc,SAAU,OAAO,CAAC,KAAa,EAAE,IAAwB,EAAA;;;;IAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,IAAI,IAAI,GAAG,CAAC;AAE7C,IAAA,OAAO,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACjC;;ACTA;;AAEG;AACqB,SAAA,aAAa,CAAC,IAA+B,EAAA;AACnE,IAAA,IAAI,CAAC,IAAI;AAAE,QAAA,OAAO,EAAE,CAAC;IACrB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;AAClC;;ACQO,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAA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CAAC;AAE5E,IAAA,MAAM,KAAK,GAAG,oBAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IACvE,IAAI,KAAK,KAAK,CAAC,CAAC;AAAE,QAAA,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAE9C,IAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;AAChC,IAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC;AAClF;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 00000000..3be0f36e --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,600 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/sourcemap-codec'), require('@jridgewell/resolve-uri')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/sourcemap-codec', '@jridgewell/resolve-uri'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.traceMapping = {}, global.sourcemapCodec, global.resolveURI)); +})(this, (function (exports, sourcemapCodec, resolveUri) { 'use strict'; + + function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); + } + + /** + * Removes everything after the last "/", but leaves the slash. + */ + function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + const REV_GENERATED_LINE = 1; + const REV_GENERATED_COLUMN = 2; + + function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; + } + function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; + } + function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; + } + function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; + } + + let found = false; + /** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ + function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; + } + function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; + } + /** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ + function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); + } + + // Rebuilds the original source files, with mappings that are ordered by source line/column instead + // of generated line/column. + function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + let index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + memo.lastIndex = ++index; + insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like + // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. + // Numeric properties on objects are magically sorted in ascending order by the engine regardless of + // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending + // order when iterating with for-in. + function buildNullArray() { + return { __proto__: null }; + } + + const AnyMap = function (map, mapUrl) { + const parsed = parse(map); + if (!('sections' in parsed)) { + return new TraceMap(parsed, mapUrl); + } + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const ignoreList = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, ignoreList, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList, + }; + return presortedDecodedMap(joined); + }; + function parse(map) { + return typeof map === 'string' ? JSON.parse(map) : map; + } + function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } + } + function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const parsed = parse(input); + if ('sections' in parsed) + return recurse(...arguments); + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + if (ignores) + for (let i = 0; i < ignores.length; i++) + ignoreList.push(ignores[i] + sourcesOffset); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } + } + function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); + } + function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; + } + + const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; + const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + const LEAST_UPPER_BOUND = -1; + const GREATEST_LOWER_BOUND = 1; + class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || undefined; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } + } + /** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ + function cast(map) { + return map; + } + /** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ + function encodedMappings(map) { + var _a; + var _b; + return ((_a = (_b = cast(map))._encoded) !== null && _a !== void 0 ? _a : (_b._encoded = sourcemapCodec.encode(cast(map)._decoded))); + } + /** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ + function decodedMappings(map) { + var _a; + return ((_a = cast(map))._decoded || (_a._decoded = sourcemapCodec.decode(cast(map)._encoded))); + } + /** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ + function traceSegment(map, line, column) { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + } + /** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ + function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); + } + /** + * Finds the generated line/column position of the provided source/line/column source position. + */ + function generatedPositionFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); + } + /** + * Finds all generated line/column positions of the provided source/line/column source position. + */ + function allGeneratedPositionsFor(map, needle) { + const { source, line, column, bias } = needle; + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); + } + /** + * Iterates each mapping in generated position order. + */ + function eachMapping(map, cb) { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + } + function sourceIndex(map, source) { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index; + } + /** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ + function sourceContentFor(map, source) { + const { sourcesContent } = map; + if (sourcesContent == null) + return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; + } + /** + * Determines if the source is marked to ignore by the source map. + */ + function isIgnored(map, source) { + const { ignoreList } = map; + if (ignoreList == null) + return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); + } + /** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ + function presortedDecodedMap(map, mapUrl) { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; + } + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + function decodedMap(map) { + return clone(map, decodedMappings(map)); + } + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + function encodedMap(map) { + return clone(map, encodedMappings(map)); + } + function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || map.x_google_ignoreList, + }; + } + function OMapping(source, line, column, name) { + return { source, line, column, name }; + } + function GMapping(line, column) { + return { line, column }; + } + function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; + } + function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; + } + function generatedPosition(map, source, line, column, bias, all) { + var _a; + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = ((_a = cast(map))._bySources || (_a._bySources = buildBySources(decodedMappings(map), (cast(map)._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = cast(map)._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); + } + + exports.AnyMap = AnyMap; + exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND; + exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND; + exports.TraceMap = TraceMap; + exports.allGeneratedPositionsFor = allGeneratedPositionsFor; + exports.decodedMap = decodedMap; + exports.decodedMappings = decodedMappings; + exports.eachMapping = eachMapping; + exports.encodedMap = encodedMap; + exports.encodedMappings = encodedMappings; + exports.generatedPositionFor = generatedPositionFor; + exports.isIgnored = isIgnored; + exports.originalPositionFor = originalPositionFor; + exports.presortedDecodedMap = presortedDecodedMap; + exports.sourceContentFor = sourceContentFor; + exports.traceSegment = traceSegment; + +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 00000000..c6716eaf --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.umd.js","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n let index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n memo.lastIndex = ++index;\n insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n DecodedSourceMap,\n DecodedSourceMapXInput,\n EncodedSourceMapXInput,\n SectionedSourceMapXInput,\n SectionedSourceMapInput,\n SectionXInput,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed = parse(map);\n\n if (!('sections' in parsed)) {\n return new TraceMap(parsed as DecodedSourceMapXInput | EncodedSourceMapXInput, mapUrl);\n }\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n const ignoreList: number[] = [];\n\n recurse(\n parsed,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n ignoreList,\n 0,\n 0,\n Infinity,\n Infinity,\n );\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n ignoreList,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction parse(map: T): Exclude {\n return typeof map === 'string' ? JSON.parse(map) : map;\n}\n\nfunction recurse(\n input: SectionedSourceMapXInput,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n ignoreList: number[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n ignoreList,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: SectionXInput['map'],\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n ignoreList: number[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const parsed = parse(input);\n if ('sections' in parsed) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(parsed, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n XInput,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type {\n SourceMap,\n DecodedSourceMap,\n EncodedSourceMap,\n Section,\n SectionedSourceMap,\n SourceMapV3,\n Bias,\n EachMapping,\n GeneratedMapping,\n InvalidGeneratedMapping,\n InvalidOriginalMapping,\n Needle,\n OriginalMapping,\n OriginalMapping as Mapping,\n SectionedSourceMapInput,\n SourceMapInput,\n SourceNeedle,\n XInput,\n EncodedSourceMapXInput,\n DecodedSourceMapXInput,\n SectionedSourceMapXInput,\n SectionXInput,\n} from './types';\n\ninterface PublicMap {\n _encoded: TraceMap['_encoded'];\n _decoded: TraceMap['_decoded'];\n _decodedMemo: TraceMap['_decodedMemo'];\n _bySources: TraceMap['_bySources'];\n _bySourceMemos: TraceMap['_bySourceMemos'];\n}\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n declare ignoreList: SourceMapV3['ignoreList'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names || [];\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n this.ignoreList = parsed.ignoreList || (parsed as XInput).x_google_ignoreList || undefined;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n}\n\n/**\n * Typescript doesn't allow friend access to private fields, so this just casts the map into a type\n * with public access modifiers.\n */\nfunction cast(map: unknown): PublicMap {\n return map as any;\n}\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport function encodedMappings(map: TraceMap): EncodedSourceMap['mappings'] {\n return (cast(map)._encoded ??= encode(cast(map)._decoded!));\n}\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport function decodedMappings(map: TraceMap): Readonly {\n return (cast(map)._decoded ||= decode(cast(map)._encoded!));\n}\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport function traceSegment(\n map: TraceMap,\n line: number,\n column: number,\n): Readonly | null {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n cast(map)._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n}\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport function originalPositionFor(\n map: TraceMap,\n needle: Needle,\n): OriginalMapping | InvalidOriginalMapping {\n let { line, column, bias } = needle;\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n cast(map)._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n}\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport function generatedPositionFor(\n map: TraceMap,\n needle: SourceNeedle,\n): GeneratedMapping | InvalidGeneratedMapping {\n const { source, line, column, bias } = needle;\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n}\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[] {\n const { source, line, column, bias } = needle;\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n}\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n}\n\nfunction sourceIndex(map: TraceMap, source: string): number {\n const { sources, resolvedSources } = map;\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n return index;\n}\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport function sourceContentFor(map: TraceMap, source: string): string | null {\n const { sourcesContent } = map;\n if (sourcesContent == null) return null;\n const index = sourceIndex(map, source);\n return index === -1 ? null : sourcesContent[index];\n}\n\n/**\n * Determines if the source is marked to ignore by the source map.\n */\nexport function isIgnored(map: TraceMap, source: string): boolean {\n const { ignoreList } = map;\n if (ignoreList == null) return false;\n const index = sourceIndex(map, source);\n return index === -1 ? false : ignoreList.includes(index);\n}\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n cast(tracer)._decoded = map.mappings;\n return tracer;\n}\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function decodedMap(\n map: TraceMap,\n): Omit & { mappings: readonly SourceMapSegment[][] } {\n return clone(map, decodedMappings(map));\n}\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function encodedMap(map: TraceMap): EncodedSourceMap {\n return clone(map, encodedMappings(map));\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n ignoreList: map.ignoreList || (map as XInput).x_google_ignoreList,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n): GeneratedMapping | InvalidGeneratedMapping;\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n): GeneratedMapping[];\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (cast(map)._bySources ||= buildBySources(\n decodedMappings(map),\n (cast(map)._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = cast(map)._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n}\n"],"names":["encode","decode","bsFound"],"mappings":";;;;;;IAEc,SAAU,OAAO,CAAC,KAAa,EAAE,IAAwB,EAAA;;;;QAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,IAAI,IAAI,GAAG,CAAC;IAE7C,IAAA,OAAO,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACjC;;ICTA;;IAEG;IACqB,SAAA,aAAa,CAAC,IAA+B,EAAA;IACnE,IAAA,IAAI,CAAC,IAAI;IAAE,QAAA,OAAO,EAAE,CAAC;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IAClC;;ICQO,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IACtB,MAAM,aAAa,GAAG,CAAC,C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AK,GAAG,oBAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QACvE,IAAI,KAAK,KAAK,CAAC,CAAC;IAAE,QAAA,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAE9C,IAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAChC,IAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAClF;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts new file mode 100644 index 00000000..ec775fbe --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts @@ -0,0 +1,8 @@ +import { TraceMap } from './trace-mapping'; +import type { SectionedSourceMapInput } from './types'; +type AnyMap = { + new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; + (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; +}; +export declare const AnyMap: AnyMap; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts new file mode 100644 index 00000000..ecb2873c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts @@ -0,0 +1,32 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts new file mode 100644 index 00000000..a91751cd --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts @@ -0,0 +1,7 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; +import type { MemoState } from './binary-search'; +export type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts new file mode 100644 index 00000000..cf7d4f8a --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts @@ -0,0 +1 @@ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts new file mode 100644 index 00000000..2bfb5dc1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts @@ -0,0 +1,2 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 00000000..6d4d318d --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,16 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type GeneratedLine = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts new file mode 100644 index 00000000..bead5c12 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts @@ -0,0 +1,4 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts new file mode 100644 index 00000000..f618ec36 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts @@ -0,0 +1,79 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping } from './types'; +export type { SourceMapSegment } from './sourcemap-segment'; +export type { SourceMap, DecodedSourceMap, EncodedSourceMap, Section, SectionedSourceMap, SourceMapV3, Bias, EachMapping, GeneratedMapping, InvalidGeneratedMapping, InvalidOriginalMapping, Needle, OriginalMapping, OriginalMapping as Mapping, SectionedSourceMapInput, SourceMapInput, SourceNeedle, XInput, EncodedSourceMapXInput, DecodedSourceMapXInput, SectionedSourceMapXInput, SectionXInput, } from './types'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +export { AnyMap } from './any-map'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + ignoreList: SourceMapV3['ignoreList']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare function encodedMappings(map: TraceMap): EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare function decodedMappings(map: TraceMap): Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare function traceSegment(map: TraceMap, line: number, column: number): Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare function originalPositionFor(map: TraceMap, needle: Needle): OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare function generatedPositionFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare function sourceContentFor(map: TraceMap, source: string): string | null; +/** + * Determines if the source is marked to ignore by the source map. + */ +export declare function isIgnored(map: TraceMap, source: string): boolean; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function decodedMap(map: TraceMap): Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function encodedMap(map: TraceMap): EncodedSourceMap; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts new file mode 100644 index 00000000..a94e6b25 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts @@ -0,0 +1,99 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export type XInput = { + x_google_ignoreList?: SourceMapV3['ignoreList']; +}; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; +export type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; + ignoreList: SourceMapV3['ignoreList']; +} diff --git a/node_modules/@jridgewell/trace-mapping/package.json b/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 00000000..454a1bdb --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,77 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.25", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "types": "dist/types/trace-mapping.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": [ + { + "types": "./dist/types/trace-mapping.d.ts", + "browser": "./dist/trace-mapping.umd.js", + "require": "./dist/trace-mapping.umd.js", + "import": "./dist/trace-mapping.mjs" + }, + "./dist/trace-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/trace-mapping.git" + }, + "license": "MIT", + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.mjs", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.mjs", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts' '**/*.md'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "c8 mocha", + "test:watch": "mocha --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "11.1.6", + "@types/mocha": "10.0.6", + "@types/node": "20.11.20", + "@typescript-eslint/eslint-plugin": "6.18.1", + "@typescript-eslint/parser": "6.18.1", + "benchmark": "2.1.4", + "c8": "9.0.0", + "esbuild": "0.19.11", + "eslint": "8.56.0", + "eslint-config-prettier": "9.1.0", + "eslint-plugin-no-only-tests": "3.1.0", + "mocha": "10.3.0", + "npm-run-all": "4.1.5", + "prettier": "3.1.1", + "rollup": "4.9.4", + "tsx": "4.7.0", + "typescript": "5.3.3" + }, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } +} diff --git a/node_modules/@polka/url/build.js b/node_modules/@polka/url/build.js new file mode 100644 index 00000000..33dfc56c --- /dev/null +++ b/node_modules/@polka/url/build.js @@ -0,0 +1,42 @@ +const qs = require('querystring'); + +/** + * @typedef ParsedURL + * @type {import('.').ParsedURL} + */ + +/** + * @typedef Request + * @property {string} url + * @property {ParsedURL} _parsedUrl + */ + +/** + * @param {Request} req + * @returns {ParsedURL|void} + */ +function parse(req) { + let raw = req.url; + if (raw == null) return; + + let prev = req._parsedUrl; + if (prev && prev.raw === raw) return prev; + + let pathname=raw, search='', query; + + if (raw.length > 1) { + let idx = raw.indexOf('?', 1); + + if (idx !== -1) { + search = raw.substring(idx); + pathname = raw.substring(0, idx); + if (search.length > 1) { + query = qs.parse(search.substring(1)); + } + } + } + + return req._parsedUrl = { pathname, search, query, raw }; +} + +exports.parse = parse; \ No newline at end of file diff --git a/node_modules/@polka/url/build.mjs b/node_modules/@polka/url/build.mjs new file mode 100644 index 00000000..ff908482 --- /dev/null +++ b/node_modules/@polka/url/build.mjs @@ -0,0 +1,40 @@ +import * as qs from 'node:querystring'; + +/** + * @typedef ParsedURL + * @type {import('.').ParsedURL} + */ + +/** + * @typedef Request + * @property {string} url + * @property {ParsedURL} _parsedUrl + */ + +/** + * @param {Request} req + * @returns {ParsedURL|void} + */ +export function parse(req) { + let raw = req.url; + if (raw == null) return; + + let prev = req._parsedUrl; + if (prev && prev.raw === raw) return prev; + + let pathname=raw, search='', query; + + if (raw.length > 1) { + let idx = raw.indexOf('?', 1); + + if (idx !== -1) { + search = raw.substring(idx); + pathname = raw.substring(0, idx); + if (search.length > 1) { + query = qs.parse(search.substring(1)); + } + } + } + + return req._parsedUrl = { pathname, search, query, raw }; +} diff --git a/node_modules/@polka/url/index.d.ts b/node_modules/@polka/url/index.d.ts new file mode 100644 index 00000000..9b27c042 --- /dev/null +++ b/node_modules/@polka/url/index.d.ts @@ -0,0 +1,10 @@ +import type { IncomingMessage } from 'http'; + +export interface ParsedURL { + pathname: string; + search: string; + query: Record | void; + raw: string; +} + +export function parse(req: IncomingMessage): ParsedURL; diff --git a/node_modules/@polka/url/package.json b/node_modules/@polka/url/package.json new file mode 100644 index 00000000..159aefec --- /dev/null +++ b/node_modules/@polka/url/package.json @@ -0,0 +1,30 @@ +{ + "version": "1.0.0-next.28", + "name": "@polka/url", + "repository": "lukeed/polka", + "description": "Super fast, memoized `req.url` parser", + "module": "build.mjs", + "types": "index.d.ts", + "main": "build.js", + "license": "MIT", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./build.mjs", + "require": "./build.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "build.*", + "index.d.*" + ], + "author": { + "name": "Luke Edwards", + "email": "luke@lukeed.com", + "url": "https://lukeed.com" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/node_modules/@polka/url/readme.md b/node_modules/@polka/url/readme.md new file mode 100644 index 00000000..e47645ce --- /dev/null +++ b/node_modules/@polka/url/readme.md @@ -0,0 +1,68 @@ +# @polka/url [![npm](https://badgen.now.sh/npm/v/@polka/url)](https://npmjs.org/package/@polka/url) [![licenses](https://licenses.dev/b/npm/%40polka%2Furl)](https://licenses.dev/npm/%40polka%2Furl) + +> Super fast, memoized `req.url` parser; _not_ limited to [Polka][polka]! + +Parses the `url` from a [`IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) request. The returned object will always only contain the following keys: `search`, `query`, `pathname`, and `raw`. + +> **Note:** This library does not process `protocol`, `hostname`, `port`, etc.
This is because the incoming `req.url` value only begins with the path information. + +Parsed requests will be mutated with a `_parsedUrl` key, containing the returned output. This is used for future memoization, avoiding the need to fully parse the same `url` value multiple times. + +## Install + +``` +$ npm install --save @polka/url +``` + +## Usage + +```js +const parse = require('@polka/url'); + +let req = { + url: '/foo/bar?fizz=buzz' +}; +let output = parse(req); +//=> { +//=> pathname: '/foo/bar', +//=> raw: '/foo/bar?fizz=buzz', +//=> search: '?fizz=buzz', +//=> query: { +//=> fizz: 'buzz' +//=> }, +//=> } + +// Attaches result for future memoization +assert.deepEqual(output, req._parsedUrl); //=> true +``` + +## API + +### url(req) +Returns: `Object` or `undefined` + +> **Important:** The `req` must have a `url` key, otherwise `undefined` will be returned.
If no input is provided at all, a `TypeError` will be thrown. + +#### req +Type: `IncomingMessage` or `{ url: string }` + +The incoming HTTP request (`req`) or a plain `Object` with a `url` key. + +> **Note:** In Node.js servers, the [`req.url`](https://nodejs.org/api/http.html#http_message_url) begins with a pathname & does not include a `hash`. + + +## Benchmarks + +Check out the [`bench`](/bench) directory for in-depth benchmark results and comparisons. + + +## Support + +Any issues or questions can be sent to the [Polka][polka] repository.
However, please specify that your inquiry is about `@polka/url` specifically. + + +## License + +MIT © [Luke Edwards](https://lukeed.com) + +[polka]: https://github.com/lukeed/polka diff --git a/node_modules/@rollup/rollup-win32-x64-msvc/README.md b/node_modules/@rollup/rollup-win32-x64-msvc/README.md new file mode 100644 index 00000000..7382dbc4 --- /dev/null +++ b/node_modules/@rollup/rollup-win32-x64-msvc/README.md @@ -0,0 +1,3 @@ +# `@rollup/rollup-win32-x64-msvc` + +This is the **x86_64-pc-windows-msvc** binary for `rollup` diff --git a/node_modules/@rollup/rollup-win32-x64-msvc/package.json b/node_modules/@rollup/rollup-win32-x64-msvc/package.json new file mode 100644 index 00000000..68c563d8 --- /dev/null +++ b/node_modules/@rollup/rollup-win32-x64-msvc/package.json @@ -0,0 +1,19 @@ +{ + "name": "@rollup/rollup-win32-x64-msvc", + "version": "4.22.5", + "os": [ + "win32" + ], + "cpu": [ + "x64" + ], + "files": [ + "rollup.win32-x64-msvc.node" + ], + "description": "Native bindings for Rollup", + "author": "Lukas Taegert-Atkinson", + "homepage": "https://rollupjs.org/", + "license": "MIT", + "repository": "rollup/rollup", + "main": "./rollup.win32-x64-msvc.node" +} \ No newline at end of file diff --git a/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node b/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node new file mode 100644 index 00000000..776d2fd1 Binary files /dev/null and b/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node differ diff --git a/node_modules/@sveltejs/adapter-auto/LICENSE b/node_modules/@sveltejs/adapter-auto/LICENSE new file mode 100644 index 00000000..22efd0c0 --- /dev/null +++ b/node_modules/@sveltejs/adapter-auto/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@sveltejs/adapter-auto/README.md b/node_modules/@sveltejs/adapter-auto/README.md new file mode 100644 index 00000000..26f861de --- /dev/null +++ b/node_modules/@sveltejs/adapter-auto/README.md @@ -0,0 +1,11 @@ +# adapter-auto + +Automatically chooses the SvelteKit adapter for your current environment, if possible. + +## Docs + +[Docs](https://kit.svelte.dev/docs/adapter-auto) + +## Changelog + +[The Changelog for this package is available on GitHub](https://github.com/sveltejs/kit/blob/main/packages/adapter-auto/CHANGELOG.md). diff --git a/node_modules/@sveltejs/adapter-auto/adapters.js b/node_modules/@sveltejs/adapter-auto/adapters.js new file mode 100644 index 00000000..edf9e343 --- /dev/null +++ b/node_modules/@sveltejs/adapter-auto/adapters.js @@ -0,0 +1,42 @@ +import process from 'node:process'; + +// List of adapters to check for. `version` is used to pin the installed adapter version and should point +// to the latest version of the adapter that is compatible with adapter-auto's current peerDependency version of SvelteKit. +export const adapters = [ + { + name: 'Vercel', + test: () => !!process.env.VERCEL, + module: '@sveltejs/adapter-vercel', + version: '4' + }, + { + name: 'Cloudflare Pages', + test: () => !!process.env.CF_PAGES, + module: '@sveltejs/adapter-cloudflare', + version: '3' + }, + { + name: 'Netlify', + test: () => !!process.env.NETLIFY, + module: '@sveltejs/adapter-netlify', + version: '3' + }, + { + name: 'Azure Static Web Apps', + test: () => process.env.GITHUB_ACTION_REPOSITORY === 'Azure/static-web-apps-deploy', + module: 'svelte-adapter-azure-swa', + version: '0.20' + }, + { + name: 'AWS via SST', + test: () => !!process.env.SST, + module: 'svelte-kit-sst', + version: '2' + }, + { + name: 'Google Cloud Run', + test: () => !!process.env.GCP_BUILDPACKS, + module: '@sveltejs/adapter-node', + version: '5' + } +]; diff --git a/node_modules/@sveltejs/adapter-auto/index.d.ts b/node_modules/@sveltejs/adapter-auto/index.d.ts new file mode 100644 index 00000000..90af12a0 --- /dev/null +++ b/node_modules/@sveltejs/adapter-auto/index.d.ts @@ -0,0 +1,3 @@ +import { Adapter } from '@sveltejs/kit'; + +export default function plugin(): Adapter; diff --git a/node_modules/@sveltejs/adapter-auto/index.js b/node_modules/@sveltejs/adapter-auto/index.js new file mode 100644 index 00000000..1519169f --- /dev/null +++ b/node_modules/@sveltejs/adapter-auto/index.js @@ -0,0 +1,128 @@ +import { execSync } from 'node:child_process'; +import { pathToFileURL } from 'node:url'; +import { resolve } from 'import-meta-resolve'; +import { adapters } from './adapters.js'; +import { dirname, join } from 'node:path'; +import { existsSync } from 'node:fs'; +import process from 'node:process'; + +/** @type {Record string>} */ +const commands = { + npm: (name, version) => `npm install -D ${name}@${version}`, + pnpm: (name, version) => `pnpm add -D ${name}@${version}`, + yarn: (name, version) => `yarn add -D ${name}@${version}` +}; + +function detect_lockfile() { + let dir = process.cwd(); + + do { + if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm'; + if (existsSync(join(dir, 'yarn.lock'))) return 'yarn'; + if (existsSync(join(dir, 'package-lock.json'))) return 'npm'; + } while (dir !== (dir = dirname(dir))); + + return 'npm'; +} + +function detect_package_manager() { + const manager = detect_lockfile(); + + try { + execSync(`${manager} --version`); + return manager; + } catch { + return 'npm'; + } +} + +/** @param {string} name */ +function import_from_cwd(name) { + const cwd = pathToFileURL(process.cwd()).href; + const url = resolve(name, cwd + '/x.js'); + + return import(url); +} + +/** @typedef {import('@sveltejs/kit').Adapter} Adapter */ + +/** + * @returns {Promise} The corresponding adapter for the current environment if found otherwise undefined + */ +async function get_adapter() { + const match = adapters.find((candidate) => candidate.test()); + + if (!match) return; + + /** @type {{ default: () => Adapter }} */ + let module; + + try { + module = await import_from_cwd(match.module); + } catch (error) { + if ( + error.code === 'ERR_MODULE_NOT_FOUND' && + error.message.startsWith(`Cannot find package '${match.module}'`) + ) { + const package_manager = detect_package_manager(); + const command = commands[package_manager](match.module, match.version); + + try { + console.log(`Installing ${match.module}...`); + + execSync(command, { + stdio: 'inherit', + env: { + ...process.env, + NODE_ENV: undefined + } + }); + + module = await import_from_cwd(match.module); + + console.log(`Successfully installed ${match.module}.`); + console.warn( + `\nIf you plan on staying on this deployment platform, consider replacing @sveltejs/adapter-auto with ${match.module}. This will give you faster and more robust installs, and more control over deployment configuration.\n` + ); + } catch (e) { + throw new Error( + `Could not install ${match.module}. Please install it yourself by adding it to your package.json's devDependencies and try building your project again.`, + { cause: e } + ); + } + } else { + throw error; + } + } + + const adapter = module.default(); + + return { + ...adapter, + adapt: (builder) => { + builder.log.info(`Detected environment: ${match.name}. Using ${match.module}`); + return adapter.adapt(builder); + } + }; +} + +/** @type {() => Adapter} */ +export default () => ({ + name: '@sveltejs/adapter-auto', + adapt: async (builder) => { + const adapter = await get_adapter(); + + if (adapter) return adapter.adapt(builder); + + builder.log.warn( + 'Could not detect a supported production environment. See https://kit.svelte.dev/docs/adapters to learn how to configure your app to run on the platform of your choosing' + ); + }, + supports: { + read: () => { + throw new Error( + "The read function imported from $app/server only works in certain environments. Since you're using @sveltejs/adapter-auto, SvelteKit cannot determine whether it will work when your app is deployed. Please replace it with an adapter tailored to your target environment." + ); + } + } +}); diff --git a/node_modules/@sveltejs/adapter-auto/package.json b/node_modules/@sveltejs/adapter-auto/package.json new file mode 100644 index 00000000..6755165e --- /dev/null +++ b/node_modules/@sveltejs/adapter-auto/package.json @@ -0,0 +1,53 @@ +{ + "name": "@sveltejs/adapter-auto", + "version": "3.2.5", + "description": "Automatically chooses the SvelteKit adapter for your current environment, if possible.", + "keywords": [ + "adapter", + "automatically", + "deploy", + "hosting", + "platform", + "svelte", + "sveltekit" + ], + "repository": { + "type": "git", + "url": "https://github.com/sveltejs/kit", + "directory": "packages/adapter-auto" + }, + "license": "MIT", + "homepage": "https://kit.svelte.dev", + "type": "module", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.js" + }, + "./package.json": "./package.json" + }, + "types": "index.d.ts", + "files": [ + "files", + "index.js", + "index.d.ts", + "adapters.js" + ], + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^3.0.1", + "@types/node": "^18.19.48", + "typescript": "^5.3.3", + "@sveltejs/kit": "^2.5.28" + }, + "dependencies": { + "import-meta-resolve": "^4.1.0" + }, + "peerDependencies": { + "@sveltejs/kit": "^2.0.0" + }, + "scripts": { + "lint": "prettier --check .", + "format": "pnpm lint --write", + "check": "tsc" + } +} \ No newline at end of file diff --git a/node_modules/@sveltejs/kit/LICENSE b/node_modules/@sveltejs/kit/LICENSE new file mode 100644 index 00000000..22efd0c0 --- /dev/null +++ b/node_modules/@sveltejs/kit/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@sveltejs/kit/README.md b/node_modules/@sveltejs/kit/README.md new file mode 100644 index 00000000..86a45472 --- /dev/null +++ b/node_modules/@sveltejs/kit/README.md @@ -0,0 +1,18 @@ +# The fastest way to build Svelte apps + +This is the [SvelteKit](https://kit.svelte.dev) framework and CLI. + +The quickest way to get started is via the [create-svelte](https://github.com/sveltejs/kit/tree/main/packages/create-svelte) package: + +```bash +npm create svelte@latest my-app +cd my-app +npm install +npm run dev +``` + +See the [documentation](https://kit.svelte.dev/docs) to learn more. + +## Changelog + +[The Changelog for this package is available on GitHub](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md). diff --git a/node_modules/@sveltejs/kit/package.json b/node_modules/@sveltejs/kit/package.json new file mode 100644 index 00000000..d4e501e2 --- /dev/null +++ b/node_modules/@sveltejs/kit/package.json @@ -0,0 +1,106 @@ +{ + "name": "@sveltejs/kit", + "version": "2.6.1", + "description": "SvelteKit is the fastest way to build Svelte apps", + "keywords": [ + "framework", + "official", + "svelte", + "sveltekit", + "vite" + ], + "repository": { + "type": "git", + "url": "https://github.com/sveltejs/kit", + "directory": "packages/kit" + }, + "license": "MIT", + "homepage": "https://kit.svelte.dev", + "type": "module", + "dependencies": { + "@types/cookie": "^0.6.0", + "cookie": "^0.6.0", + "devalue": "^5.1.0", + "esm-env": "^1.0.0", + "import-meta-resolve": "^4.1.0", + "kleur": "^4.1.5", + "magic-string": "^0.30.5", + "mrmime": "^2.0.0", + "sade": "^1.8.1", + "set-cookie-parser": "^2.6.0", + "sirv": "^2.0.4", + "tiny-glob": "^0.2.9" + }, + "devDependencies": { + "@playwright/test": "^1.44.1", + "@sveltejs/vite-plugin-svelte": "^3.0.1", + "@types/connect": "^3.4.38", + "@types/node": "^18.19.48", + "@types/set-cookie-parser": "^2.4.7", + "dts-buddy": "^0.5.3", + "rollup": "^4.14.2", + "svelte": "^4.2.10", + "svelte-preprocess": "^6.0.0", + "typescript": "^5.3.3", + "vite": "^5.3.2", + "vitest": "^2.0.1" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1", + "svelte": "^4.0.0 || ^5.0.0-next.0", + "vite": "^5.0.3" + }, + "bin": { + "svelte-kit": "svelte-kit.js" + }, + "files": [ + "src", + "!src/**/*.spec.js", + "!src/core/**/fixtures", + "!src/core/**/test", + "types", + "svelte-kit.js", + "postinstall.js" + ], + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./types/index.d.ts", + "import": "./src/exports/index.js" + }, + "./node": { + "types": "./types/index.d.ts", + "import": "./src/exports/node/index.js" + }, + "./node/polyfills": { + "types": "./types/index.d.ts", + "import": "./src/exports/node/polyfills.js" + }, + "./hooks": { + "types": "./types/index.d.ts", + "import": "./src/exports/hooks/index.js" + }, + "./vite": { + "types": "./types/index.d.ts", + "import": "./src/exports/vite/index.js" + } + }, + "types": "types/index.d.ts", + "engines": { + "node": ">=18.13" + }, + "scripts": { + "lint": "prettier --config ../../.prettierrc --check .", + "check": "tsc && cd ./test/types && tsc", + "check:all": "tsc && pnpm -r --filter=\"./**\" check", + "format": "prettier --config ../../.prettierrc --write .", + "test": "pnpm test:unit && pnpm test:integration", + "test:integration": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test", + "test:cross-platform:dev": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:dev", + "test:cross-platform:build": "pnpm test:unit && pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:build", + "test:unit": "vitest --config kit.vitest.config.js run", + "postinstall": "node postinstall.js", + "generate:version": "node scripts/generate-version.js", + "generate:types": "node scripts/generate-dts.js" + } +} \ No newline at end of file diff --git a/node_modules/@sveltejs/kit/postinstall.js b/node_modules/@sveltejs/kit/postinstall.js new file mode 100644 index 00000000..ac79151e --- /dev/null +++ b/node_modules/@sveltejs/kit/postinstall.js @@ -0,0 +1,55 @@ +import { load_config } from './src/core/config/index.js'; +import glob from 'tiny-glob/sync.js'; +import fs from 'node:fs'; +import process from 'node:process'; + +try { + const cwd = process.env.INIT_CWD ?? process.cwd(); + process.chdir(cwd); + + if (fs.existsSync('package.json')) { + const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); + + const workspaces = []; + + if (pkg.workspaces) { + // Find all npm and Yarn workspace glob patterns + // https://classic.yarnpkg.com/blog/2018/02/15/nohoist/ + // https://docs.npmjs.com/cli/v9/configuring-npm/package-json#workspaces + const patterns = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces.packages; + + for (const pattern of patterns) { + workspaces.push( + ...glob(pattern, { cwd, absolute: true }).filter((path) => + fs.statSync(path).isDirectory() + ) + ); + } + } else { + workspaces.push(cwd); + } + + for (const cwd of workspaces) { + process.chdir(cwd); + + if (!fs.existsSync('package.json')) continue; + if (!fs.existsSync('svelte.config.js')) continue; + + const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); + if (!pkg.dependencies?.['@sveltejs/kit'] && !pkg.devDependencies?.['@sveltejs/kit']) continue; + + // defer import until after the chdir so that peer dependency resolves correctly + const sync = await import('./src/core/sync/sync.js'); + + try { + const config = await load_config(); + sync.all(config, 'development'); + } catch (error) { + console.error('Error while trying to sync SvelteKit config'); + console.error(error); + } + } + } +} catch (error) { + console.error(error); +} diff --git a/node_modules/@sveltejs/kit/src/cli.js b/node_modules/@sveltejs/kit/src/cli.js new file mode 100644 index 00000000..1ebb0204 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/cli.js @@ -0,0 +1,45 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import process from 'node:process'; +import colors from 'kleur'; +import sade from 'sade'; +import { load_config } from './core/config/index.js'; +import { coalesce_to_error } from './utils/error.js'; + +/** @param {unknown} e */ +function handle_error(e) { + const error = coalesce_to_error(e); + + if (error.name === 'SyntaxError') throw error; + + console.error(colors.bold().red(`> ${error.message}`)); + if (error.stack) { + console.error(colors.gray(error.stack.split('\n').slice(1).join('\n'))); + } + + process.exit(1); +} + +const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8')); +const prog = sade('svelte-kit').version(pkg.version); + +prog + .command('sync') + .describe('Synchronise generated type definitions') + .option('--mode', 'Specify a mode for loading environment variables', 'development') + .action(async ({ mode }) => { + if (!fs.existsSync('svelte.config.js')) { + console.warn(`Missing ${path.resolve('svelte.config.js')} — skipping`); + return; + } + + try { + const config = await load_config(); + const sync = await import('./core/sync/sync.js'); + sync.all_types(config, mode); + } catch (error) { + handle_error(error); + } + }); + +prog.parse(process.argv, { unknown: (arg) => `Unknown option: ${arg}` }); diff --git a/node_modules/@sveltejs/kit/src/constants.js b/node_modules/@sveltejs/kit/src/constants.js new file mode 100644 index 00000000..7790ab1c --- /dev/null +++ b/node_modules/@sveltejs/kit/src/constants.js @@ -0,0 +1,11 @@ +/** + * A fake asset path used in `vite dev` and `vite preview`, so that we can + * serve local assets while verifying that requests are correctly prefixed + */ +export const SVELTE_KIT_ASSETS = '/_svelte_kit_assets'; + +export const GENERATED_COMMENT = '// this file is generated — do not edit it\n'; + +export const ENDPOINT_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']; + +export const PAGE_METHODS = ['GET', 'POST', 'HEAD']; diff --git a/node_modules/@sveltejs/kit/src/core/adapt/builder.js b/node_modules/@sveltejs/kit/src/core/adapt/builder.js new file mode 100644 index 00000000..e02efbdd --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/adapt/builder.js @@ -0,0 +1,249 @@ +import colors from 'kleur'; +import { createReadStream, createWriteStream, existsSync, statSync } from 'node:fs'; +import { extname, resolve } from 'node:path'; +import { pipeline } from 'node:stream'; +import { promisify } from 'node:util'; +import zlib from 'node:zlib'; +import { copy, rimraf, mkdirp } from '../../utils/filesystem.js'; +import { generate_manifest } from '../generate_manifest/index.js'; +import { get_route_segments } from '../../utils/routing.js'; +import { get_env } from '../../exports/vite/utils.js'; +import generate_fallback from '../postbuild/fallback.js'; +import { write } from '../sync/utils.js'; +import { list_files } from '../utils.js'; +import { find_server_assets } from '../generate_manifest/find_server_assets.js'; + +const pipe = promisify(pipeline); +const extensions = ['.html', '.js', '.mjs', '.json', '.css', '.svg', '.xml', '.wasm']; + +/** + * Creates the Builder which is passed to adapters for building the application. + * @param {{ + * config: import('types').ValidatedConfig; + * build_data: import('types').BuildData; + * server_metadata: import('types').ServerMetadata; + * route_data: import('types').RouteData[]; + * prerendered: import('types').Prerendered; + * prerender_map: import('types').PrerenderMap; + * log: import('types').Logger; + * vite_config: import('vite').ResolvedConfig; + * }} opts + * @returns {import('@sveltejs/kit').Builder} + */ +export function create_builder({ + config, + build_data, + server_metadata, + route_data, + prerendered, + prerender_map, + log, + vite_config +}) { + /** @type {Map} */ + const lookup = new Map(); + + /** + * Rather than exposing the internal `RouteData` type, which is subject to change, + * we expose a stable type that adapters can use to group/filter routes + */ + const routes = route_data.map((route) => { + const { config, methods, page, api } = /** @type {import('types').ServerMetadataRoute} */ ( + server_metadata.routes.get(route.id) + ); + + /** @type {import('@sveltejs/kit').RouteDefinition} */ + const facade = { + id: route.id, + api, + page, + segments: get_route_segments(route.id).map((segment) => ({ + dynamic: segment.includes('['), + rest: segment.includes('[...'), + content: segment + })), + pattern: route.pattern, + prerender: prerender_map.get(route.id) ?? false, + methods, + config + }; + + lookup.set(facade, route); + + return facade; + }); + + return { + log, + rimraf, + mkdirp, + copy, + + config, + prerendered, + routes, + + async compress(directory) { + if (!existsSync(directory)) { + return; + } + + const files = list_files(directory, (file) => extensions.includes(extname(file))).map( + (file) => resolve(directory, file) + ); + + await Promise.all( + files.flatMap((file) => [compress_file(file, 'gz'), compress_file(file, 'br')]) + ); + }, + + async createEntries(fn) { + const seen = new Set(); + + for (let i = 0; i < route_data.length; i += 1) { + const route = route_data[i]; + if (prerender_map.get(route.id) === true) continue; + const { id, filter, complete } = fn(routes[i]); + + if (seen.has(id)) continue; + seen.add(id); + + const group = [route]; + + // figure out which lower priority routes should be considered fallbacks + for (let j = i + 1; j < route_data.length; j += 1) { + if (prerender_map.get(routes[j].id) === true) continue; + if (filter(routes[j])) { + group.push(route_data[j]); + } + } + + const filtered = new Set(group); + + // heuristic: if /foo/[bar] is included, /foo/[bar].json should + // also be included, since the page likely needs the endpoint + // TODO is this still necessary, given the new way of doing things? + filtered.forEach((route) => { + if (route.page) { + const endpoint = route_data.find((candidate) => candidate.id === route.id + '.json'); + + if (endpoint) { + filtered.add(endpoint); + } + } + }); + + if (filtered.size > 0) { + await complete({ + generateManifest: ({ relativePath }) => + generate_manifest({ + build_data, + relative_path: relativePath, + routes: Array.from(filtered) + }) + }); + } + } + }, + + findServerAssets(route_data) { + return find_server_assets( + build_data, + route_data.map((route) => /** @type {import('types').RouteData} */ (lookup.get(route))) + ); + }, + + async generateFallback(dest) { + const manifest_path = `${config.kit.outDir}/output/server/manifest-full.js`; + const env = get_env(config.kit.env, vite_config.mode); + + const fallback = await generate_fallback({ + manifest_path, + env: { ...env.private, ...env.public } + }); + + if (existsSync(dest)) { + console.log( + colors + .bold() + .yellow( + `Overwriting ${dest} with fallback page. Consider using a different name for the fallback.` + ) + ); + } + + write(dest, fallback); + }, + + generateEnvModule() { + const dest = `${config.kit.outDir}/output/prerendered/dependencies/${config.kit.appDir}/env.js`; + const env = get_env(config.kit.env, vite_config.mode); + + write(dest, `export const env=${JSON.stringify(env.public)}`); + }, + + generateManifest({ relativePath, routes: subset }) { + return generate_manifest({ + build_data, + relative_path: relativePath, + routes: subset + ? subset.map((route) => /** @type {import('types').RouteData} */ (lookup.get(route))) + : route_data.filter((route) => prerender_map.get(route.id) !== true) + }); + }, + + getBuildDirectory(name) { + return `${config.kit.outDir}/${name}`; + }, + + getClientDirectory() { + return `${config.kit.outDir}/output/client`; + }, + + getServerDirectory() { + return `${config.kit.outDir}/output/server`; + }, + + getAppPath() { + return build_data.app_path; + }, + + writeClient(dest) { + return copy(`${config.kit.outDir}/output/client`, dest, { + // avoid making vite build artefacts public + filter: (basename) => basename !== '.vite' + }); + }, + + writePrerendered(dest) { + const source = `${config.kit.outDir}/output/prerendered`; + return [...copy(`${source}/pages`, dest), ...copy(`${source}/dependencies`, dest)]; + }, + + writeServer(dest) { + return copy(`${config.kit.outDir}/output/server`, dest); + } + }; +} + +/** + * @param {string} file + * @param {'gz' | 'br'} format + */ +async function compress_file(file, format = 'gz') { + const compress = + format == 'br' + ? zlib.createBrotliCompress({ + params: { + [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, + [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY, + [zlib.constants.BROTLI_PARAM_SIZE_HINT]: statSync(file).size + } + }) + : zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION }); + + const source = createReadStream(file); + const destination = createWriteStream(`${file}.${format}`); + + await pipe(source, compress, destination); +} diff --git a/node_modules/@sveltejs/kit/src/core/adapt/index.js b/node_modules/@sveltejs/kit/src/core/adapt/index.js new file mode 100644 index 00000000..3cfe5275 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/adapt/index.js @@ -0,0 +1,41 @@ +import colors from 'kleur'; +import { create_builder } from './builder.js'; + +/** + * @param {import('types').ValidatedConfig} config + * @param {import('types').BuildData} build_data + * @param {import('types').ServerMetadata} server_metadata + * @param {import('types').Prerendered} prerendered + * @param {import('types').PrerenderMap} prerender_map + * @param {import('types').Logger} log + * @param {import('vite').ResolvedConfig} vite_config + */ +export async function adapt( + config, + build_data, + server_metadata, + prerendered, + prerender_map, + log, + vite_config +) { + // This is only called when adapter is truthy, so the cast is safe + const { name, adapt } = /** @type {import('@sveltejs/kit').Adapter} */ (config.kit.adapter); + + console.log(colors.bold().cyan(`\n> Using ${name}`)); + + const builder = create_builder({ + config, + build_data, + server_metadata, + route_data: build_data.manifest_data.routes.filter((route) => route.page || route.endpoint), + prerendered, + prerender_map, + log, + vite_config + }); + + await adapt(builder); + + log.success('done'); +} diff --git a/node_modules/@sveltejs/kit/src/core/config/default-error.html b/node_modules/@sveltejs/kit/src/core/config/default-error.html new file mode 100644 index 00000000..c322e168 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/config/default-error.html @@ -0,0 +1,80 @@ + + + + + %sveltekit.error.message% + + + + +
+ %sveltekit.status% +
+

%sveltekit.error.message%

+
+
+ + diff --git a/node_modules/@sveltejs/kit/src/core/config/index.js b/node_modules/@sveltejs/kit/src/core/config/index.js new file mode 100644 index 00000000..36b82a86 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/config/index.js @@ -0,0 +1,119 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import process from 'node:process'; +import * as url from 'node:url'; +import options from './options.js'; + +/** + * Loads the template (src/app.html by default) and validates that it has the + * required content. + * @param {string} cwd + * @param {import('types').ValidatedConfig} config + */ +export function load_template(cwd, { kit }) { + const { env, files } = kit; + + const relative = path.relative(cwd, files.appTemplate); + + if (!fs.existsSync(files.appTemplate)) { + throw new Error(`${relative} does not exist`); + } + + const contents = fs.readFileSync(files.appTemplate, 'utf8'); + + const expected_tags = ['%sveltekit.head%', '%sveltekit.body%']; + expected_tags.forEach((tag) => { + if (contents.indexOf(tag) === -1) { + throw new Error(`${relative} is missing ${tag}`); + } + }); + + for (const match of contents.matchAll(/%sveltekit\.env\.([^%]+)%/g)) { + if (!match[1].startsWith(env.publicPrefix)) { + throw new Error( + `Environment variables in ${relative} must start with ${env.publicPrefix} (saw %sveltekit.env.${match[1]}%)` + ); + } + } + + return contents; +} + +/** + * Loads the error page (src/error.html by default) if it exists. + * Falls back to a generic error page content. + * @param {import('types').ValidatedConfig} config + */ +export function load_error_page(config) { + let { errorTemplate } = config.kit.files; + + // Don't do this inside resolving the config, because that would mean + // adding/removing error.html isn't detected and would require a restart. + if (!fs.existsSync(config.kit.files.errorTemplate)) { + errorTemplate = url.fileURLToPath(new URL('./default-error.html', import.meta.url)); + } + + return fs.readFileSync(errorTemplate, 'utf-8'); +} + +/** + * Loads and validates svelte.config.js + * @param {{ cwd?: string }} options + * @returns {Promise} + */ +export async function load_config({ cwd = process.cwd() } = {}) { + const config_file = path.join(cwd, 'svelte.config.js'); + + if (!fs.existsSync(config_file)) { + return process_config({}, { cwd }); + } + + const config = await import(`${url.pathToFileURL(config_file).href}?ts=${Date.now()}`); + + try { + return process_config(config.default, { cwd }); + } catch (e) { + const error = /** @type {Error} */ (e); + + // redact the stack trace — it's not helpful to users + error.stack = `Could not load svelte.config.js: ${error.message}\n`; + throw error; + } +} + +/** + * @param {import('@sveltejs/kit').Config} config + * @returns {import('types').ValidatedConfig} + */ +function process_config(config, { cwd = process.cwd() } = {}) { + const validated = validate_config(config); + + validated.kit.outDir = path.resolve(cwd, validated.kit.outDir); + + for (const key in validated.kit.files) { + if (key === 'hooks') { + validated.kit.files.hooks.client = path.resolve(cwd, validated.kit.files.hooks.client); + validated.kit.files.hooks.server = path.resolve(cwd, validated.kit.files.hooks.server); + validated.kit.files.hooks.universal = path.resolve(cwd, validated.kit.files.hooks.universal); + } else { + // @ts-expect-error + validated.kit.files[key] = path.resolve(cwd, validated.kit.files[key]); + } + } + + return validated; +} + +/** + * @param {import('@sveltejs/kit').Config} config + * @returns {import('types').ValidatedConfig} + */ +export function validate_config(config) { + if (typeof config !== 'object') { + throw new Error( + 'svelte.config.js must have a configuration object as its default export. See https://kit.svelte.dev/docs/configuration' + ); + } + + return options(config, 'config'); +} diff --git a/node_modules/@sveltejs/kit/src/core/config/options.js b/node_modules/@sveltejs/kit/src/core/config/options.js new file mode 100644 index 00000000..a4b41f2a --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/config/options.js @@ -0,0 +1,429 @@ +import { join } from 'node:path'; +import process from 'node:process'; + +/** @typedef {import('./types.js').Validator} Validator */ + +const directives = object({ + 'child-src': string_array(), + 'default-src': string_array(), + 'frame-src': string_array(), + 'worker-src': string_array(), + 'connect-src': string_array(), + 'font-src': string_array(), + 'img-src': string_array(), + 'manifest-src': string_array(), + 'media-src': string_array(), + 'object-src': string_array(), + 'prefetch-src': string_array(), + 'script-src': string_array(), + 'script-src-elem': string_array(), + 'script-src-attr': string_array(), + 'style-src': string_array(), + 'style-src-elem': string_array(), + 'style-src-attr': string_array(), + 'base-uri': string_array(), + sandbox: string_array(), + 'form-action': string_array(), + 'frame-ancestors': string_array(), + 'navigate-to': string_array(), + 'report-uri': string_array(), + 'report-to': string_array(), + 'require-trusted-types-for': string_array(), + 'trusted-types': string_array(), + 'upgrade-insecure-requests': boolean(false), + 'require-sri-for': string_array(), + 'block-all-mixed-content': boolean(false), + 'plugin-types': string_array(), + referrer: string_array() +}); + +/** @type {Validator} */ +const options = object( + { + extensions: validate(['.svelte'], (input, keypath) => { + if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) { + throw new Error(`${keypath} must be an array of strings`); + } + + input.forEach((extension) => { + if (extension[0] !== '.') { + throw new Error(`Each member of ${keypath} must start with '.' — saw '${extension}'`); + } + + if (!/^(\.[a-z0-9]+)+$/i.test(extension)) { + throw new Error(`File extensions must be alphanumeric — saw '${extension}'`); + } + }); + + return input; + }), + + kit: object({ + adapter: validate(null, (input, keypath) => { + if (typeof input !== 'object' || !input.adapt) { + let message = `${keypath} should be an object with an "adapt" method`; + + if (Array.isArray(input) || typeof input === 'string') { + // for the early adapter adopters + message += ', rather than the name of an adapter'; + } + + throw new Error(`${message}. See https://kit.svelte.dev/docs/adapters`); + } + + return input; + }), + + alias: validate({}, (input, keypath) => { + if (typeof input !== 'object') { + throw new Error(`${keypath} should be an object`); + } + + for (const key in input) { + assert_string(input[key], `${keypath}.${key}`); + } + + return input; + }), + + appDir: validate('_app', (input, keypath) => { + assert_string(input, keypath); + + if (input) { + if (input.startsWith('/') || input.endsWith('/')) { + throw new Error( + "config.kit.appDir cannot start or end with '/'. See https://kit.svelte.dev/docs/configuration" + ); + } + } else { + throw new Error(`${keypath} cannot be empty`); + } + + return input; + }), + + csp: object({ + mode: list(['auto', 'hash', 'nonce']), + directives, + reportOnly: directives + }), + + csrf: object({ + checkOrigin: boolean(true) + }), + + embedded: boolean(false), + + env: object({ + dir: string(process.cwd()), + publicPrefix: string('PUBLIC_'), + privatePrefix: string('') + }), + + files: object({ + assets: string('static'), + hooks: object({ + client: string(join('src', 'hooks.client')), + server: string(join('src', 'hooks.server')), + universal: string(join('src', 'hooks')) + }), + lib: string(join('src', 'lib')), + params: string(join('src', 'params')), + routes: string(join('src', 'routes')), + serviceWorker: string(join('src', 'service-worker')), + appTemplate: string(join('src', 'app.html')), + errorTemplate: string(join('src', 'error.html')) + }), + + inlineStyleThreshold: number(0), + + moduleExtensions: string_array(['.js', '.ts']), + + outDir: string('.svelte-kit'), + + output: object({ + preloadStrategy: list(['modulepreload', 'preload-js', 'preload-mjs'], 'modulepreload') + }), + + paths: object({ + base: validate('', (input, keypath) => { + assert_string(input, keypath); + + if (input !== '' && (input.endsWith('/') || !input.startsWith('/'))) { + throw new Error( + `${keypath} option must either be the empty string or a root-relative path that starts but doesn't end with '/'. See https://kit.svelte.dev/docs/configuration#paths` + ); + } + + return input; + }), + assets: validate('', (input, keypath) => { + assert_string(input, keypath); + + if (input) { + if (!/^[a-z]+:\/\//.test(input)) { + throw new Error( + `${keypath} option must be an absolute path, if specified. See https://kit.svelte.dev/docs/configuration#paths` + ); + } + + if (input.endsWith('/')) { + throw new Error( + `${keypath} option must not end with '/'. See https://kit.svelte.dev/docs/configuration#paths` + ); + } + } + + return input; + }), + relative: boolean(true) + }), + + prerender: object({ + concurrency: number(1), + crawl: boolean(true), + entries: validate(['*'], (input, keypath) => { + if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) { + throw new Error(`${keypath} must be an array of strings`); + } + + input.forEach((page) => { + if (page !== '*' && page[0] !== '/') { + throw new Error( + `Each member of ${keypath} must be either '*' or an absolute path beginning with '/' — saw '${page}'` + ); + } + }); + + return input; + }), + + handleHttpError: validate( + (/** @type {any} */ { message }) => { + throw new Error( + message + + '\nTo suppress or handle this error, implement `handleHttpError` in https://kit.svelte.dev/docs/configuration#prerender' + ); + }, + (input, keypath) => { + if (typeof input === 'function') return input; + if (['fail', 'warn', 'ignore'].includes(input)) return input; + throw new Error(`${keypath} should be "fail", "warn", "ignore" or a custom function`); + } + ), + + handleMissingId: validate( + (/** @type {any} */ { message }) => { + throw new Error( + message + + '\nTo suppress or handle this error, implement `handleMissingId` in https://kit.svelte.dev/docs/configuration#prerender' + ); + }, + (input, keypath) => { + if (typeof input === 'function') return input; + if (['fail', 'warn', 'ignore'].includes(input)) return input; + throw new Error(`${keypath} should be "fail", "warn", "ignore" or a custom function`); + } + ), + + handleEntryGeneratorMismatch: validate( + (/** @type {any} */ { message }) => { + throw new Error( + message + + '\nTo suppress or handle this error, implement `handleEntryGeneratorMismatch` in https://kit.svelte.dev/docs/configuration#prerender' + ); + }, + (input, keypath) => { + if (typeof input === 'function') return input; + if (['fail', 'warn', 'ignore'].includes(input)) return input; + throw new Error(`${keypath} should be "fail", "warn", "ignore" or a custom function`); + } + ), + + origin: validate('http://sveltekit-prerender', (input, keypath) => { + assert_string(input, keypath); + + let origin; + + try { + origin = new URL(input).origin; + } catch { + throw new Error(`${keypath} must be a valid origin`); + } + + if (input !== origin) { + throw new Error(`${keypath} must be a valid origin (${origin} rather than ${input})`); + } + + return origin; + }) + }), + + serviceWorker: object({ + register: boolean(true), + files: fun((filename) => !/\.DS_Store/.test(filename)) + }), + + typescript: object({ + config: fun((config) => config) + }), + + version: object({ + name: string(Date.now().toString()), + pollInterval: number(0) + }) + }) + }, + true +); + +/** + * @param {Record} children + * @param {boolean} [allow_unknown] + * @returns {Validator} + */ +function object(children, allow_unknown = false) { + return (input, keypath) => { + /** @type {Record} */ + const output = {}; + + if ((input && typeof input !== 'object') || Array.isArray(input)) { + throw new Error(`${keypath} should be an object`); + } + + for (const key in input) { + if (!(key in children)) { + if (allow_unknown) { + output[key] = input[key]; + } else { + let message = `Unexpected option ${keypath}.${key}`; + + // special case + if (keypath === 'config.kit' && key in options) { + message += ` (did you mean config.${key}?)`; + } + + throw new Error(message); + } + } + } + + for (const key in children) { + const validator = children[key]; + output[key] = validator(input && input[key], `${keypath}.${key}`); + } + + return output; + }; +} + +/** + * @param {any} fallback + * @param {(value: any, keypath: string) => any} fn + * @returns {Validator} + */ +function validate(fallback, fn) { + return (input, keypath) => { + return input === undefined ? fallback : fn(input, keypath); + }; +} + +/** + * @param {string | null} fallback + * @param {boolean} allow_empty + * @returns {Validator} + */ +function string(fallback, allow_empty = true) { + return validate(fallback, (input, keypath) => { + assert_string(input, keypath); + + if (!allow_empty && input === '') { + throw new Error(`${keypath} cannot be empty`); + } + + return input; + }); +} + +/** + * @param {string[] | undefined} [fallback] + * @returns {Validator} + */ +function string_array(fallback) { + return validate(fallback, (input, keypath) => { + if (!Array.isArray(input) || input.some((value) => typeof value !== 'string')) { + throw new Error(`${keypath} must be an array of strings, if specified`); + } + + return input; + }); +} + +/** + * @param {number} fallback + * @returns {Validator} + */ +function number(fallback) { + return validate(fallback, (input, keypath) => { + if (typeof input !== 'number') { + throw new Error(`${keypath} should be a number, if specified`); + } + return input; + }); +} + +/** + * @param {boolean} fallback + * @returns {Validator} + */ +function boolean(fallback) { + return validate(fallback, (input, keypath) => { + if (typeof input !== 'boolean') { + throw new Error(`${keypath} should be true or false, if specified`); + } + return input; + }); +} + +/** + * @param {string[]} options + * @returns {Validator} + */ +function list(options, fallback = options[0]) { + return validate(fallback, (input, keypath) => { + if (!options.includes(input)) { + // prettier-ignore + const msg = options.length > 2 + ? `${keypath} should be one of ${options.slice(0, -1).map(input => `"${input}"`).join(', ')} or "${options[options.length - 1]}"` + : `${keypath} should be either "${options[0]}" or "${options[1]}"`; + + throw new Error(msg); + } + return input; + }); +} + +/** + * @param {(...args: any) => any} fallback + * @returns {Validator} + */ +function fun(fallback) { + return validate(fallback, (input, keypath) => { + if (typeof input !== 'function') { + throw new Error(`${keypath} should be a function, if specified`); + } + return input; + }); +} + +/** + * @param {string} input + * @param {string} keypath + */ +function assert_string(input, keypath) { + if (typeof input !== 'string') { + throw new Error(`${keypath} should be a string, if specified`); + } +} + +export default options; diff --git a/node_modules/@sveltejs/kit/src/core/config/types.d.ts b/node_modules/@sveltejs/kit/src/core/config/types.d.ts new file mode 100644 index 00000000..00d005c3 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/config/types.d.ts @@ -0,0 +1 @@ +export type Validator = (input: T, keypath: string) => T; diff --git a/node_modules/@sveltejs/kit/src/core/env.js b/node_modules/@sveltejs/kit/src/core/env.js new file mode 100644 index 00000000..455eb0f4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/env.js @@ -0,0 +1,152 @@ +import { GENERATED_COMMENT } from '../constants.js'; +import { dedent } from './sync/utils.js'; +import { runtime_base } from './utils.js'; + +/** + * @typedef {'public' | 'private'} EnvType + */ + +/** + * @param {string} id + * @param {Record} env + * @returns {string} + */ +export function create_static_module(id, env) { + /** @type {string[]} */ + const declarations = []; + + for (const key in env) { + if (!valid_identifier.test(key) || reserved.has(key)) { + continue; + } + + const comment = `/** @type {import('${id}').${key}} */`; + const declaration = `export const ${key} = ${JSON.stringify(env[key])};`; + + declarations.push(`${comment}\n${declaration}`); + } + + return GENERATED_COMMENT + declarations.join('\n\n'); +} + +/** + * @param {EnvType} type + * @param {Record | undefined} dev_values If in a development mode, values to pre-populate the module with. + */ +export function create_dynamic_module(type, dev_values) { + if (dev_values) { + const keys = Object.entries(dev_values).map( + ([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v)}` + ); + return `export const env = {\n${keys.join(',\n')}\n}`; + } + return `export { ${type}_env as env } from '${runtime_base}/shared-server.js';`; +} + +/** + * @param {EnvType} id + * @param {import('types').Env} env + * @returns {string} + */ +export function create_static_types(id, env) { + const declarations = Object.keys(env[id]) + .filter((k) => valid_identifier.test(k)) + .map((k) => `export const ${k}: string;`); + + return dedent` + declare module '$env/static/${id}' { + ${declarations.join('\n')} + } + `; +} + +/** + * @param {EnvType} id + * @param {import('types').Env} env + * @param {{ + * public_prefix: string; + * private_prefix: string; + * }} prefixes + * @returns {string} + */ +export function create_dynamic_types(id, env, { public_prefix, private_prefix }) { + const properties = Object.keys(env[id]) + .filter((k) => valid_identifier.test(k)) + .map((k) => `${k}: string;`); + + const public_prefixed = `[key: \`${public_prefix}\${string}\`]`; + const private_prefixed = `[key: \`${private_prefix}\${string}\`]`; + + if (id === 'private') { + if (public_prefix) { + properties.push(`${public_prefixed}: undefined;`); + } + properties.push(`${private_prefixed}: string | undefined;`); + } else { + if (private_prefix) { + properties.push(`${private_prefixed}: undefined;`); + } + properties.push(`${public_prefixed}: string | undefined;`); + } + + return dedent` + declare module '$env/dynamic/${id}' { + export const env: { + ${properties.join('\n')} + } + } + `; +} + +export const reserved = new Set([ + 'do', + 'if', + 'in', + 'for', + 'let', + 'new', + 'try', + 'var', + 'case', + 'else', + 'enum', + 'eval', + 'null', + 'this', + 'true', + 'void', + 'with', + 'await', + 'break', + 'catch', + 'class', + 'const', + 'false', + 'super', + 'throw', + 'while', + 'yield', + 'delete', + 'export', + 'import', + 'public', + 'return', + 'static', + 'switch', + 'typeof', + 'default', + 'extends', + 'finally', + 'package', + 'private', + 'continue', + 'debugger', + 'function', + 'arguments', + 'interface', + 'protected', + 'implements', + 'instanceof' +]); + +export const valid_identifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/; diff --git a/node_modules/@sveltejs/kit/src/core/generate_manifest/find_server_assets.js b/node_modules/@sveltejs/kit/src/core/generate_manifest/find_server_assets.js new file mode 100644 index 00000000..3a562f4b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/generate_manifest/find_server_assets.js @@ -0,0 +1,52 @@ +import { find_deps } from '../../exports/vite/build/utils.js'; + +/** + * Finds all the assets that are imported by server files associated with `routes` + * @param {import('types').BuildData} build_data + * @param {import('types').RouteData[]} routes + */ +export function find_server_assets(build_data, routes) { + /** + * All nodes actually used in the routes definition (prerendered routes are omitted). + * Root layout/error is always included as they are needed for 404 and root errors. + * @type {Set} + */ + const used_nodes = new Set([0, 1]); + + // TODO add hooks.server.js asset imports + /** @type {Set} */ + const server_assets = new Set(); + + /** @param {string} id */ + function add_assets(id) { + if (id in build_data.server_manifest) { + const deps = find_deps(build_data.server_manifest, id, false); + for (const asset of deps.assets) { + server_assets.add(asset); + } + } + } + + for (const route of routes) { + if (route.page) { + for (const i of route.page.layouts) used_nodes.add(i); + for (const i of route.page.errors) used_nodes.add(i); + used_nodes.add(route.page.leaf); + } + + if (route.endpoint) { + add_assets(route.endpoint.file); + } + } + + for (const n of used_nodes) { + const node = build_data.manifest_data.nodes[n]; + if (node?.server) add_assets(node.server); + } + + if (build_data.manifest_data.hooks.server) { + add_assets(build_data.manifest_data.hooks.server); + } + + return Array.from(server_assets); +} diff --git a/node_modules/@sveltejs/kit/src/core/generate_manifest/index.js b/node_modules/@sveltejs/kit/src/core/generate_manifest/index.js new file mode 100644 index 00000000..a2ef4cd4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/generate_manifest/index.js @@ -0,0 +1,140 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import * as mime from 'mrmime'; +import { s } from '../../utils/misc.js'; +import { get_mime_lookup } from '../utils.js'; +import { resolve_symlinks } from '../../exports/vite/build/utils.js'; +import { compact } from '../../utils/array.js'; +import { join_relative } from '../../utils/filesystem.js'; +import { dedent } from '../sync/utils.js'; +import { find_server_assets } from './find_server_assets.js'; + +/** + * Generates the data used to write the server-side manifest.js file. This data is used in the Vite + * build process, to power routing, etc. + * @param {{ + * build_data: import('types').BuildData; + * relative_path: string; + * routes: import('types').RouteData[]; + * }} opts + */ +export function generate_manifest({ build_data, relative_path, routes }) { + /** + * @type {Map} The new index of each node in the filtered nodes array + */ + const reindexed = new Map(); + /** + * All nodes actually used in the routes definition (prerendered routes are omitted). + * Root layout/error is always included as they are needed for 404 and root errors. + * @type {Set} + */ + const used_nodes = new Set([0, 1]); + + const server_assets = find_server_assets(build_data, routes); + + for (const route of routes) { + if (route.page) { + for (const i of route.page.layouts) used_nodes.add(i); + for (const i of route.page.errors) used_nodes.add(i); + used_nodes.add(route.page.leaf); + } + } + + const node_paths = compact( + build_data.manifest_data.nodes.map((_, i) => { + if (used_nodes.has(i)) { + reindexed.set(i, reindexed.size); + return join_relative(relative_path, `/nodes/${i}.js`); + } + }) + ); + + /** @type {(path: string) => string} */ + const loader = (path) => `__memo(() => import('${path}'))`; + + const assets = build_data.manifest_data.assets.map((asset) => asset.file); + if (build_data.service_worker) { + assets.push(build_data.service_worker); + } + + const matchers = new Set(); + + /** @param {Array} indexes */ + function get_nodes(indexes) { + const string = indexes.map((n) => reindexed.get(n) ?? '').join(','); + + // since JavaScript ignores trailing commas, we need to insert a dummy + // comma so that the array has the correct length if the last item + // is undefined + return `[${string},]`; + } + + const mime_types = get_mime_lookup(build_data.manifest_data); + + /** @type {Record} */ + const files = {}; + for (const file of server_assets) { + files[file] = fs.statSync(path.resolve(build_data.out_dir, 'server', file)).size; + + const ext = path.extname(file); + mime_types[ext] ??= mime.lookup(ext) || ''; + } + + // prettier-ignore + // String representation of + /** @template {import('@sveltejs/kit').SSRManifest} T */ + const manifest_expr = dedent` + { + appDir: ${s(build_data.app_dir)}, + appPath: ${s(build_data.app_path)}, + assets: new Set(${s(assets)}), + mimeTypes: ${s(mime_types)}, + _: { + client: ${s(build_data.client)}, + nodes: [ + ${(node_paths).map(loader).join(',\n')} + ], + routes: [ + ${routes.map(route => { + if (!route.page && !route.endpoint) return; + + route.params.forEach(param => { + if (param.matcher) matchers.add(param.matcher); + }); + + return dedent` + { + id: ${s(route.id)}, + pattern: ${route.pattern}, + params: ${s(route.params)}, + page: ${route.page ? `{ layouts: ${get_nodes(route.page.layouts)}, errors: ${get_nodes(route.page.errors)}, leaf: ${reindexed.get(route.page.leaf)} }` : 'null'}, + endpoint: ${route.endpoint ? loader(join_relative(relative_path, resolve_symlinks(build_data.server_manifest, route.endpoint.file).chunk.file)) : 'null'} + } + `; + }).filter(Boolean).join(',\n')} + ], + matchers: async () => { + ${Array.from( + matchers, + type => `const { match: ${type} } = await import ('${(join_relative(relative_path, `/entries/matchers/${type}.js`))}')` + ).join('\n')} + return { ${Array.from(matchers).join(', ')} }; + }, + server_assets: ${s(files)} + } + } + `; + + // Memoize the loaders to prevent Node from doing unnecessary work + // on every dynamic import call + return dedent` + (() => { + function __memo(fn) { + let value; + return () => value ??= (value = fn()); + } + + return ${manifest_expr} + })() + `; +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/analyse.js b/node_modules/@sveltejs/kit/src/core/postbuild/analyse.js new file mode 100644 index 00000000..1cc92868 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/analyse.js @@ -0,0 +1,243 @@ +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { get_option } from '../../utils/options.js'; +import { + validate_layout_exports, + validate_layout_server_exports, + validate_page_exports, + validate_page_server_exports, + validate_server_exports +} from '../../utils/exports.js'; +import { load_config } from '../config/index.js'; +import { forked } from '../../utils/fork.js'; +import { installPolyfills } from '../../exports/node/polyfills.js'; +import { ENDPOINT_METHODS } from '../../constants.js'; +import { filter_private_env, filter_public_env } from '../../utils/env.js'; +import { resolve_route } from '../../utils/routing.js'; +import { get_page_config } from '../../utils/route_config.js'; +import { check_feature } from '../../utils/features.js'; +import { createReadableStream } from '@sveltejs/kit/node'; + +export default forked(import.meta.url, analyse); + +/** + * @param {{ + * manifest_path: string; + * manifest_data: import('types').ManifestData; + * server_manifest: import('vite').Manifest; + * tracked_features: Record; + * env: Record + * }} opts + */ +async function analyse({ manifest_path, manifest_data, server_manifest, tracked_features, env }) { + /** @type {import('@sveltejs/kit').SSRManifest} */ + const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; + + /** @type {import('types').ValidatedKitConfig} */ + const config = (await load_config()).kit; + + const server_root = join(config.outDir, 'output'); + + /** @type {import('types').ServerInternalModule} */ + const internal = await import(pathToFileURL(`${server_root}/server/internal.js`).href); + + installPolyfills(); + + // configure `import { building } from '$app/environment'` — + // essential we do this before analysing the code + internal.set_building(); + + // set env, in case it's used in initialisation + const { publicPrefix: public_prefix, privatePrefix: private_prefix } = config.env; + const private_env = filter_private_env(env, { public_prefix, private_prefix }); + const public_env = filter_public_env(env, { public_prefix, private_prefix }); + internal.set_private_env(private_env); + internal.set_public_env(public_env); + internal.set_safe_public_env(public_env); + internal.set_manifest(manifest); + internal.set_read_implementation((file) => createReadableStream(`${server_root}/server/${file}`)); + + /** @type {import('types').ServerMetadata} */ + const metadata = { + nodes: [], + routes: new Map() + }; + + const nodes = await Promise.all(manifest._.nodes.map((loader) => loader())); + + // analyse nodes + for (const node of nodes) { + metadata.nodes[node.index] = { + has_server_load: node.server?.load !== undefined || node.server?.trailingSlash !== undefined + }; + } + + // analyse routes + for (const route of manifest._.routes) { + const page = + route.page && + analyse_page( + route.page.layouts.map((n) => (n === undefined ? n : nodes[n])), + nodes[route.page.leaf] + ); + + const endpoint = route.endpoint && analyse_endpoint(route, await route.endpoint()); + + if (page?.prerender && endpoint?.prerender) { + throw new Error(`Cannot prerender a route with both +page and +server files (${route.id})`); + } + + if (page?.config && endpoint?.config) { + for (const key in { ...page.config, ...endpoint.config }) { + if (JSON.stringify(page.config[key]) !== JSON.stringify(endpoint.config[key])) { + throw new Error( + `Mismatched route config for ${route.id} — the +page and +server files must export the same config, if any` + ); + } + } + } + + const route_config = page?.config ?? endpoint?.config ?? {}; + const prerender = page?.prerender ?? endpoint?.prerender; + + if (prerender !== true) { + for (const feature of list_features( + route, + manifest_data, + server_manifest, + tracked_features + )) { + check_feature(route.id, route_config, feature, config.adapter); + } + } + + const page_methods = page?.methods ?? []; + const api_methods = endpoint?.methods ?? []; + const entries = page?.entries ?? endpoint?.entries; + + metadata.routes.set(route.id, { + config: route_config, + methods: Array.from(new Set([...page_methods, ...api_methods])), + page: { + methods: page_methods + }, + api: { + methods: api_methods + }, + prerender, + entries: + entries && (await entries()).map((entry_object) => resolve_route(route.id, entry_object)) + }); + } + + return metadata; +} + +/** + * @param {import('types').SSRRoute} route + * @param {import('types').SSREndpoint} mod + */ +function analyse_endpoint(route, mod) { + validate_server_exports(mod, route.id); + + if (mod.prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) { + throw new Error( + `Cannot prerender a +server file with POST, PATCH, PUT, or DELETE (${route.id})` + ); + } + + /** @type {Array} */ + const methods = []; + + for (const method of /** @type {import('types').HttpMethod[]} */ (ENDPOINT_METHODS)) { + if (mod[method]) methods.push(method); + } + + if (mod.fallback) { + methods.push('*'); + } + + return { + config: mod.config, + entries: mod.entries, + methods, + prerender: mod.prerender ?? false + }; +} + +/** + * @param {Array} layouts + * @param {import('types').SSRNode} leaf + */ +function analyse_page(layouts, leaf) { + for (const layout of layouts) { + if (layout) { + validate_layout_server_exports(layout.server, layout.server_id); + validate_layout_exports(layout.universal, layout.universal_id); + } + } + + /** @type {Array<'GET' | 'POST'>} */ + const methods = ['GET']; + if (leaf.server?.actions) methods.push('POST'); + + validate_page_server_exports(leaf.server, leaf.server_id); + validate_page_exports(leaf.universal, leaf.universal_id); + + return { + config: get_page_config([...layouts, leaf]), + entries: leaf.universal?.entries ?? leaf.server?.entries, + methods, + prerender: get_option([...layouts, leaf], 'prerender') ?? false + }; +} + +/** + * @param {import('types').SSRRoute} route + * @param {import('types').ManifestData} manifest_data + * @param {import('vite').Manifest} server_manifest + * @param {Record} tracked_features + */ +function list_features(route, manifest_data, server_manifest, tracked_features) { + const features = new Set(); + + const route_data = /** @type {import('types').RouteData} */ ( + manifest_data.routes.find((r) => r.id === route.id) + ); + + /** @param {string} id */ + function visit(id) { + const chunk = server_manifest[id]; + if (!chunk) return; + + if (chunk.file in tracked_features) { + for (const feature of tracked_features[chunk.file]) { + features.add(feature); + } + } + + if (chunk.imports) { + for (const id of chunk.imports) { + visit(id); + } + } + } + + let page_node = route_data?.leaf; + while (page_node) { + if (page_node.server) visit(page_node.server); + page_node = page_node.parent ?? null; + } + + if (route_data.endpoint) { + visit(route_data.endpoint.file); + } + + if (manifest_data.hooks.server) { + // TODO if hooks.server.js imports `read`, it will be in the entry chunk + // we don't currently account for that case + visit(manifest_data.hooks.server); + } + + return Array.from(features); +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/crawl.js b/node_modules/@sveltejs/kit/src/core/postbuild/crawl.js new file mode 100644 index 00000000..caffef58 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/crawl.js @@ -0,0 +1,243 @@ +import { resolve } from '../../utils/url.js'; +import { decode } from './entities.js'; + +const DOCTYPE = 'DOCTYPE'; +const CDATA_OPEN = '[CDATA['; +const CDATA_CLOSE = ']]>'; +const COMMENT_OPEN = '--'; +const COMMENT_CLOSE = '-->'; + +const TAG_OPEN = /[a-zA-Z]/; +const TAG_CHAR = /[a-zA-Z0-9]/; +const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/; + +const WHITESPACE = /[\s\n\r]/; + +const CRAWLABLE_META_NAME_ATTRS = new Set([ + 'og:url', + 'og:image', + 'og:image:url', + 'og:image:secure_url', + 'og:video', + 'og:video:url', + 'og:video:secure_url', + 'og:audio', + 'og:audio:url', + 'og:audio:secure_url', + 'twitter:image' +]); + +/** + * @param {string} html + * @param {string} base + */ +export function crawl(html, base) { + /** @type {string[]} */ + const ids = []; + + /** @type {string[]} */ + const hrefs = []; + + let i = 0; + main: while (i < html.length) { + const char = html[i]; + + if (char === '<') { + if (html[i + 1] === '!') { + i += 2; + + if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) { + i += DOCTYPE.length; + while (i < html.length) { + if (html[i++] === '>') { + continue main; + } + } + } + + // skip cdata + if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) { + i += CDATA_OPEN.length; + while (i < html.length) { + if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) { + i += CDATA_CLOSE.length; + continue main; + } + + i += 1; + } + } + + // skip comments + if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) { + i += COMMENT_OPEN.length; + while (i < html.length) { + if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) { + i += COMMENT_CLOSE.length; + continue main; + } + + i += 1; + } + } + } + + // parse opening tags + const start = ++i; + if (TAG_OPEN.test(html[start])) { + while (i < html.length) { + if (!TAG_CHAR.test(html[i])) { + break; + } + + i += 1; + } + + const tag = html.slice(start, i).toUpperCase(); + + /** @type {Record} */ + const attributes = {}; + + if (tag === 'SCRIPT' || tag === 'STYLE') { + while (i < html.length) { + if ( + html[i] === '<' && + html[i + 1] === '/' && + html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag + ) { + continue main; + } + + i += 1; + } + } + + while (i < html.length) { + const start = i; + + const char = html[start]; + if (char === '>') break; + + if (ATTRIBUTE_NAME.test(char)) { + i += 1; + + while (i < html.length) { + if (!ATTRIBUTE_NAME.test(html[i])) { + break; + } + + i += 1; + } + + const name = html.slice(start, i).toLowerCase(); + + while (WHITESPACE.test(html[i])) i += 1; + + if (html[i] === '=') { + i += 1; + while (WHITESPACE.test(html[i])) i += 1; + + let value; + + if (html[i] === "'" || html[i] === '"') { + const quote = html[i++]; + + const start = i; + let escaped = false; + + while (i < html.length) { + if (escaped) { + escaped = false; + } else { + const char = html[i]; + + if (html[i] === quote) { + break; + } + + if (char === '\\') { + escaped = true; + } + } + + i += 1; + } + + value = html.slice(start, i); + } else { + const start = i; + while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1; + value = html.slice(start, i); + + i -= 1; + } + + value = decode(value); + attributes[name] = value; + } else { + i -= 1; + } + } + + i += 1; + } + + const { href, id, name, property, rel, src, srcset, content } = attributes; + + if (href) { + if (tag === 'BASE') { + base = resolve(base, href); + } else if (!rel || !/\bexternal\b/i.test(rel)) { + hrefs.push(resolve(base, href)); + } + } + + if (id) { + ids.push(id); + } + + if (name && tag === 'A') { + ids.push(name); + } + + if (src) { + hrefs.push(resolve(base, src)); + } + + if (srcset) { + let value = srcset; + const candidates = []; + let insideURL = true; + value = value.trim(); + for (let i = 0; i < value.length; i++) { + if (value[i] === ',' && (!insideURL || (insideURL && WHITESPACE.test(value[i + 1])))) { + candidates.push(value.slice(0, i)); + value = value.substring(i + 1).trim(); + i = 0; + insideURL = true; + } else if (WHITESPACE.test(value[i])) { + insideURL = false; + } + } + candidates.push(value); + for (const candidate of candidates) { + const src = candidate.split(WHITESPACE)[0]; + if (src) hrefs.push(resolve(base, src)); + } + } + + if (tag === 'META' && content) { + const attr = name ?? property; + + if (attr && CRAWLABLE_META_NAME_ATTRS.has(attr)) { + hrefs.push(resolve(base, content)); + } + } + } + } + + i += 1; + } + + return { ids, hrefs }; +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/entities.js b/node_modules/@sveltejs/kit/src/core/postbuild/entities.js new file mode 100644 index 00000000..91888a95 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/entities.js @@ -0,0 +1,2252 @@ +/** + * A list of all named HTML entities, from https://html.spec.whatwg.org/multipage/named-characters.html + * @type {Record} + */ +const entities = { + AElig: 'Æ', + 'AElig;': 'Æ', + AMP: '&', + 'AMP;': '&', + Aacute: 'Á', + 'Aacute;': 'Á', + 'Abreve;': 'Ă', + Acirc: 'Â', + 'Acirc;': 'Â', + 'Acy;': 'А', + 'Afr;': '𝔄', + Agrave: 'À', + 'Agrave;': 'À', + 'Alpha;': 'Α', + 'Amacr;': 'Ā', + 'And;': '⩓', + 'Aogon;': 'Ą', + 'Aopf;': '𝔸', + 'ApplyFunction;': '⁡', + Aring: 'Å', + 'Aring;': 'Å', + 'Ascr;': '𝒜', + 'Assign;': '≔', + Atilde: 'Ã', + 'Atilde;': 'Ã', + Auml: 'Ä', + 'Auml;': 'Ä', + 'Backslash;': '∖', + 'Barv;': '⫧', + 'Barwed;': '⌆', + 'Bcy;': 'Б', + 'Because;': '∵', + 'Bernoullis;': 'ℬ', + 'Beta;': 'Β', + 'Bfr;': '𝔅', + 'Bopf;': '𝔹', + 'Breve;': '˘', + 'Bscr;': 'ℬ', + 'Bumpeq;': '≎', + 'CHcy;': 'Ч', + COPY: '©', + 'COPY;': '©', + 'Cacute;': 'Ć', + 'Cap;': '⋒', + 'CapitalDifferentialD;': 'ⅅ', + 'Cayleys;': 'ℭ', + 'Ccaron;': 'Č', + Ccedil: 'Ç', + 'Ccedil;': 'Ç', + 'Ccirc;': 'Ĉ', + 'Cconint;': '∰', + 'Cdot;': 'Ċ', + 'Cedilla;': '¸', + 'CenterDot;': '·', + 'Cfr;': 'ℭ', + 'Chi;': 'Χ', + 'CircleDot;': '⊙', + 'CircleMinus;': '⊖', + 'CirclePlus;': '⊕', + 'CircleTimes;': '⊗', + 'ClockwiseContourIntegral;': '∲', + 'CloseCurlyDoubleQuote;': '”', + 'CloseCurlyQuote;': '’', + 'Colon;': '∷', + 'Colone;': '⩴', + 'Congruent;': '≡', + 'Conint;': '∯', + 'ContourIntegral;': '∮', + 'Copf;': 'ℂ', + 'Coproduct;': '∐', + 'CounterClockwiseContourIntegral;': '∳', + 'Cross;': '⨯', + 'Cscr;': '𝒞', + 'Cup;': '⋓', + 'CupCap;': '≍', + 'DD;': 'ⅅ', + 'DDotrahd;': '⤑', + 'DJcy;': 'Ђ', + 'DScy;': 'Ѕ', + 'DZcy;': 'Џ', + 'Dagger;': '‡', + 'Darr;': '↡', + 'Dashv;': '⫤', + 'Dcaron;': 'Ď', + 'Dcy;': 'Д', + 'Del;': '∇', + 'Delta;': 'Δ', + 'Dfr;': '𝔇', + 'DiacriticalAcute;': '´', + 'DiacriticalDot;': '˙', + 'DiacriticalDoubleAcute;': '˝', + 'DiacriticalGrave;': '`', + 'DiacriticalTilde;': '˜', + 'Diamond;': '⋄', + 'DifferentialD;': 'ⅆ', + 'Dopf;': '𝔻', + 'Dot;': '¨', + 'DotDot;': '⃜', + 'DotEqual;': '≐', + 'DoubleContourIntegral;': '∯', + 'DoubleDot;': '¨', + 'DoubleDownArrow;': '⇓', + 'DoubleLeftArrow;': '⇐', + 'DoubleLeftRightArrow;': '⇔', + 'DoubleLeftTee;': '⫤', + 'DoubleLongLeftArrow;': '⟸', + 'DoubleLongLeftRightArrow;': '⟺', + 'DoubleLongRightArrow;': '⟹', + 'DoubleRightArrow;': '⇒', + 'DoubleRightTee;': '⊨', + 'DoubleUpArrow;': '⇑', + 'DoubleUpDownArrow;': '⇕', + 'DoubleVerticalBar;': '∥', + 'DownArrow;': '↓', + 'DownArrowBar;': '⤓', + 'DownArrowUpArrow;': '⇵', + 'DownBreve;': '̑', + 'DownLeftRightVector;': '⥐', + 'DownLeftTeeVector;': '⥞', + 'DownLeftVector;': '↽', + 'DownLeftVectorBar;': '⥖', + 'DownRightTeeVector;': '⥟', + 'DownRightVector;': '⇁', + 'DownRightVectorBar;': '⥗', + 'DownTee;': '⊤', + 'DownTeeArrow;': '↧', + 'Downarrow;': '⇓', + 'Dscr;': '𝒟', + 'Dstrok;': 'Đ', + 'ENG;': 'Ŋ', + ETH: 'Ð', + 'ETH;': 'Ð', + Eacute: 'É', + 'Eacute;': 'É', + 'Ecaron;': 'Ě', + Ecirc: 'Ê', + 'Ecirc;': 'Ê', + 'Ecy;': 'Э', + 'Edot;': 'Ė', + 'Efr;': '𝔈', + Egrave: 'È', + 'Egrave;': 'È', + 'Element;': '∈', + 'Emacr;': 'Ē', + 'EmptySmallSquare;': '◻', + 'EmptyVerySmallSquare;': '▫', + 'Eogon;': 'Ę', + 'Eopf;': '𝔼', + 'Epsilon;': 'Ε', + 'Equal;': '⩵', + 'EqualTilde;': '≂', + 'Equilibrium;': '⇌', + 'Escr;': 'ℰ', + 'Esim;': '⩳', + 'Eta;': 'Η', + Euml: 'Ë', + 'Euml;': 'Ë', + 'Exists;': '∃', + 'ExponentialE;': 'ⅇ', + 'Fcy;': 'Ф', + 'Ffr;': '𝔉', + 'FilledSmallSquare;': '◼', + 'FilledVerySmallSquare;': '▪', + 'Fopf;': '𝔽', + 'ForAll;': '∀', + 'Fouriertrf;': 'ℱ', + 'Fscr;': 'ℱ', + 'GJcy;': 'Ѓ', + GT: '>', + 'GT;': '>', + 'Gamma;': 'Γ', + 'Gammad;': 'Ϝ', + 'Gbreve;': 'Ğ', + 'Gcedil;': 'Ģ', + 'Gcirc;': 'Ĝ', + 'Gcy;': 'Г', + 'Gdot;': 'Ġ', + 'Gfr;': '𝔊', + 'Gg;': '⋙', + 'Gopf;': '𝔾', + 'GreaterEqual;': '≥', + 'GreaterEqualLess;': '⋛', + 'GreaterFullEqual;': '≧', + 'GreaterGreater;': '⪢', + 'GreaterLess;': '≷', + 'GreaterSlantEqual;': '⩾', + 'GreaterTilde;': '≳', + 'Gscr;': '𝒢', + 'Gt;': '≫', + 'HARDcy;': 'Ъ', + 'Hacek;': 'ˇ', + 'Hat;': '^', + 'Hcirc;': 'Ĥ', + 'Hfr;': 'ℌ', + 'HilbertSpace;': 'ℋ', + 'Hopf;': 'ℍ', + 'HorizontalLine;': '─', + 'Hscr;': 'ℋ', + 'Hstrok;': 'Ħ', + 'HumpDownHump;': '≎', + 'HumpEqual;': '≏', + 'IEcy;': 'Е', + 'IJlig;': 'IJ', + 'IOcy;': 'Ё', + Iacute: 'Í', + 'Iacute;': 'Í', + Icirc: 'Î', + 'Icirc;': 'Î', + 'Icy;': 'И', + 'Idot;': 'İ', + 'Ifr;': 'ℑ', + Igrave: 'Ì', + 'Igrave;': 'Ì', + 'Im;': 'ℑ', + 'Imacr;': 'Ī', + 'ImaginaryI;': 'ⅈ', + 'Implies;': '⇒', + 'Int;': '∬', + 'Integral;': '∫', + 'Intersection;': '⋂', + 'InvisibleComma;': '⁣', + 'InvisibleTimes;': '⁢', + 'Iogon;': 'Į', + 'Iopf;': '𝕀', + 'Iota;': 'Ι', + 'Iscr;': 'ℐ', + 'Itilde;': 'Ĩ', + 'Iukcy;': 'І', + Iuml: 'Ï', + 'Iuml;': 'Ï', + 'Jcirc;': 'Ĵ', + 'Jcy;': 'Й', + 'Jfr;': '𝔍', + 'Jopf;': '𝕁', + 'Jscr;': '𝒥', + 'Jsercy;': 'Ј', + 'Jukcy;': 'Є', + 'KHcy;': 'Х', + 'KJcy;': 'Ќ', + 'Kappa;': 'Κ', + 'Kcedil;': 'Ķ', + 'Kcy;': 'К', + 'Kfr;': '𝔎', + 'Kopf;': '𝕂', + 'Kscr;': '𝒦', + 'LJcy;': 'Љ', + LT: '<', + 'LT;': '<', + 'Lacute;': 'Ĺ', + 'Lambda;': 'Λ', + 'Lang;': '⟪', + 'Laplacetrf;': 'ℒ', + 'Larr;': '↞', + 'Lcaron;': 'Ľ', + 'Lcedil;': 'Ļ', + 'Lcy;': 'Л', + 'LeftAngleBracket;': '⟨', + 'LeftArrow;': '←', + 'LeftArrowBar;': '⇤', + 'LeftArrowRightArrow;': '⇆', + 'LeftCeiling;': '⌈', + 'LeftDoubleBracket;': '⟦', + 'LeftDownTeeVector;': '⥡', + 'LeftDownVector;': '⇃', + 'LeftDownVectorBar;': '⥙', + 'LeftFloor;': '⌊', + 'LeftRightArrow;': '↔', + 'LeftRightVector;': '⥎', + 'LeftTee;': '⊣', + 'LeftTeeArrow;': '↤', + 'LeftTeeVector;': '⥚', + 'LeftTriangle;': '⊲', + 'LeftTriangleBar;': '⧏', + 'LeftTriangleEqual;': '⊴', + 'LeftUpDownVector;': '⥑', + 'LeftUpTeeVector;': '⥠', + 'LeftUpVector;': '↿', + 'LeftUpVectorBar;': '⥘', + 'LeftVector;': '↼', + 'LeftVectorBar;': '⥒', + 'Leftarrow;': '⇐', + 'Leftrightarrow;': '⇔', + 'LessEqualGreater;': '⋚', + 'LessFullEqual;': '≦', + 'LessGreater;': '≶', + 'LessLess;': '⪡', + 'LessSlantEqual;': '⩽', + 'LessTilde;': '≲', + 'Lfr;': '𝔏', + 'Ll;': '⋘', + 'Lleftarrow;': '⇚', + 'Lmidot;': 'Ŀ', + 'LongLeftArrow;': '⟵', + 'LongLeftRightArrow;': '⟷', + 'LongRightArrow;': '⟶', + 'Longleftarrow;': '⟸', + 'Longleftrightarrow;': '⟺', + 'Longrightarrow;': '⟹', + 'Lopf;': '𝕃', + 'LowerLeftArrow;': '↙', + 'LowerRightArrow;': '↘', + 'Lscr;': 'ℒ', + 'Lsh;': '↰', + 'Lstrok;': 'Ł', + 'Lt;': '≪', + 'Map;': '⤅', + 'Mcy;': 'М', + 'MediumSpace;': ' ', + 'Mellintrf;': 'ℳ', + 'Mfr;': '𝔐', + 'MinusPlus;': '∓', + 'Mopf;': '𝕄', + 'Mscr;': 'ℳ', + 'Mu;': 'Μ', + 'NJcy;': 'Њ', + 'Nacute;': 'Ń', + 'Ncaron;': 'Ň', + 'Ncedil;': 'Ņ', + 'Ncy;': 'Н', + 'NegativeMediumSpace;': '​', + 'NegativeThickSpace;': '​', + 'NegativeThinSpace;': '​', + 'NegativeVeryThinSpace;': '​', + 'NestedGreaterGreater;': '≫', + 'NestedLessLess;': '≪', + 'NewLine;': '\n', + 'Nfr;': '𝔑', + 'NoBreak;': '⁠', + 'NonBreakingSpace;': ' ', + 'Nopf;': 'ℕ', + 'Not;': '⫬', + 'NotCongruent;': '≢', + 'NotCupCap;': '≭', + 'NotDoubleVerticalBar;': '∦', + 'NotElement;': '∉', + 'NotEqual;': '≠', + 'NotEqualTilde;': '≂̸', + 'NotExists;': '∄', + 'NotGreater;': '≯', + 'NotGreaterEqual;': '≱', + 'NotGreaterFullEqual;': '≧̸', + 'NotGreaterGreater;': '≫̸', + 'NotGreaterLess;': '≹', + 'NotGreaterSlantEqual;': '⩾̸', + 'NotGreaterTilde;': '≵', + 'NotHumpDownHump;': '≎̸', + 'NotHumpEqual;': '≏̸', + 'NotLeftTriangle;': '⋪', + 'NotLeftTriangleBar;': '⧏̸', + 'NotLeftTriangleEqual;': '⋬', + 'NotLess;': '≮', + 'NotLessEqual;': '≰', + 'NotLessGreater;': '≸', + 'NotLessLess;': '≪̸', + 'NotLessSlantEqual;': '⩽̸', + 'NotLessTilde;': '≴', + 'NotNestedGreaterGreater;': '⪢̸', + 'NotNestedLessLess;': '⪡̸', + 'NotPrecedes;': '⊀', + 'NotPrecedesEqual;': '⪯̸', + 'NotPrecedesSlantEqual;': '⋠', + 'NotReverseElement;': '∌', + 'NotRightTriangle;': '⋫', + 'NotRightTriangleBar;': '⧐̸', + 'NotRightTriangleEqual;': '⋭', + 'NotSquareSubset;': '⊏̸', + 'NotSquareSubsetEqual;': '⋢', + 'NotSquareSuperset;': '⊐̸', + 'NotSquareSupersetEqual;': '⋣', + 'NotSubset;': '⊂⃒', + 'NotSubsetEqual;': '⊈', + 'NotSucceeds;': '⊁', + 'NotSucceedsEqual;': '⪰̸', + 'NotSucceedsSlantEqual;': '⋡', + 'NotSucceedsTilde;': '≿̸', + 'NotSuperset;': '⊃⃒', + 'NotSupersetEqual;': '⊉', + 'NotTilde;': '≁', + 'NotTildeEqual;': '≄', + 'NotTildeFullEqual;': '≇', + 'NotTildeTilde;': '≉', + 'NotVerticalBar;': '∤', + 'Nscr;': '𝒩', + Ntilde: 'Ñ', + 'Ntilde;': 'Ñ', + 'Nu;': 'Ν', + 'OElig;': 'Œ', + Oacute: 'Ó', + 'Oacute;': 'Ó', + Ocirc: 'Ô', + 'Ocirc;': 'Ô', + 'Ocy;': 'О', + 'Odblac;': 'Ő', + 'Ofr;': '𝔒', + Ograve: 'Ò', + 'Ograve;': 'Ò', + 'Omacr;': 'Ō', + 'Omega;': 'Ω', + 'Omicron;': 'Ο', + 'Oopf;': '𝕆', + 'OpenCurlyDoubleQuote;': '“', + 'OpenCurlyQuote;': '‘', + 'Or;': '⩔', + 'Oscr;': '𝒪', + Oslash: 'Ø', + 'Oslash;': 'Ø', + Otilde: 'Õ', + 'Otilde;': 'Õ', + 'Otimes;': '⨷', + Ouml: 'Ö', + 'Ouml;': 'Ö', + 'OverBar;': '‾', + 'OverBrace;': '⏞', + 'OverBracket;': '⎴', + 'OverParenthesis;': '⏜', + 'PartialD;': '∂', + 'Pcy;': 'П', + 'Pfr;': '𝔓', + 'Phi;': 'Φ', + 'Pi;': 'Π', + 'PlusMinus;': '±', + 'Poincareplane;': 'ℌ', + 'Popf;': 'ℙ', + 'Pr;': '⪻', + 'Precedes;': '≺', + 'PrecedesEqual;': '⪯', + 'PrecedesSlantEqual;': '≼', + 'PrecedesTilde;': '≾', + 'Prime;': '″', + 'Product;': '∏', + 'Proportion;': '∷', + 'Proportional;': '∝', + 'Pscr;': '𝒫', + 'Psi;': 'Ψ', + QUOT: '"', + 'QUOT;': '"', + 'Qfr;': '𝔔', + 'Qopf;': 'ℚ', + 'Qscr;': '𝒬', + 'RBarr;': '⤐', + REG: '®', + 'REG;': '®', + 'Racute;': 'Ŕ', + 'Rang;': '⟫', + 'Rarr;': '↠', + 'Rarrtl;': '⤖', + 'Rcaron;': 'Ř', + 'Rcedil;': 'Ŗ', + 'Rcy;': 'Р', + 'Re;': 'ℜ', + 'ReverseElement;': '∋', + 'ReverseEquilibrium;': '⇋', + 'ReverseUpEquilibrium;': '⥯', + 'Rfr;': 'ℜ', + 'Rho;': 'Ρ', + 'RightAngleBracket;': '⟩', + 'RightArrow;': '→', + 'RightArrowBar;': '⇥', + 'RightArrowLeftArrow;': '⇄', + 'RightCeiling;': '⌉', + 'RightDoubleBracket;': '⟧', + 'RightDownTeeVector;': '⥝', + 'RightDownVector;': '⇂', + 'RightDownVectorBar;': '⥕', + 'RightFloor;': '⌋', + 'RightTee;': '⊢', + 'RightTeeArrow;': '↦', + 'RightTeeVector;': '⥛', + 'RightTriangle;': '⊳', + 'RightTriangleBar;': '⧐', + 'RightTriangleEqual;': '⊵', + 'RightUpDownVector;': '⥏', + 'RightUpTeeVector;': '⥜', + 'RightUpVector;': '↾', + 'RightUpVectorBar;': '⥔', + 'RightVector;': '⇀', + 'RightVectorBar;': '⥓', + 'Rightarrow;': '⇒', + 'Ropf;': 'ℝ', + 'RoundImplies;': '⥰', + 'Rrightarrow;': '⇛', + 'Rscr;': 'ℛ', + 'Rsh;': '↱', + 'RuleDelayed;': '⧴', + 'SHCHcy;': 'Щ', + 'SHcy;': 'Ш', + 'SOFTcy;': 'Ь', + 'Sacute;': 'Ś', + 'Sc;': '⪼', + 'Scaron;': 'Š', + 'Scedil;': 'Ş', + 'Scirc;': 'Ŝ', + 'Scy;': 'С', + 'Sfr;': '𝔖', + 'ShortDownArrow;': '↓', + 'ShortLeftArrow;': '←', + 'ShortRightArrow;': '→', + 'ShortUpArrow;': '↑', + 'Sigma;': 'Σ', + 'SmallCircle;': '∘', + 'Sopf;': '𝕊', + 'Sqrt;': '√', + 'Square;': '□', + 'SquareIntersection;': '⊓', + 'SquareSubset;': '⊏', + 'SquareSubsetEqual;': '⊑', + 'SquareSuperset;': '⊐', + 'SquareSupersetEqual;': '⊒', + 'SquareUnion;': '⊔', + 'Sscr;': '𝒮', + 'Star;': '⋆', + 'Sub;': '⋐', + 'Subset;': '⋐', + 'SubsetEqual;': '⊆', + 'Succeeds;': '≻', + 'SucceedsEqual;': '⪰', + 'SucceedsSlantEqual;': '≽', + 'SucceedsTilde;': '≿', + 'SuchThat;': '∋', + 'Sum;': '∑', + 'Sup;': '⋑', + 'Superset;': '⊃', + 'SupersetEqual;': '⊇', + 'Supset;': '⋑', + THORN: 'Þ', + 'THORN;': 'Þ', + 'TRADE;': '™', + 'TSHcy;': 'Ћ', + 'TScy;': 'Ц', + 'Tab;': '\t', + 'Tau;': 'Τ', + 'Tcaron;': 'Ť', + 'Tcedil;': 'Ţ', + 'Tcy;': 'Т', + 'Tfr;': '𝔗', + 'Therefore;': '∴', + 'Theta;': 'Θ', + 'ThickSpace;': '  ', + 'ThinSpace;': ' ', + 'Tilde;': '∼', + 'TildeEqual;': '≃', + 'TildeFullEqual;': '≅', + 'TildeTilde;': '≈', + 'Topf;': '𝕋', + 'TripleDot;': '⃛', + 'Tscr;': '𝒯', + 'Tstrok;': 'Ŧ', + Uacute: 'Ú', + 'Uacute;': 'Ú', + 'Uarr;': '↟', + 'Uarrocir;': '⥉', + 'Ubrcy;': 'Ў', + 'Ubreve;': 'Ŭ', + Ucirc: 'Û', + 'Ucirc;': 'Û', + 'Ucy;': 'У', + 'Udblac;': 'Ű', + 'Ufr;': '𝔘', + Ugrave: 'Ù', + 'Ugrave;': 'Ù', + 'Umacr;': 'Ū', + 'UnderBar;': '_', + 'UnderBrace;': '⏟', + 'UnderBracket;': '⎵', + 'UnderParenthesis;': '⏝', + 'Union;': '⋃', + 'UnionPlus;': '⊎', + 'Uogon;': 'Ų', + 'Uopf;': '𝕌', + 'UpArrow;': '↑', + 'UpArrowBar;': '⤒', + 'UpArrowDownArrow;': '⇅', + 'UpDownArrow;': '↕', + 'UpEquilibrium;': '⥮', + 'UpTee;': '⊥', + 'UpTeeArrow;': '↥', + 'Uparrow;': '⇑', + 'Updownarrow;': '⇕', + 'UpperLeftArrow;': '↖', + 'UpperRightArrow;': '↗', + 'Upsi;': 'ϒ', + 'Upsilon;': 'Υ', + 'Uring;': 'Ů', + 'Uscr;': '𝒰', + 'Utilde;': 'Ũ', + Uuml: 'Ü', + 'Uuml;': 'Ü', + 'VDash;': '⊫', + 'Vbar;': '⫫', + 'Vcy;': 'В', + 'Vdash;': '⊩', + 'Vdashl;': '⫦', + 'Vee;': '⋁', + 'Verbar;': '‖', + 'Vert;': '‖', + 'VerticalBar;': '∣', + 'VerticalLine;': '|', + 'VerticalSeparator;': '❘', + 'VerticalTilde;': '≀', + 'VeryThinSpace;': ' ', + 'Vfr;': '𝔙', + 'Vopf;': '𝕍', + 'Vscr;': '𝒱', + 'Vvdash;': '⊪', + 'Wcirc;': 'Ŵ', + 'Wedge;': '⋀', + 'Wfr;': '𝔚', + 'Wopf;': '𝕎', + 'Wscr;': '𝒲', + 'Xfr;': '𝔛', + 'Xi;': 'Ξ', + 'Xopf;': '𝕏', + 'Xscr;': '𝒳', + 'YAcy;': 'Я', + 'YIcy;': 'Ї', + 'YUcy;': 'Ю', + Yacute: 'Ý', + 'Yacute;': 'Ý', + 'Ycirc;': 'Ŷ', + 'Ycy;': 'Ы', + 'Yfr;': '𝔜', + 'Yopf;': '𝕐', + 'Yscr;': '𝒴', + 'Yuml;': 'Ÿ', + 'ZHcy;': 'Ж', + 'Zacute;': 'Ź', + 'Zcaron;': 'Ž', + 'Zcy;': 'З', + 'Zdot;': 'Ż', + 'ZeroWidthSpace;': '​', + 'Zeta;': 'Ζ', + 'Zfr;': 'ℨ', + 'Zopf;': 'ℤ', + 'Zscr;': '𝒵', + aacute: 'á', + 'aacute;': 'á', + 'abreve;': 'ă', + 'ac;': '∾', + 'acE;': '∾̳', + 'acd;': '∿', + acirc: 'â', + 'acirc;': 'â', + acute: '´', + 'acute;': '´', + 'acy;': 'а', + aelig: 'æ', + 'aelig;': 'æ', + 'af;': '⁡', + 'afr;': '𝔞', + agrave: 'à', + 'agrave;': 'à', + 'alefsym;': 'ℵ', + 'aleph;': 'ℵ', + 'alpha;': 'α', + 'amacr;': 'ā', + 'amalg;': '⨿', + amp: '&', + 'amp;': '&', + 'and;': '∧', + 'andand;': '⩕', + 'andd;': '⩜', + 'andslope;': '⩘', + 'andv;': '⩚', + 'ang;': '∠', + 'ange;': '⦤', + 'angle;': '∠', + 'angmsd;': '∡', + 'angmsdaa;': '⦨', + 'angmsdab;': '⦩', + 'angmsdac;': '⦪', + 'angmsdad;': '⦫', + 'angmsdae;': '⦬', + 'angmsdaf;': '⦭', + 'angmsdag;': '⦮', + 'angmsdah;': '⦯', + 'angrt;': '∟', + 'angrtvb;': '⊾', + 'angrtvbd;': '⦝', + 'angsph;': '∢', + 'angst;': 'Å', + 'angzarr;': '⍼', + 'aogon;': 'ą', + 'aopf;': '𝕒', + 'ap;': '≈', + 'apE;': '⩰', + 'apacir;': '⩯', + 'ape;': '≊', + 'apid;': '≋', + 'apos;': "'", + 'approx;': '≈', + 'approxeq;': '≊', + aring: 'å', + 'aring;': 'å', + 'ascr;': '𝒶', + 'ast;': '*', + 'asymp;': '≈', + 'asympeq;': '≍', + atilde: 'ã', + 'atilde;': 'ã', + auml: 'ä', + 'auml;': 'ä', + 'awconint;': '∳', + 'awint;': '⨑', + 'bNot;': '⫭', + 'backcong;': '≌', + 'backepsilon;': '϶', + 'backprime;': '‵', + 'backsim;': '∽', + 'backsimeq;': '⋍', + 'barvee;': '⊽', + 'barwed;': '⌅', + 'barwedge;': '⌅', + 'bbrk;': '⎵', + 'bbrktbrk;': '⎶', + 'bcong;': '≌', + 'bcy;': 'б', + 'bdquo;': '„', + 'becaus;': '∵', + 'because;': '∵', + 'bemptyv;': '⦰', + 'bepsi;': '϶', + 'bernou;': 'ℬ', + 'beta;': 'β', + 'beth;': 'ℶ', + 'between;': '≬', + 'bfr;': '𝔟', + 'bigcap;': '⋂', + 'bigcirc;': '◯', + 'bigcup;': '⋃', + 'bigodot;': '⨀', + 'bigoplus;': '⨁', + 'bigotimes;': '⨂', + 'bigsqcup;': '⨆', + 'bigstar;': '★', + 'bigtriangledown;': '▽', + 'bigtriangleup;': '△', + 'biguplus;': '⨄', + 'bigvee;': '⋁', + 'bigwedge;': '⋀', + 'bkarow;': '⤍', + 'blacklozenge;': '⧫', + 'blacksquare;': '▪', + 'blacktriangle;': '▴', + 'blacktriangledown;': '▾', + 'blacktriangleleft;': '◂', + 'blacktriangleright;': '▸', + 'blank;': '␣', + 'blk12;': '▒', + 'blk14;': '░', + 'blk34;': '▓', + 'block;': '█', + 'bne;': '=⃥', + 'bnequiv;': '≡⃥', + 'bnot;': '⌐', + 'bopf;': '𝕓', + 'bot;': '⊥', + 'bottom;': '⊥', + 'bowtie;': '⋈', + 'boxDL;': '╗', + 'boxDR;': '╔', + 'boxDl;': '╖', + 'boxDr;': '╓', + 'boxH;': '═', + 'boxHD;': '╦', + 'boxHU;': '╩', + 'boxHd;': '╤', + 'boxHu;': '╧', + 'boxUL;': '╝', + 'boxUR;': '╚', + 'boxUl;': '╜', + 'boxUr;': '╙', + 'boxV;': '║', + 'boxVH;': '╬', + 'boxVL;': '╣', + 'boxVR;': '╠', + 'boxVh;': '╫', + 'boxVl;': '╢', + 'boxVr;': '╟', + 'boxbox;': '⧉', + 'boxdL;': '╕', + 'boxdR;': '╒', + 'boxdl;': '┐', + 'boxdr;': '┌', + 'boxh;': '─', + 'boxhD;': '╥', + 'boxhU;': '╨', + 'boxhd;': '┬', + 'boxhu;': '┴', + 'boxminus;': '⊟', + 'boxplus;': '⊞', + 'boxtimes;': '⊠', + 'boxuL;': '╛', + 'boxuR;': '╘', + 'boxul;': '┘', + 'boxur;': '└', + 'boxv;': '│', + 'boxvH;': '╪', + 'boxvL;': '╡', + 'boxvR;': '╞', + 'boxvh;': '┼', + 'boxvl;': '┤', + 'boxvr;': '├', + 'bprime;': '‵', + 'breve;': '˘', + brvbar: '¦', + 'brvbar;': '¦', + 'bscr;': '𝒷', + 'bsemi;': '⁏', + 'bsim;': '∽', + 'bsime;': '⋍', + 'bsol;': '\\', + 'bsolb;': '⧅', + 'bsolhsub;': '⟈', + 'bull;': '•', + 'bullet;': '•', + 'bump;': '≎', + 'bumpE;': '⪮', + 'bumpe;': '≏', + 'bumpeq;': '≏', + 'cacute;': 'ć', + 'cap;': '∩', + 'capand;': '⩄', + 'capbrcup;': '⩉', + 'capcap;': '⩋', + 'capcup;': '⩇', + 'capdot;': '⩀', + 'caps;': '∩︀', + 'caret;': '⁁', + 'caron;': 'ˇ', + 'ccaps;': '⩍', + 'ccaron;': 'č', + ccedil: 'ç', + 'ccedil;': 'ç', + 'ccirc;': 'ĉ', + 'ccups;': '⩌', + 'ccupssm;': '⩐', + 'cdot;': 'ċ', + cedil: '¸', + 'cedil;': '¸', + 'cemptyv;': '⦲', + cent: '¢', + 'cent;': '¢', + 'centerdot;': '·', + 'cfr;': '𝔠', + 'chcy;': 'ч', + 'check;': '✓', + 'checkmark;': '✓', + 'chi;': 'χ', + 'cir;': '○', + 'cirE;': '⧃', + 'circ;': 'ˆ', + 'circeq;': '≗', + 'circlearrowleft;': '↺', + 'circlearrowright;': '↻', + 'circledR;': '®', + 'circledS;': 'Ⓢ', + 'circledast;': '⊛', + 'circledcirc;': '⊚', + 'circleddash;': '⊝', + 'cire;': '≗', + 'cirfnint;': '⨐', + 'cirmid;': '⫯', + 'cirscir;': '⧂', + 'clubs;': '♣', + 'clubsuit;': '♣', + 'colon;': ':', + 'colone;': '≔', + 'coloneq;': '≔', + 'comma;': ',', + 'commat;': '@', + 'comp;': '∁', + 'compfn;': '∘', + 'complement;': '∁', + 'complexes;': 'ℂ', + 'cong;': '≅', + 'congdot;': '⩭', + 'conint;': '∮', + 'copf;': '𝕔', + 'coprod;': '∐', + copy: '©', + 'copy;': '©', + 'copysr;': '℗', + 'crarr;': '↵', + 'cross;': '✗', + 'cscr;': '𝒸', + 'csub;': '⫏', + 'csube;': '⫑', + 'csup;': '⫐', + 'csupe;': '⫒', + 'ctdot;': '⋯', + 'cudarrl;': '⤸', + 'cudarrr;': '⤵', + 'cuepr;': '⋞', + 'cuesc;': '⋟', + 'cularr;': '↶', + 'cularrp;': '⤽', + 'cup;': '∪', + 'cupbrcap;': '⩈', + 'cupcap;': '⩆', + 'cupcup;': '⩊', + 'cupdot;': '⊍', + 'cupor;': '⩅', + 'cups;': '∪︀', + 'curarr;': '↷', + 'curarrm;': '⤼', + 'curlyeqprec;': '⋞', + 'curlyeqsucc;': '⋟', + 'curlyvee;': '⋎', + 'curlywedge;': '⋏', + curren: '¤', + 'curren;': '¤', + 'curvearrowleft;': '↶', + 'curvearrowright;': '↷', + 'cuvee;': '⋎', + 'cuwed;': '⋏', + 'cwconint;': '∲', + 'cwint;': '∱', + 'cylcty;': '⌭', + 'dArr;': '⇓', + 'dHar;': '⥥', + 'dagger;': '†', + 'daleth;': 'ℸ', + 'darr;': '↓', + 'dash;': '‐', + 'dashv;': '⊣', + 'dbkarow;': '⤏', + 'dblac;': '˝', + 'dcaron;': 'ď', + 'dcy;': 'д', + 'dd;': 'ⅆ', + 'ddagger;': '‡', + 'ddarr;': '⇊', + 'ddotseq;': '⩷', + deg: '°', + 'deg;': '°', + 'delta;': 'δ', + 'demptyv;': '⦱', + 'dfisht;': '⥿', + 'dfr;': '𝔡', + 'dharl;': '⇃', + 'dharr;': '⇂', + 'diam;': '⋄', + 'diamond;': '⋄', + 'diamondsuit;': '♦', + 'diams;': '♦', + 'die;': '¨', + 'digamma;': 'ϝ', + 'disin;': '⋲', + 'div;': '÷', + divide: '÷', + 'divide;': '÷', + 'divideontimes;': '⋇', + 'divonx;': '⋇', + 'djcy;': 'ђ', + 'dlcorn;': '⌞', + 'dlcrop;': '⌍', + 'dollar;': '$', + 'dopf;': '𝕕', + 'dot;': '˙', + 'doteq;': '≐', + 'doteqdot;': '≑', + 'dotminus;': '∸', + 'dotplus;': '∔', + 'dotsquare;': '⊡', + 'doublebarwedge;': '⌆', + 'downarrow;': '↓', + 'downdownarrows;': '⇊', + 'downharpoonleft;': '⇃', + 'downharpoonright;': '⇂', + 'drbkarow;': '⤐', + 'drcorn;': '⌟', + 'drcrop;': '⌌', + 'dscr;': '𝒹', + 'dscy;': 'ѕ', + 'dsol;': '⧶', + 'dstrok;': 'đ', + 'dtdot;': '⋱', + 'dtri;': '▿', + 'dtrif;': '▾', + 'duarr;': '⇵', + 'duhar;': '⥯', + 'dwangle;': '⦦', + 'dzcy;': 'џ', + 'dzigrarr;': '⟿', + 'eDDot;': '⩷', + 'eDot;': '≑', + eacute: 'é', + 'eacute;': 'é', + 'easter;': '⩮', + 'ecaron;': 'ě', + 'ecir;': '≖', + ecirc: 'ê', + 'ecirc;': 'ê', + 'ecolon;': '≕', + 'ecy;': 'э', + 'edot;': 'ė', + 'ee;': 'ⅇ', + 'efDot;': '≒', + 'efr;': '𝔢', + 'eg;': '⪚', + egrave: 'è', + 'egrave;': 'è', + 'egs;': '⪖', + 'egsdot;': '⪘', + 'el;': '⪙', + 'elinters;': '⏧', + 'ell;': 'ℓ', + 'els;': '⪕', + 'elsdot;': '⪗', + 'emacr;': 'ē', + 'empty;': '∅', + 'emptyset;': '∅', + 'emptyv;': '∅', + 'emsp13;': ' ', + 'emsp14;': ' ', + 'emsp;': ' ', + 'eng;': 'ŋ', + 'ensp;': ' ', + 'eogon;': 'ę', + 'eopf;': '𝕖', + 'epar;': '⋕', + 'eparsl;': '⧣', + 'eplus;': '⩱', + 'epsi;': 'ε', + 'epsilon;': 'ε', + 'epsiv;': 'ϵ', + 'eqcirc;': '≖', + 'eqcolon;': '≕', + 'eqsim;': '≂', + 'eqslantgtr;': '⪖', + 'eqslantless;': '⪕', + 'equals;': '=', + 'equest;': '≟', + 'equiv;': '≡', + 'equivDD;': '⩸', + 'eqvparsl;': '⧥', + 'erDot;': '≓', + 'erarr;': '⥱', + 'escr;': 'ℯ', + 'esdot;': '≐', + 'esim;': '≂', + 'eta;': 'η', + eth: 'ð', + 'eth;': 'ð', + euml: 'ë', + 'euml;': 'ë', + 'euro;': '€', + 'excl;': '!', + 'exist;': '∃', + 'expectation;': 'ℰ', + 'exponentiale;': 'ⅇ', + 'fallingdotseq;': '≒', + 'fcy;': 'ф', + 'female;': '♀', + 'ffilig;': 'ffi', + 'fflig;': 'ff', + 'ffllig;': 'ffl', + 'ffr;': '𝔣', + 'filig;': 'fi', + 'fjlig;': 'fj', + 'flat;': '♭', + 'fllig;': 'fl', + 'fltns;': '▱', + 'fnof;': 'ƒ', + 'fopf;': '𝕗', + 'forall;': '∀', + 'fork;': '⋔', + 'forkv;': '⫙', + 'fpartint;': '⨍', + frac12: '½', + 'frac12;': '½', + 'frac13;': '⅓', + frac14: '¼', + 'frac14;': '¼', + 'frac15;': '⅕', + 'frac16;': '⅙', + 'frac18;': '⅛', + 'frac23;': '⅔', + 'frac25;': '⅖', + frac34: '¾', + 'frac34;': '¾', + 'frac35;': '⅗', + 'frac38;': '⅜', + 'frac45;': '⅘', + 'frac56;': '⅚', + 'frac58;': '⅝', + 'frac78;': '⅞', + 'frasl;': '⁄', + 'frown;': '⌢', + 'fscr;': '𝒻', + 'gE;': '≧', + 'gEl;': '⪌', + 'gacute;': 'ǵ', + 'gamma;': 'γ', + 'gammad;': 'ϝ', + 'gap;': '⪆', + 'gbreve;': 'ğ', + 'gcirc;': 'ĝ', + 'gcy;': 'г', + 'gdot;': 'ġ', + 'ge;': '≥', + 'gel;': '⋛', + 'geq;': '≥', + 'geqq;': '≧', + 'geqslant;': '⩾', + 'ges;': '⩾', + 'gescc;': '⪩', + 'gesdot;': '⪀', + 'gesdoto;': '⪂', + 'gesdotol;': '⪄', + 'gesl;': '⋛︀', + 'gesles;': '⪔', + 'gfr;': '𝔤', + 'gg;': '≫', + 'ggg;': '⋙', + 'gimel;': 'ℷ', + 'gjcy;': 'ѓ', + 'gl;': '≷', + 'glE;': '⪒', + 'gla;': '⪥', + 'glj;': '⪤', + 'gnE;': '≩', + 'gnap;': '⪊', + 'gnapprox;': '⪊', + 'gne;': '⪈', + 'gneq;': '⪈', + 'gneqq;': '≩', + 'gnsim;': '⋧', + 'gopf;': '𝕘', + 'grave;': '`', + 'gscr;': 'ℊ', + 'gsim;': '≳', + 'gsime;': '⪎', + 'gsiml;': '⪐', + gt: '>', + 'gt;': '>', + 'gtcc;': '⪧', + 'gtcir;': '⩺', + 'gtdot;': '⋗', + 'gtlPar;': '⦕', + 'gtquest;': '⩼', + 'gtrapprox;': '⪆', + 'gtrarr;': '⥸', + 'gtrdot;': '⋗', + 'gtreqless;': '⋛', + 'gtreqqless;': '⪌', + 'gtrless;': '≷', + 'gtrsim;': '≳', + 'gvertneqq;': '≩︀', + 'gvnE;': '≩︀', + 'hArr;': '⇔', + 'hairsp;': ' ', + 'half;': '½', + 'hamilt;': 'ℋ', + 'hardcy;': 'ъ', + 'harr;': '↔', + 'harrcir;': '⥈', + 'harrw;': '↭', + 'hbar;': 'ℏ', + 'hcirc;': 'ĥ', + 'hearts;': '♥', + 'heartsuit;': '♥', + 'hellip;': '…', + 'hercon;': '⊹', + 'hfr;': '𝔥', + 'hksearow;': '⤥', + 'hkswarow;': '⤦', + 'hoarr;': '⇿', + 'homtht;': '∻', + 'hookleftarrow;': '↩', + 'hookrightarrow;': '↪', + 'hopf;': '𝕙', + 'horbar;': '―', + 'hscr;': '𝒽', + 'hslash;': 'ℏ', + 'hstrok;': 'ħ', + 'hybull;': '⁃', + 'hyphen;': '‐', + iacute: 'í', + 'iacute;': 'í', + 'ic;': '⁣', + icirc: 'î', + 'icirc;': 'î', + 'icy;': 'и', + 'iecy;': 'е', + iexcl: '¡', + 'iexcl;': '¡', + 'iff;': '⇔', + 'ifr;': '𝔦', + igrave: 'ì', + 'igrave;': 'ì', + 'ii;': 'ⅈ', + 'iiiint;': '⨌', + 'iiint;': '∭', + 'iinfin;': '⧜', + 'iiota;': '℩', + 'ijlig;': 'ij', + 'imacr;': 'ī', + 'image;': 'ℑ', + 'imagline;': 'ℐ', + 'imagpart;': 'ℑ', + 'imath;': 'ı', + 'imof;': '⊷', + 'imped;': 'Ƶ', + 'in;': '∈', + 'incare;': '℅', + 'infin;': '∞', + 'infintie;': '⧝', + 'inodot;': 'ı', + 'int;': '∫', + 'intcal;': '⊺', + 'integers;': 'ℤ', + 'intercal;': '⊺', + 'intlarhk;': '⨗', + 'intprod;': '⨼', + 'iocy;': 'ё', + 'iogon;': 'į', + 'iopf;': '𝕚', + 'iota;': 'ι', + 'iprod;': '⨼', + iquest: '¿', + 'iquest;': '¿', + 'iscr;': '𝒾', + 'isin;': '∈', + 'isinE;': '⋹', + 'isindot;': '⋵', + 'isins;': '⋴', + 'isinsv;': '⋳', + 'isinv;': '∈', + 'it;': '⁢', + 'itilde;': 'ĩ', + 'iukcy;': 'і', + iuml: 'ï', + 'iuml;': 'ï', + 'jcirc;': 'ĵ', + 'jcy;': 'й', + 'jfr;': '𝔧', + 'jmath;': 'ȷ', + 'jopf;': '𝕛', + 'jscr;': '𝒿', + 'jsercy;': 'ј', + 'jukcy;': 'є', + 'kappa;': 'κ', + 'kappav;': 'ϰ', + 'kcedil;': 'ķ', + 'kcy;': 'к', + 'kfr;': '𝔨', + 'kgreen;': 'ĸ', + 'khcy;': 'х', + 'kjcy;': 'ќ', + 'kopf;': '𝕜', + 'kscr;': '𝓀', + 'lAarr;': '⇚', + 'lArr;': '⇐', + 'lAtail;': '⤛', + 'lBarr;': '⤎', + 'lE;': '≦', + 'lEg;': '⪋', + 'lHar;': '⥢', + 'lacute;': 'ĺ', + 'laemptyv;': '⦴', + 'lagran;': 'ℒ', + 'lambda;': 'λ', + 'lang;': '⟨', + 'langd;': '⦑', + 'langle;': '⟨', + 'lap;': '⪅', + laquo: '«', + 'laquo;': '«', + 'larr;': '←', + 'larrb;': '⇤', + 'larrbfs;': '⤟', + 'larrfs;': '⤝', + 'larrhk;': '↩', + 'larrlp;': '↫', + 'larrpl;': '⤹', + 'larrsim;': '⥳', + 'larrtl;': '↢', + 'lat;': '⪫', + 'latail;': '⤙', + 'late;': '⪭', + 'lates;': '⪭︀', + 'lbarr;': '⤌', + 'lbbrk;': '❲', + 'lbrace;': '{', + 'lbrack;': '[', + 'lbrke;': '⦋', + 'lbrksld;': '⦏', + 'lbrkslu;': '⦍', + 'lcaron;': 'ľ', + 'lcedil;': 'ļ', + 'lceil;': '⌈', + 'lcub;': '{', + 'lcy;': 'л', + 'ldca;': '⤶', + 'ldquo;': '“', + 'ldquor;': '„', + 'ldrdhar;': '⥧', + 'ldrushar;': '⥋', + 'ldsh;': '↲', + 'le;': '≤', + 'leftarrow;': '←', + 'leftarrowtail;': '↢', + 'leftharpoondown;': '↽', + 'leftharpoonup;': '↼', + 'leftleftarrows;': '⇇', + 'leftrightarrow;': '↔', + 'leftrightarrows;': '⇆', + 'leftrightharpoons;': '⇋', + 'leftrightsquigarrow;': '↭', + 'leftthreetimes;': '⋋', + 'leg;': '⋚', + 'leq;': '≤', + 'leqq;': '≦', + 'leqslant;': '⩽', + 'les;': '⩽', + 'lescc;': '⪨', + 'lesdot;': '⩿', + 'lesdoto;': '⪁', + 'lesdotor;': '⪃', + 'lesg;': '⋚︀', + 'lesges;': '⪓', + 'lessapprox;': '⪅', + 'lessdot;': '⋖', + 'lesseqgtr;': '⋚', + 'lesseqqgtr;': '⪋', + 'lessgtr;': '≶', + 'lesssim;': '≲', + 'lfisht;': '⥼', + 'lfloor;': '⌊', + 'lfr;': '𝔩', + 'lg;': '≶', + 'lgE;': '⪑', + 'lhard;': '↽', + 'lharu;': '↼', + 'lharul;': '⥪', + 'lhblk;': '▄', + 'ljcy;': 'љ', + 'll;': '≪', + 'llarr;': '⇇', + 'llcorner;': '⌞', + 'llhard;': '⥫', + 'lltri;': '◺', + 'lmidot;': 'ŀ', + 'lmoust;': '⎰', + 'lmoustache;': '⎰', + 'lnE;': '≨', + 'lnap;': '⪉', + 'lnapprox;': '⪉', + 'lne;': '⪇', + 'lneq;': '⪇', + 'lneqq;': '≨', + 'lnsim;': '⋦', + 'loang;': '⟬', + 'loarr;': '⇽', + 'lobrk;': '⟦', + 'longleftarrow;': '⟵', + 'longleftrightarrow;': '⟷', + 'longmapsto;': '⟼', + 'longrightarrow;': '⟶', + 'looparrowleft;': '↫', + 'looparrowright;': '↬', + 'lopar;': '⦅', + 'lopf;': '𝕝', + 'loplus;': '⨭', + 'lotimes;': '⨴', + 'lowast;': '∗', + 'lowbar;': '_', + 'loz;': '◊', + 'lozenge;': '◊', + 'lozf;': '⧫', + 'lpar;': '(', + 'lparlt;': '⦓', + 'lrarr;': '⇆', + 'lrcorner;': '⌟', + 'lrhar;': '⇋', + 'lrhard;': '⥭', + 'lrm;': '‎', + 'lrtri;': '⊿', + 'lsaquo;': '‹', + 'lscr;': '𝓁', + 'lsh;': '↰', + 'lsim;': '≲', + 'lsime;': '⪍', + 'lsimg;': '⪏', + 'lsqb;': '[', + 'lsquo;': '‘', + 'lsquor;': '‚', + 'lstrok;': 'ł', + lt: '<', + 'lt;': '<', + 'ltcc;': '⪦', + 'ltcir;': '⩹', + 'ltdot;': '⋖', + 'lthree;': '⋋', + 'ltimes;': '⋉', + 'ltlarr;': '⥶', + 'ltquest;': '⩻', + 'ltrPar;': '⦖', + 'ltri;': '◃', + 'ltrie;': '⊴', + 'ltrif;': '◂', + 'lurdshar;': '⥊', + 'luruhar;': '⥦', + 'lvertneqq;': '≨︀', + 'lvnE;': '≨︀', + 'mDDot;': '∺', + macr: '¯', + 'macr;': '¯', + 'male;': '♂', + 'malt;': '✠', + 'maltese;': '✠', + 'map;': '↦', + 'mapsto;': '↦', + 'mapstodown;': '↧', + 'mapstoleft;': '↤', + 'mapstoup;': '↥', + 'marker;': '▮', + 'mcomma;': '⨩', + 'mcy;': 'м', + 'mdash;': '—', + 'measuredangle;': '∡', + 'mfr;': '𝔪', + 'mho;': '℧', + micro: 'µ', + 'micro;': 'µ', + 'mid;': '∣', + 'midast;': '*', + 'midcir;': '⫰', + middot: '·', + 'middot;': '·', + 'minus;': '−', + 'minusb;': '⊟', + 'minusd;': '∸', + 'minusdu;': '⨪', + 'mlcp;': '⫛', + 'mldr;': '…', + 'mnplus;': '∓', + 'models;': '⊧', + 'mopf;': '𝕞', + 'mp;': '∓', + 'mscr;': '𝓂', + 'mstpos;': '∾', + 'mu;': 'μ', + 'multimap;': '⊸', + 'mumap;': '⊸', + 'nGg;': '⋙̸', + 'nGt;': '≫⃒', + 'nGtv;': '≫̸', + 'nLeftarrow;': '⇍', + 'nLeftrightarrow;': '⇎', + 'nLl;': '⋘̸', + 'nLt;': '≪⃒', + 'nLtv;': '≪̸', + 'nRightarrow;': '⇏', + 'nVDash;': '⊯', + 'nVdash;': '⊮', + 'nabla;': '∇', + 'nacute;': 'ń', + 'nang;': '∠⃒', + 'nap;': '≉', + 'napE;': '⩰̸', + 'napid;': '≋̸', + 'napos;': 'ʼn', + 'napprox;': '≉', + 'natur;': '♮', + 'natural;': '♮', + 'naturals;': 'ℕ', + nbsp: ' ', + 'nbsp;': ' ', + 'nbump;': '≎̸', + 'nbumpe;': '≏̸', + 'ncap;': '⩃', + 'ncaron;': 'ň', + 'ncedil;': 'ņ', + 'ncong;': '≇', + 'ncongdot;': '⩭̸', + 'ncup;': '⩂', + 'ncy;': 'н', + 'ndash;': '–', + 'ne;': '≠', + 'neArr;': '⇗', + 'nearhk;': '⤤', + 'nearr;': '↗', + 'nearrow;': '↗', + 'nedot;': '≐̸', + 'nequiv;': '≢', + 'nesear;': '⤨', + 'nesim;': '≂̸', + 'nexist;': '∄', + 'nexists;': '∄', + 'nfr;': '𝔫', + 'ngE;': '≧̸', + 'nge;': '≱', + 'ngeq;': '≱', + 'ngeqq;': '≧̸', + 'ngeqslant;': '⩾̸', + 'nges;': '⩾̸', + 'ngsim;': '≵', + 'ngt;': '≯', + 'ngtr;': '≯', + 'nhArr;': '⇎', + 'nharr;': '↮', + 'nhpar;': '⫲', + 'ni;': '∋', + 'nis;': '⋼', + 'nisd;': '⋺', + 'niv;': '∋', + 'njcy;': 'њ', + 'nlArr;': '⇍', + 'nlE;': '≦̸', + 'nlarr;': '↚', + 'nldr;': '‥', + 'nle;': '≰', + 'nleftarrow;': '↚', + 'nleftrightarrow;': '↮', + 'nleq;': '≰', + 'nleqq;': '≦̸', + 'nleqslant;': '⩽̸', + 'nles;': '⩽̸', + 'nless;': '≮', + 'nlsim;': '≴', + 'nlt;': '≮', + 'nltri;': '⋪', + 'nltrie;': '⋬', + 'nmid;': '∤', + 'nopf;': '𝕟', + not: '¬', + 'not;': '¬', + 'notin;': '∉', + 'notinE;': '⋹̸', + 'notindot;': '⋵̸', + 'notinva;': '∉', + 'notinvb;': '⋷', + 'notinvc;': '⋶', + 'notni;': '∌', + 'notniva;': '∌', + 'notnivb;': '⋾', + 'notnivc;': '⋽', + 'npar;': '∦', + 'nparallel;': '∦', + 'nparsl;': '⫽⃥', + 'npart;': '∂̸', + 'npolint;': '⨔', + 'npr;': '⊀', + 'nprcue;': '⋠', + 'npre;': '⪯̸', + 'nprec;': '⊀', + 'npreceq;': '⪯̸', + 'nrArr;': '⇏', + 'nrarr;': '↛', + 'nrarrc;': '⤳̸', + 'nrarrw;': '↝̸', + 'nrightarrow;': '↛', + 'nrtri;': '⋫', + 'nrtrie;': '⋭', + 'nsc;': '⊁', + 'nsccue;': '⋡', + 'nsce;': '⪰̸', + 'nscr;': '𝓃', + 'nshortmid;': '∤', + 'nshortparallel;': '∦', + 'nsim;': '≁', + 'nsime;': '≄', + 'nsimeq;': '≄', + 'nsmid;': '∤', + 'nspar;': '∦', + 'nsqsube;': '⋢', + 'nsqsupe;': '⋣', + 'nsub;': '⊄', + 'nsubE;': '⫅̸', + 'nsube;': '⊈', + 'nsubset;': '⊂⃒', + 'nsubseteq;': '⊈', + 'nsubseteqq;': '⫅̸', + 'nsucc;': '⊁', + 'nsucceq;': '⪰̸', + 'nsup;': '⊅', + 'nsupE;': '⫆̸', + 'nsupe;': '⊉', + 'nsupset;': '⊃⃒', + 'nsupseteq;': '⊉', + 'nsupseteqq;': '⫆̸', + 'ntgl;': '≹', + ntilde: 'ñ', + 'ntilde;': 'ñ', + 'ntlg;': '≸', + 'ntriangleleft;': '⋪', + 'ntrianglelefteq;': '⋬', + 'ntriangleright;': '⋫', + 'ntrianglerighteq;': '⋭', + 'nu;': 'ν', + 'num;': '#', + 'numero;': '№', + 'numsp;': ' ', + 'nvDash;': '⊭', + 'nvHarr;': '⤄', + 'nvap;': '≍⃒', + 'nvdash;': '⊬', + 'nvge;': '≥⃒', + 'nvgt;': '>⃒', + 'nvinfin;': '⧞', + 'nvlArr;': '⤂', + 'nvle;': '≤⃒', + 'nvlt;': '<⃒', + 'nvltrie;': '⊴⃒', + 'nvrArr;': '⤃', + 'nvrtrie;': '⊵⃒', + 'nvsim;': '∼⃒', + 'nwArr;': '⇖', + 'nwarhk;': '⤣', + 'nwarr;': '↖', + 'nwarrow;': '↖', + 'nwnear;': '⤧', + 'oS;': 'Ⓢ', + oacute: 'ó', + 'oacute;': 'ó', + 'oast;': '⊛', + 'ocir;': '⊚', + ocirc: 'ô', + 'ocirc;': 'ô', + 'ocy;': 'о', + 'odash;': '⊝', + 'odblac;': 'ő', + 'odiv;': '⨸', + 'odot;': '⊙', + 'odsold;': '⦼', + 'oelig;': 'œ', + 'ofcir;': '⦿', + 'ofr;': '𝔬', + 'ogon;': '˛', + ograve: 'ò', + 'ograve;': 'ò', + 'ogt;': '⧁', + 'ohbar;': '⦵', + 'ohm;': 'Ω', + 'oint;': '∮', + 'olarr;': '↺', + 'olcir;': '⦾', + 'olcross;': '⦻', + 'oline;': '‾', + 'olt;': '⧀', + 'omacr;': 'ō', + 'omega;': 'ω', + 'omicron;': 'ο', + 'omid;': '⦶', + 'ominus;': '⊖', + 'oopf;': '𝕠', + 'opar;': '⦷', + 'operp;': '⦹', + 'oplus;': '⊕', + 'or;': '∨', + 'orarr;': '↻', + 'ord;': '⩝', + 'order;': 'ℴ', + 'orderof;': 'ℴ', + ordf: 'ª', + 'ordf;': 'ª', + ordm: 'º', + 'ordm;': 'º', + 'origof;': '⊶', + 'oror;': '⩖', + 'orslope;': '⩗', + 'orv;': '⩛', + 'oscr;': 'ℴ', + oslash: 'ø', + 'oslash;': 'ø', + 'osol;': '⊘', + otilde: 'õ', + 'otilde;': 'õ', + 'otimes;': '⊗', + 'otimesas;': '⨶', + ouml: 'ö', + 'ouml;': 'ö', + 'ovbar;': '⌽', + 'par;': '∥', + para: '¶', + 'para;': '¶', + 'parallel;': '∥', + 'parsim;': '⫳', + 'parsl;': '⫽', + 'part;': '∂', + 'pcy;': 'п', + 'percnt;': '%', + 'period;': '.', + 'permil;': '‰', + 'perp;': '⊥', + 'pertenk;': '‱', + 'pfr;': '𝔭', + 'phi;': 'φ', + 'phiv;': 'ϕ', + 'phmmat;': 'ℳ', + 'phone;': '☎', + 'pi;': 'π', + 'pitchfork;': '⋔', + 'piv;': 'ϖ', + 'planck;': 'ℏ', + 'planckh;': 'ℎ', + 'plankv;': 'ℏ', + 'plus;': '+', + 'plusacir;': '⨣', + 'plusb;': '⊞', + 'pluscir;': '⨢', + 'plusdo;': '∔', + 'plusdu;': '⨥', + 'pluse;': '⩲', + plusmn: '±', + 'plusmn;': '±', + 'plussim;': '⨦', + 'plustwo;': '⨧', + 'pm;': '±', + 'pointint;': '⨕', + 'popf;': '𝕡', + pound: '£', + 'pound;': '£', + 'pr;': '≺', + 'prE;': '⪳', + 'prap;': '⪷', + 'prcue;': '≼', + 'pre;': '⪯', + 'prec;': '≺', + 'precapprox;': '⪷', + 'preccurlyeq;': '≼', + 'preceq;': '⪯', + 'precnapprox;': '⪹', + 'precneqq;': '⪵', + 'precnsim;': '⋨', + 'precsim;': '≾', + 'prime;': '′', + 'primes;': 'ℙ', + 'prnE;': '⪵', + 'prnap;': '⪹', + 'prnsim;': '⋨', + 'prod;': '∏', + 'profalar;': '⌮', + 'profline;': '⌒', + 'profsurf;': '⌓', + 'prop;': '∝', + 'propto;': '∝', + 'prsim;': '≾', + 'prurel;': '⊰', + 'pscr;': '𝓅', + 'psi;': 'ψ', + 'puncsp;': ' ', + 'qfr;': '𝔮', + 'qint;': '⨌', + 'qopf;': '𝕢', + 'qprime;': '⁗', + 'qscr;': '𝓆', + 'quaternions;': 'ℍ', + 'quatint;': '⨖', + 'quest;': '?', + 'questeq;': '≟', + quot: '"', + 'quot;': '"', + 'rAarr;': '⇛', + 'rArr;': '⇒', + 'rAtail;': '⤜', + 'rBarr;': '⤏', + 'rHar;': '⥤', + 'race;': '∽̱', + 'racute;': 'ŕ', + 'radic;': '√', + 'raemptyv;': '⦳', + 'rang;': '⟩', + 'rangd;': '⦒', + 'range;': '⦥', + 'rangle;': '⟩', + raquo: '»', + 'raquo;': '»', + 'rarr;': '→', + 'rarrap;': '⥵', + 'rarrb;': '⇥', + 'rarrbfs;': '⤠', + 'rarrc;': '⤳', + 'rarrfs;': '⤞', + 'rarrhk;': '↪', + 'rarrlp;': '↬', + 'rarrpl;': '⥅', + 'rarrsim;': '⥴', + 'rarrtl;': '↣', + 'rarrw;': '↝', + 'ratail;': '⤚', + 'ratio;': '∶', + 'rationals;': 'ℚ', + 'rbarr;': '⤍', + 'rbbrk;': '❳', + 'rbrace;': '}', + 'rbrack;': ']', + 'rbrke;': '⦌', + 'rbrksld;': '⦎', + 'rbrkslu;': '⦐', + 'rcaron;': 'ř', + 'rcedil;': 'ŗ', + 'rceil;': '⌉', + 'rcub;': '}', + 'rcy;': 'р', + 'rdca;': '⤷', + 'rdldhar;': '⥩', + 'rdquo;': '”', + 'rdquor;': '”', + 'rdsh;': '↳', + 'real;': 'ℜ', + 'realine;': 'ℛ', + 'realpart;': 'ℜ', + 'reals;': 'ℝ', + 'rect;': '▭', + reg: '®', + 'reg;': '®', + 'rfisht;': '⥽', + 'rfloor;': '⌋', + 'rfr;': '𝔯', + 'rhard;': '⇁', + 'rharu;': '⇀', + 'rharul;': '⥬', + 'rho;': 'ρ', + 'rhov;': 'ϱ', + 'rightarrow;': '→', + 'rightarrowtail;': '↣', + 'rightharpoondown;': '⇁', + 'rightharpoonup;': '⇀', + 'rightleftarrows;': '⇄', + 'rightleftharpoons;': '⇌', + 'rightrightarrows;': '⇉', + 'rightsquigarrow;': '↝', + 'rightthreetimes;': '⋌', + 'ring;': '˚', + 'risingdotseq;': '≓', + 'rlarr;': '⇄', + 'rlhar;': '⇌', + 'rlm;': '‏', + 'rmoust;': '⎱', + 'rmoustache;': '⎱', + 'rnmid;': '⫮', + 'roang;': '⟭', + 'roarr;': '⇾', + 'robrk;': '⟧', + 'ropar;': '⦆', + 'ropf;': '𝕣', + 'roplus;': '⨮', + 'rotimes;': '⨵', + 'rpar;': ')', + 'rpargt;': '⦔', + 'rppolint;': '⨒', + 'rrarr;': '⇉', + 'rsaquo;': '›', + 'rscr;': '𝓇', + 'rsh;': '↱', + 'rsqb;': ']', + 'rsquo;': '’', + 'rsquor;': '’', + 'rthree;': '⋌', + 'rtimes;': '⋊', + 'rtri;': '▹', + 'rtrie;': '⊵', + 'rtrif;': '▸', + 'rtriltri;': '⧎', + 'ruluhar;': '⥨', + 'rx;': '℞', + 'sacute;': 'ś', + 'sbquo;': '‚', + 'sc;': '≻', + 'scE;': '⪴', + 'scap;': '⪸', + 'scaron;': 'š', + 'sccue;': '≽', + 'sce;': '⪰', + 'scedil;': 'ş', + 'scirc;': 'ŝ', + 'scnE;': '⪶', + 'scnap;': '⪺', + 'scnsim;': '⋩', + 'scpolint;': '⨓', + 'scsim;': '≿', + 'scy;': 'с', + 'sdot;': '⋅', + 'sdotb;': '⊡', + 'sdote;': '⩦', + 'seArr;': '⇘', + 'searhk;': '⤥', + 'searr;': '↘', + 'searrow;': '↘', + sect: '§', + 'sect;': '§', + 'semi;': ';', + 'seswar;': '⤩', + 'setminus;': '∖', + 'setmn;': '∖', + 'sext;': '✶', + 'sfr;': '𝔰', + 'sfrown;': '⌢', + 'sharp;': '♯', + 'shchcy;': 'щ', + 'shcy;': 'ш', + 'shortmid;': '∣', + 'shortparallel;': '∥', + shy: '­', + 'shy;': '­', + 'sigma;': 'σ', + 'sigmaf;': 'ς', + 'sigmav;': 'ς', + 'sim;': '∼', + 'simdot;': '⩪', + 'sime;': '≃', + 'simeq;': '≃', + 'simg;': '⪞', + 'simgE;': '⪠', + 'siml;': '⪝', + 'simlE;': '⪟', + 'simne;': '≆', + 'simplus;': '⨤', + 'simrarr;': '⥲', + 'slarr;': '←', + 'smallsetminus;': '∖', + 'smashp;': '⨳', + 'smeparsl;': '⧤', + 'smid;': '∣', + 'smile;': '⌣', + 'smt;': '⪪', + 'smte;': '⪬', + 'smtes;': '⪬︀', + 'softcy;': 'ь', + 'sol;': '/', + 'solb;': '⧄', + 'solbar;': '⌿', + 'sopf;': '𝕤', + 'spades;': '♠', + 'spadesuit;': '♠', + 'spar;': '∥', + 'sqcap;': '⊓', + 'sqcaps;': '⊓︀', + 'sqcup;': '⊔', + 'sqcups;': '⊔︀', + 'sqsub;': '⊏', + 'sqsube;': '⊑', + 'sqsubset;': '⊏', + 'sqsubseteq;': '⊑', + 'sqsup;': '⊐', + 'sqsupe;': '⊒', + 'sqsupset;': '⊐', + 'sqsupseteq;': '⊒', + 'squ;': '□', + 'square;': '□', + 'squarf;': '▪', + 'squf;': '▪', + 'srarr;': '→', + 'sscr;': '𝓈', + 'ssetmn;': '∖', + 'ssmile;': '⌣', + 'sstarf;': '⋆', + 'star;': '☆', + 'starf;': '★', + 'straightepsilon;': 'ϵ', + 'straightphi;': 'ϕ', + 'strns;': '¯', + 'sub;': '⊂', + 'subE;': '⫅', + 'subdot;': '⪽', + 'sube;': '⊆', + 'subedot;': '⫃', + 'submult;': '⫁', + 'subnE;': '⫋', + 'subne;': '⊊', + 'subplus;': '⪿', + 'subrarr;': '⥹', + 'subset;': '⊂', + 'subseteq;': '⊆', + 'subseteqq;': '⫅', + 'subsetneq;': '⊊', + 'subsetneqq;': '⫋', + 'subsim;': '⫇', + 'subsub;': '⫕', + 'subsup;': '⫓', + 'succ;': '≻', + 'succapprox;': '⪸', + 'succcurlyeq;': '≽', + 'succeq;': '⪰', + 'succnapprox;': '⪺', + 'succneqq;': '⪶', + 'succnsim;': '⋩', + 'succsim;': '≿', + 'sum;': '∑', + 'sung;': '♪', + sup1: '¹', + 'sup1;': '¹', + sup2: '²', + 'sup2;': '²', + sup3: '³', + 'sup3;': '³', + 'sup;': '⊃', + 'supE;': '⫆', + 'supdot;': '⪾', + 'supdsub;': '⫘', + 'supe;': '⊇', + 'supedot;': '⫄', + 'suphsol;': '⟉', + 'suphsub;': '⫗', + 'suplarr;': '⥻', + 'supmult;': '⫂', + 'supnE;': '⫌', + 'supne;': '⊋', + 'supplus;': '⫀', + 'supset;': '⊃', + 'supseteq;': '⊇', + 'supseteqq;': '⫆', + 'supsetneq;': '⊋', + 'supsetneqq;': '⫌', + 'supsim;': '⫈', + 'supsub;': '⫔', + 'supsup;': '⫖', + 'swArr;': '⇙', + 'swarhk;': '⤦', + 'swarr;': '↙', + 'swarrow;': '↙', + 'swnwar;': '⤪', + szlig: 'ß', + 'szlig;': 'ß', + 'target;': '⌖', + 'tau;': 'τ', + 'tbrk;': '⎴', + 'tcaron;': 'ť', + 'tcedil;': 'ţ', + 'tcy;': 'т', + 'tdot;': '⃛', + 'telrec;': '⌕', + 'tfr;': '𝔱', + 'there4;': '∴', + 'therefore;': '∴', + 'theta;': 'θ', + 'thetasym;': 'ϑ', + 'thetav;': 'ϑ', + 'thickapprox;': '≈', + 'thicksim;': '∼', + 'thinsp;': ' ', + 'thkap;': '≈', + 'thksim;': '∼', + thorn: 'þ', + 'thorn;': 'þ', + 'tilde;': '˜', + times: '×', + 'times;': '×', + 'timesb;': '⊠', + 'timesbar;': '⨱', + 'timesd;': '⨰', + 'tint;': '∭', + 'toea;': '⤨', + 'top;': '⊤', + 'topbot;': '⌶', + 'topcir;': '⫱', + 'topf;': '𝕥', + 'topfork;': '⫚', + 'tosa;': '⤩', + 'tprime;': '‴', + 'trade;': '™', + 'triangle;': '▵', + 'triangledown;': '▿', + 'triangleleft;': '◃', + 'trianglelefteq;': '⊴', + 'triangleq;': '≜', + 'triangleright;': '▹', + 'trianglerighteq;': '⊵', + 'tridot;': '◬', + 'trie;': '≜', + 'triminus;': '⨺', + 'triplus;': '⨹', + 'trisb;': '⧍', + 'tritime;': '⨻', + 'trpezium;': '⏢', + 'tscr;': '𝓉', + 'tscy;': 'ц', + 'tshcy;': 'ћ', + 'tstrok;': 'ŧ', + 'twixt;': '≬', + 'twoheadleftarrow;': '↞', + 'twoheadrightarrow;': '↠', + 'uArr;': '⇑', + 'uHar;': '⥣', + uacute: 'ú', + 'uacute;': 'ú', + 'uarr;': '↑', + 'ubrcy;': 'ў', + 'ubreve;': 'ŭ', + ucirc: 'û', + 'ucirc;': 'û', + 'ucy;': 'у', + 'udarr;': '⇅', + 'udblac;': 'ű', + 'udhar;': '⥮', + 'ufisht;': '⥾', + 'ufr;': '𝔲', + ugrave: 'ù', + 'ugrave;': 'ù', + 'uharl;': '↿', + 'uharr;': '↾', + 'uhblk;': '▀', + 'ulcorn;': '⌜', + 'ulcorner;': '⌜', + 'ulcrop;': '⌏', + 'ultri;': '◸', + 'umacr;': 'ū', + uml: '¨', + 'uml;': '¨', + 'uogon;': 'ų', + 'uopf;': '𝕦', + 'uparrow;': '↑', + 'updownarrow;': '↕', + 'upharpoonleft;': '↿', + 'upharpoonright;': '↾', + 'uplus;': '⊎', + 'upsi;': 'υ', + 'upsih;': 'ϒ', + 'upsilon;': 'υ', + 'upuparrows;': '⇈', + 'urcorn;': '⌝', + 'urcorner;': '⌝', + 'urcrop;': '⌎', + 'uring;': 'ů', + 'urtri;': '◹', + 'uscr;': '𝓊', + 'utdot;': '⋰', + 'utilde;': 'ũ', + 'utri;': '▵', + 'utrif;': '▴', + 'uuarr;': '⇈', + uuml: 'ü', + 'uuml;': 'ü', + 'uwangle;': '⦧', + 'vArr;': '⇕', + 'vBar;': '⫨', + 'vBarv;': '⫩', + 'vDash;': '⊨', + 'vangrt;': '⦜', + 'varepsilon;': 'ϵ', + 'varkappa;': 'ϰ', + 'varnothing;': '∅', + 'varphi;': 'ϕ', + 'varpi;': 'ϖ', + 'varpropto;': '∝', + 'varr;': '↕', + 'varrho;': 'ϱ', + 'varsigma;': 'ς', + 'varsubsetneq;': '⊊︀', + 'varsubsetneqq;': '⫋︀', + 'varsupsetneq;': '⊋︀', + 'varsupsetneqq;': '⫌︀', + 'vartheta;': 'ϑ', + 'vartriangleleft;': '⊲', + 'vartriangleright;': '⊳', + 'vcy;': 'в', + 'vdash;': '⊢', + 'vee;': '∨', + 'veebar;': '⊻', + 'veeeq;': '≚', + 'vellip;': '⋮', + 'verbar;': '|', + 'vert;': '|', + 'vfr;': '𝔳', + 'vltri;': '⊲', + 'vnsub;': '⊂⃒', + 'vnsup;': '⊃⃒', + 'vopf;': '𝕧', + 'vprop;': '∝', + 'vrtri;': '⊳', + 'vscr;': '𝓋', + 'vsubnE;': '⫋︀', + 'vsubne;': '⊊︀', + 'vsupnE;': '⫌︀', + 'vsupne;': '⊋︀', + 'vzigzag;': '⦚', + 'wcirc;': 'ŵ', + 'wedbar;': '⩟', + 'wedge;': '∧', + 'wedgeq;': '≙', + 'weierp;': '℘', + 'wfr;': '𝔴', + 'wopf;': '𝕨', + 'wp;': '℘', + 'wr;': '≀', + 'wreath;': '≀', + 'wscr;': '𝓌', + 'xcap;': '⋂', + 'xcirc;': '◯', + 'xcup;': '⋃', + 'xdtri;': '▽', + 'xfr;': '𝔵', + 'xhArr;': '⟺', + 'xharr;': '⟷', + 'xi;': 'ξ', + 'xlArr;': '⟸', + 'xlarr;': '⟵', + 'xmap;': '⟼', + 'xnis;': '⋻', + 'xodot;': '⨀', + 'xopf;': '𝕩', + 'xoplus;': '⨁', + 'xotime;': '⨂', + 'xrArr;': '⟹', + 'xrarr;': '⟶', + 'xscr;': '𝓍', + 'xsqcup;': '⨆', + 'xuplus;': '⨄', + 'xutri;': '△', + 'xvee;': '⋁', + 'xwedge;': '⋀', + yacute: 'ý', + 'yacute;': 'ý', + 'yacy;': 'я', + 'ycirc;': 'ŷ', + 'ycy;': 'ы', + yen: '¥', + 'yen;': '¥', + 'yfr;': '𝔶', + 'yicy;': 'ї', + 'yopf;': '𝕪', + 'yscr;': '𝓎', + 'yucy;': 'ю', + yuml: 'ÿ', + 'yuml;': 'ÿ', + 'zacute;': 'ź', + 'zcaron;': 'ž', + 'zcy;': 'з', + 'zdot;': 'ż', + 'zeetrf;': 'ℨ', + 'zeta;': 'ζ', + 'zfr;': '𝔷', + 'zhcy;': 'ж', + 'zigrarr;': '⇝', + 'zopf;': '𝕫', + 'zscr;': '𝓏', + 'zwj;': '‍', + 'zwnj;': '‌' +}; + +const numeric = /&#(x)?([0-9a-f]+);/i; +const named = new RegExp( + `&(${Object.keys(entities) + .sort((a, b) => b.length - a.length) + .join('|')})`, + 'g' +); + +/** @param {string} str */ +export function decode(str) { + return str + .replace(numeric, (_match, hex, code) => String.fromCharCode(hex ? parseInt(code, 16) : +code)) + .replace(named, (_match, entity) => entities[entity]); +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/fallback.js b/node_modules/@sveltejs/kit/src/core/postbuild/fallback.js new file mode 100644 index 00000000..d77400a4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/fallback.js @@ -0,0 +1,54 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { installPolyfills } from '../../exports/node/polyfills.js'; +import { load_config } from '../config/index.js'; +import { forked } from '../../utils/fork.js'; + +export default forked(import.meta.url, generate_fallback); + +/** + * @param {{ + * manifest_path: string; + * env: Record + * }} opts + */ +async function generate_fallback({ manifest_path, env }) { + /** @type {import('types').ValidatedKitConfig} */ + const config = (await load_config()).kit; + + installPolyfills(); + + const server_root = join(config.outDir, 'output'); + + /** @type {import('types').ServerInternalModule} */ + const { set_building } = await import(pathToFileURL(`${server_root}/server/internal.js`).href); + + /** @type {import('types').ServerModule} */ + const { Server } = await import(pathToFileURL(`${server_root}/server/index.js`).href); + + /** @type {import('@sveltejs/kit').SSRManifest} */ + const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; + + set_building(); + + const server = new Server(manifest); + await server.init({ env }); + + const response = await server.respond(new Request(config.prerender.origin + '/[fallback]'), { + getClientAddress: () => { + throw new Error('Cannot read clientAddress during prerendering'); + }, + prerendering: { + fallback: true, + dependencies: new Map() + }, + read: (file) => readFileSync(join(config.files.assets, file)) + }); + + if (response.ok) { + return await response.text(); + } + + throw new Error(`Could not create a fallback page — failed with status ${response.status}`); +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js b/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js new file mode 100644 index 00000000..f1633ab8 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js @@ -0,0 +1,511 @@ +import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { installPolyfills } from '../../exports/node/polyfills.js'; +import { mkdirp, posixify, walk } from '../../utils/filesystem.js'; +import { decode_uri, is_root_relative, resolve } from '../../utils/url.js'; +import { escape_html_attr } from '../../utils/escape.js'; +import { logger } from '../utils.js'; +import { load_config } from '../config/index.js'; +import { get_route_segments } from '../../utils/routing.js'; +import { queue } from './queue.js'; +import { crawl } from './crawl.js'; +import { forked } from '../../utils/fork.js'; +import * as devalue from 'devalue'; +import { createReadableStream } from '@sveltejs/kit/node'; + +export default forked(import.meta.url, prerender); + +/** + * @param {{ + * out: string; + * manifest_path: string; + * metadata: import('types').ServerMetadata; + * verbose: boolean; + * env: Record + * }} opts + */ +async function prerender({ out, manifest_path, metadata, verbose, env }) { + /** @type {import('@sveltejs/kit').SSRManifest} */ + const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; + + /** @type {import('types').ServerInternalModule} */ + const internal = await import(pathToFileURL(`${out}/server/internal.js`).href); + + /** @type {import('types').ServerModule} */ + const { Server } = await import(pathToFileURL(`${out}/server/index.js`).href); + + // configure `import { building } from '$app/environment'` — + // essential we do this before analysing the code + internal.set_building(); + internal.set_prerendering(); + + /** + * @template {{message: string}} T + * @template {Omit} K + * @param {import('types').Logger} log + * @param {'fail' | 'warn' | 'ignore' | ((details: T) => void)} input + * @param {(details: K) => string} format + * @returns {(details: K) => void} + */ + function normalise_error_handler(log, input, format) { + switch (input) { + case 'fail': + return (details) => { + throw new Error(format(details)); + }; + case 'warn': + return (details) => { + log.error(format(details)); + }; + case 'ignore': + return () => {}; + default: + // @ts-expect-error TS thinks T might be of a different kind, but it's not + return (details) => input({ ...details, message: format(details) }); + } + } + + const OK = 2; + const REDIRECT = 3; + + /** @type {import('types').Prerendered} */ + const prerendered = { + pages: new Map(), + assets: new Map(), + redirects: new Map(), + paths: [] + }; + + /** @type {import('types').PrerenderMap} */ + const prerender_map = new Map(); + + for (const [id, { prerender }] of metadata.routes) { + if (prerender !== undefined) { + prerender_map.set(id, prerender); + } + } + + /** @type {Set} */ + const prerendered_routes = new Set(); + + /** @type {import('types').ValidatedKitConfig} */ + const config = (await load_config()).kit; + + const emulator = await config.adapter?.emulate?.(); + + /** @type {import('types').Logger} */ + const log = logger({ verbose }); + + installPolyfills(); + + /** @type {Map} */ + const saved = new Map(); + + const handle_http_error = normalise_error_handler( + log, + config.prerender.handleHttpError, + ({ status, path, referrer, referenceType }) => { + const message = + status === 404 && !path.startsWith(config.paths.base) + ? `${path} does not begin with \`base\`, which is configured in \`paths.base\` and can be imported from \`$app/paths\` - see https://kit.svelte.dev/docs/configuration#paths for more info` + : path; + + return `${status} ${message}${referrer ? ` (${referenceType} from ${referrer})` : ''}`; + } + ); + + const handle_missing_id = normalise_error_handler( + log, + config.prerender.handleMissingId, + ({ path, id, referrers }) => { + return ( + `The following pages contain links to ${path}#${id}, but no element with id="${id}" exists on ${path} - see the \`handleMissingId\` option in https://kit.svelte.dev/docs/configuration#prerender for more info:` + + referrers.map((l) => `\n - ${l}`).join('') + ); + } + ); + + const handle_entry_generator_mismatch = normalise_error_handler( + log, + config.prerender.handleEntryGeneratorMismatch, + ({ generatedFromId, entry, matchedId }) => { + return `The entries export from ${generatedFromId} generated entry ${entry}, which was matched by ${matchedId} - see the \`handleEntryGeneratorMismatch\` option in https://kit.svelte.dev/docs/configuration#prerender for more info.`; + } + ); + + const q = queue(config.prerender.concurrency); + + /** + * @param {string} path + * @param {boolean} is_html + */ + function output_filename(path, is_html) { + const file = path.slice(config.paths.base.length + 1) || 'index.html'; + + if (is_html && !file.endsWith('.html')) { + return file + (file.endsWith('/') ? 'index.html' : '.html'); + } + + return file; + } + + const files = new Set(walk(`${out}/client`).map(posixify)); + files.add(`${config.appDir}/env.js`); + + const immutable = `${config.appDir}/immutable`; + if (existsSync(`${out}/server/${immutable}`)) { + for (const file of walk(`${out}/server/${immutable}`)) { + files.add(posixify(`${config.appDir}/immutable/${file}`)); + } + } + const seen = new Set(); + const written = new Set(); + + /** @type {Map>} */ + const expected_hashlinks = new Map(); + + /** @type {Map} */ + const actual_hashlinks = new Map(); + + /** + * @param {string | null} referrer + * @param {string} decoded + * @param {string} [encoded] + * @param {string} [generated_from_id] + */ + function enqueue(referrer, decoded, encoded, generated_from_id) { + if (seen.has(decoded)) return; + seen.add(decoded); + + const file = decoded.slice(config.paths.base.length + 1); + if (files.has(file)) return; + + return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer, generated_from_id)); + } + + /** + * @param {string} decoded + * @param {string} encoded + * @param {string?} referrer + * @param {string} [generated_from_id] + */ + async function visit(decoded, encoded, referrer, generated_from_id) { + if (!decoded.startsWith(config.paths.base)) { + handle_http_error({ status: 404, path: decoded, referrer, referenceType: 'linked' }); + return; + } + + /** @type {Map} */ + const dependencies = new Map(); + + const response = await server.respond(new Request(config.prerender.origin + encoded), { + getClientAddress() { + throw new Error('Cannot read clientAddress during prerendering'); + }, + prerendering: { + dependencies + }, + read: (file) => { + // stuff we just wrote + const filepath = saved.get(file); + if (filepath) return readFileSync(filepath); + + // stuff in `static` + return readFileSync(join(config.files.assets, file)); + }, + emulator + }); + + const encoded_id = response.headers.get('x-sveltekit-routeid'); + const decoded_id = encoded_id && decode_uri(encoded_id); + if ( + decoded_id !== null && + generated_from_id !== undefined && + decoded_id !== generated_from_id + ) { + handle_entry_generator_mismatch({ + generatedFromId: generated_from_id, + entry: decoded, + matchedId: decoded_id + }); + } + + const body = Buffer.from(await response.arrayBuffer()); + + save('pages', response, body, decoded, encoded, referrer, 'linked'); + + for (const [dependency_path, result] of dependencies) { + // this seems circuitous, but using new URL allows us to not care + // whether dependency_path is encoded or not + const encoded_dependency_path = new URL(dependency_path, 'http://localhost').pathname; + const decoded_dependency_path = decode_uri(encoded_dependency_path); + + const headers = Object.fromEntries(result.response.headers); + + const prerender = headers['x-sveltekit-prerender']; + if (prerender) { + const encoded_route_id = headers['x-sveltekit-routeid']; + if (encoded_route_id != null) { + const route_id = decode_uri(encoded_route_id); + const existing_value = prerender_map.get(route_id); + if (existing_value !== 'auto') { + prerender_map.set(route_id, prerender === 'true' ? true : 'auto'); + } + } + } + + const body = result.body ?? new Uint8Array(await result.response.arrayBuffer()); + + save( + 'dependencies', + result.response, + body, + decoded_dependency_path, + encoded_dependency_path, + decoded, + 'fetched' + ); + } + + // avoid triggering `filterSerializeResponseHeaders` guard + const headers = Object.fromEntries(response.headers); + + if (config.prerender.crawl && headers['content-type'] === 'text/html') { + const { ids, hrefs } = crawl(body.toString(), decoded); + + actual_hashlinks.set(decoded, ids); + + /** @param {string} href */ + const removePrerenderOrigin = (href) => { + if (href.startsWith(config.prerender.origin)) { + if (href === config.prerender.origin) return '/'; + if (href.at(config.prerender.origin.length) !== '/') return href; + return href.slice(config.prerender.origin.length); + } + return href; + }; + + for (const href of hrefs.map(removePrerenderOrigin)) { + if (!is_root_relative(href)) continue; + + const { pathname, search, hash } = new URL(href, 'http://localhost'); + + if (search) { + // TODO warn that query strings have no effect on statically-exported pages + } + + if (hash) { + const key = decode_uri(pathname + hash); + + if (!expected_hashlinks.has(key)) { + expected_hashlinks.set(key, new Set()); + } + + /** @type {Set} */ (expected_hashlinks.get(key)).add(decoded); + } + + enqueue(decoded, decode_uri(pathname), pathname); + } + } + } + + /** + * @param {'pages' | 'dependencies'} category + * @param {Response} response + * @param {string | Uint8Array} body + * @param {string} decoded + * @param {string} encoded + * @param {string | null} referrer + * @param {'linked' | 'fetched'} referenceType + */ + function save(category, response, body, decoded, encoded, referrer, referenceType) { + const response_type = Math.floor(response.status / 100); + const headers = Object.fromEntries(response.headers); + + const type = headers['content-type']; + const is_html = response_type === REDIRECT || type === 'text/html'; + + const file = output_filename(decoded, is_html); + const dest = `${config.outDir}/output/prerendered/${category}/${file}`; + + if (written.has(file)) return; + + const encoded_route_id = response.headers.get('x-sveltekit-routeid'); + const route_id = encoded_route_id != null ? decode_uri(encoded_route_id) : null; + if (route_id !== null) prerendered_routes.add(route_id); + + if (response_type === REDIRECT) { + const location = headers['location']; + + if (location) { + const resolved = resolve(encoded, location); + if (is_root_relative(resolved)) { + enqueue(decoded, decode_uri(resolved), resolved); + } + + if (!headers['x-sveltekit-normalize']) { + mkdirp(dirname(dest)); + + log.warn(`${response.status} ${decoded} -> ${location}`); + + writeFileSync( + dest, + `` + ); + + written.add(file); + + if (!prerendered.redirects.has(decoded)) { + prerendered.redirects.set(decoded, { + status: response.status, + location: resolved + }); + + prerendered.paths.push(decoded); + } + } + } else { + log.warn(`location header missing on redirect received from ${decoded}`); + } + + return; + } + + if (response.status === 200) { + if (existsSync(dest) && statSync(dest).isDirectory()) { + throw new Error( + `Cannot save ${decoded} as it is already a directory. See https://kit.svelte.dev/docs/page-options#prerender-route-conflicts for more information` + ); + } + + const dir = dirname(dest); + + if (existsSync(dir) && !statSync(dir).isDirectory()) { + const parent = decoded.split('/').slice(0, -1).join('/'); + throw new Error( + `Cannot save ${decoded} as ${parent} is already a file. See https://kit.svelte.dev/docs/page-options#prerender-route-conflicts for more information` + ); + } + + mkdirp(dir); + + log.info(`${response.status} ${decoded}`); + writeFileSync(dest, body); + written.add(file); + + if (is_html) { + prerendered.pages.set(decoded, { + file + }); + } else { + prerendered.assets.set(decoded, { + type + }); + } + + prerendered.paths.push(decoded); + } else if (response_type !== OK) { + handle_http_error({ status: response.status, path: decoded, referrer, referenceType }); + } + + manifest.assets.add(file); + saved.set(file, dest); + } + + /** @type {Array<{ id: string, entries: Array}>} */ + const route_level_entries = []; + for (const [id, { entries }] of metadata.routes.entries()) { + if (entries) { + route_level_entries.push({ id, entries }); + } + } + + let has_prerenderable_routes = false; + + for (const value of prerender_map.values()) { + if (value) { + has_prerenderable_routes = true; + break; + } + } + + if ( + (config.prerender.entries.length === 0 && route_level_entries.length === 0) || + !has_prerenderable_routes + ) { + return { prerendered, prerender_map }; + } + + log.info('Prerendering'); + + const server = new Server(manifest); + await server.init({ + env, + read: (file) => createReadableStream(`${config.outDir}/output/server/${file}`) + }); + + for (const entry of config.prerender.entries) { + if (entry === '*') { + for (const [id, prerender] of prerender_map) { + if (prerender) { + // remove optional parameters from the route + const segments = get_route_segments(id).filter((segment) => !segment.startsWith('[[')); + const processed_id = '/' + segments.join('/'); + + if (processed_id.includes('[')) continue; + const path = `/${get_route_segments(processed_id).join('/')}`; + enqueue(null, config.paths.base + path); + } + } + } else { + enqueue(null, config.paths.base + entry); + } + } + + for (const { id, entries } of route_level_entries) { + for (const entry of entries) { + enqueue(null, config.paths.base + entry, undefined, id); + } + } + + await q.done(); + + // handle invalid fragment links + for (const [key, referrers] of expected_hashlinks) { + const index = key.indexOf('#'); + const path = key.slice(0, index); + const id = key.slice(index + 1); + + const hashlinks = actual_hashlinks.get(path); + // ignore fragment links to pages that were not prerendered + if (!hashlinks) continue; + + if (!hashlinks.includes(id)) { + handle_missing_id({ id, path, referrers: Array.from(referrers) }); + } + } + + /** @type {string[]} */ + const not_prerendered = []; + + for (const [route_id, prerender] of prerender_map) { + if (prerender === true && !prerendered_routes.has(route_id)) { + not_prerendered.push(route_id); + } + } + + if (not_prerendered.length > 0) { + const list = not_prerendered.map((id) => ` - ${id}`).join('\n'); + + throw new Error( + `The following routes were marked as prerenderable, but were not prerendered because they were not found while crawling your app:\n${list}\n\nSee https://kit.svelte.dev/docs/page-options#prerender-troubleshooting for info on how to solve this` + ); + } + + return { prerendered, prerender_map }; +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/queue.js b/node_modules/@sveltejs/kit/src/core/postbuild/queue.js new file mode 100644 index 00000000..79a2e9b7 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/queue.js @@ -0,0 +1,80 @@ +/** + * @typedef {{ + * fn: () => Promise, + * fulfil: (value: any) => void, + * reject: (error: Error) => void + * }} Task + */ + +/** @param {number} concurrency */ +export function queue(concurrency) { + /** @type {Task[]} */ + const tasks = []; + + let current = 0; + + /** @type {(value?: any) => void} */ + let fulfil; + + /** @type {(error: Error) => void} */ + let reject; + + let closed = false; + + const done = new Promise((f, r) => { + fulfil = f; + reject = r; + }); + + done.catch(() => { + // this is necessary in case a catch handler is never added + // to the done promise by the user + }); + + function dequeue() { + if (current < concurrency) { + const task = tasks.shift(); + + if (task) { + current += 1; + const promise = Promise.resolve(task.fn()); + + promise + .then(task.fulfil, (err) => { + task.reject(err); + reject(err); + }) + .then(() => { + current -= 1; + dequeue(); + }); + } else if (current === 0) { + closed = true; + fulfil(); + } + } + } + + return { + /** @param {() => any} fn */ + add: (fn) => { + if (closed) throw new Error('Cannot add tasks to a queue that has ended'); + + const promise = new Promise((fulfil, reject) => { + tasks.push({ fn, fulfil, reject }); + }); + + dequeue(); + return promise; + }, + + done: () => { + if (current === 0) { + closed = true; + fulfil(); + } + + return done; + } + }; +} diff --git a/assets/.gitkeep b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/conflict.js similarity index 100% rename from assets/.gitkeep rename to node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/conflict.js diff --git a/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/index.js b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/index.js new file mode 100644 index 00000000..588ba3d9 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/index.js @@ -0,0 +1,590 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import process from 'node:process'; +import colors from 'kleur'; +import { lookup } from 'mrmime'; +import { list_files, runtime_directory } from '../../utils.js'; +import { posixify, resolve_entry } from '../../../utils/filesystem.js'; +import { parse_route_id } from '../../../utils/routing.js'; +import { sort_routes } from './sort.js'; +import { isSvelte5Plus } from '../utils.js'; + +/** + * Generates the manifest data used for the client-side manifest and types generation. + * @param {{ + * config: import('types').ValidatedConfig; + * fallback?: string; + * cwd?: string; + * }} opts + * @returns {import('types').ManifestData} + */ +export default function create_manifest_data({ + config, + fallback = `${runtime_directory}/components/${isSvelte5Plus() ? 'svelte-5' : 'svelte-4'}`, + cwd = process.cwd() +}) { + const assets = create_assets(config); + const hooks = create_hooks(config, cwd); + const matchers = create_matchers(config, cwd); + const { nodes, routes } = create_routes_and_nodes(cwd, config, fallback); + + for (const route of routes) { + for (const param of route.params) { + if (param.matcher && !matchers[param.matcher]) { + throw new Error(`No matcher found for parameter '${param.matcher}' in route ${route.id}`); + } + } + } + + return { + assets, + hooks, + matchers, + nodes, + routes + }; +} + +/** + * @param {import('types').ValidatedConfig} config + */ +export function create_assets(config) { + return list_files(config.kit.files.assets).map((file) => ({ + file, + size: fs.statSync(path.resolve(config.kit.files.assets, file)).size, + type: lookup(file) || null + })); +} + +/** + * @param {import('types').ValidatedConfig} config + * @param {string} cwd + */ +function create_hooks(config, cwd) { + const client = resolve_entry(config.kit.files.hooks.client); + const server = resolve_entry(config.kit.files.hooks.server); + const universal = resolve_entry(config.kit.files.hooks.universal); + + return { + client: client && posixify(path.relative(cwd, client)), + server: server && posixify(path.relative(cwd, server)), + universal: universal && posixify(path.relative(cwd, universal)) + }; +} + +/** + * @param {import('types').ValidatedConfig} config + * @param {string} cwd + */ +function create_matchers(config, cwd) { + const params_base = path.relative(cwd, config.kit.files.params); + + /** @type {Record} */ + const matchers = {}; + if (fs.existsSync(config.kit.files.params)) { + for (const file of fs.readdirSync(config.kit.files.params)) { + const ext = path.extname(file); + if (!config.kit.moduleExtensions.includes(ext)) continue; + const type = file.slice(0, -ext.length); + + if (/^\w+$/.test(type)) { + const matcher_file = path.join(params_base, file); + + // Disallow same matcher with different extensions + if (matchers[type]) { + throw new Error(`Duplicate matchers: ${matcher_file} and ${matchers[type]}`); + } else { + matchers[type] = matcher_file; + } + } else { + // Allow for matcher test collocation + if (type.endsWith('.test') || type.endsWith('.spec')) continue; + + throw new Error( + `Matcher names can only have underscores and alphanumeric characters — "${file}" is invalid` + ); + } + } + } + + return matchers; +} + +/** + * @param {import('types').ValidatedConfig} config + * @param {string} cwd + * @param {string} fallback + */ +function create_routes_and_nodes(cwd, config, fallback) { + /** @type {import('types').RouteData[]} */ + const routes = []; + + const routes_base = posixify(path.relative(cwd, config.kit.files.routes)); + + const valid_extensions = [...config.extensions, ...config.kit.moduleExtensions]; + + /** @type {import('types').PageNode[]} */ + const nodes = []; + + if (fs.existsSync(config.kit.files.routes)) { + /** + * @param {number} depth + * @param {string} id + * @param {string} segment + * @param {import('types').RouteData | null} parent + */ + const walk = (depth, id, segment, parent) => { + const unescaped = id.replace(/\[([ux])\+([^\]]+)\]/gi, (match, type, code) => { + if (match !== match.toLowerCase()) { + throw new Error(`Character escape sequence in ${id} must be lowercase`); + } + + if (!/[0-9a-f]+/.test(code)) { + throw new Error(`Invalid character escape sequence in ${id}`); + } + + if (type === 'x') { + if (code.length !== 2) { + throw new Error(`Hexadecimal escape sequence in ${id} must be two characters`); + } + + return String.fromCharCode(parseInt(code, 16)); + } else { + if (code.length < 4 || code.length > 6) { + throw new Error( + `Unicode escape sequence in ${id} must be between four and six characters` + ); + } + + return String.fromCharCode(parseInt(code, 16)); + } + }); + + if (/\]\[/.test(unescaped)) { + throw new Error(`Invalid route ${id} — parameters must be separated`); + } + + if (count_occurrences('[', id) !== count_occurrences(']', id)) { + throw new Error(`Invalid route ${id} — brackets are unbalanced`); + } + + if (/#/.test(segment)) { + // Vite will barf on files with # in them + throw new Error(`Route ${id} should be renamed to ${id.replace(/#/g, '[x+23]')}`); + } + + if (/\[\.\.\.\w+\]\/\[\[/.test(id)) { + throw new Error( + `Invalid route ${id} — an [[optional]] route segment cannot follow a [...rest] route segment` + ); + } + + if (/\[\[\.\.\./.test(id)) { + throw new Error( + `Invalid route ${id} — a rest route segment is always optional, remove the outer square brackets` + ); + } + + const { pattern, params } = parse_route_id(id); + + /** @type {import('types').RouteData} */ + const route = { + id, + parent, + + segment, + pattern, + params, + + layout: null, + error: null, + leaf: null, + page: null, + endpoint: null + }; + + // important to do this before walking children, so that child + // routes appear later + routes.push(route); + + // if we don't do this, the route map becomes unwieldy to console.log + Object.defineProperty(route, 'parent', { enumerable: false }); + + const dir = path.join(cwd, routes_base, id); + + // We can't use withFileTypes because of a NodeJs bug which returns wrong results + // with isDirectory() in case of symlinks: https://github.com/nodejs/node/issues/30646 + const files = fs.readdirSync(dir).map((name) => ({ + is_dir: fs.statSync(path.join(dir, name)).isDirectory(), + name + })); + + // process files first + for (const file of files) { + if (file.is_dir) continue; + + const ext = valid_extensions.find((ext) => file.name.endsWith(ext)); + if (!ext) continue; + + if (!file.name.startsWith('+')) { + const name = file.name.slice(0, -ext.length); + // check if it is a valid route filename but missing the + prefix + const typo = + /^(?:(page(?:@(.*))?)|(layout(?:@(.*))?)|(error))$/.test(name) || + /^(?:(server)|(page(?:(@[a-zA-Z0-9_-]*))?(\.server)?)|(layout(?:(@[a-zA-Z0-9_-]*))?(\.server)?))$/.test( + name + ); + if (typo) { + console.log( + colors + .bold() + .yellow( + `Missing route file prefix. Did you mean +${file.name}?` + + ` at ${path.join(dir, file.name)}` + ) + ); + } + + continue; + } + + if (file.name.endsWith('.d.ts')) { + let name = file.name.slice(0, -5); + const ext = valid_extensions.find((ext) => name.endsWith(ext)); + if (ext) name = name.slice(0, -ext.length); + + const valid = + /^\+(?:(page(?:@(.*))?)|(layout(?:@(.*))?)|(error))$/.test(name) || + /^\+(?:(server)|(page(?:(@[a-zA-Z0-9_-]*))?(\.server)?)|(layout(?:(@[a-zA-Z0-9_-]*))?(\.server)?))$/.test( + name + ); + + if (valid) continue; + } + + const project_relative = posixify(path.relative(cwd, path.join(dir, file.name))); + + const item = analyze( + project_relative, + file.name, + config.extensions, + config.kit.moduleExtensions + ); + + /** + * @param {string} type + * @param {string} existing_file + */ + function duplicate_files_error(type, existing_file) { + return new Error( + `Multiple ${type} files found in ${routes_base}${route.id} : ${path.basename( + existing_file + )} and ${file.name}` + ); + } + + if (item.kind === 'component') { + if (item.is_error) { + route.error = { + depth, + component: project_relative + }; + } else if (item.is_layout) { + if (!route.layout) { + route.layout = { depth, child_pages: [] }; + } else if (route.layout.component) { + throw duplicate_files_error('layout component', route.layout.component); + } + + route.layout.component = project_relative; + if (item.uses_layout !== undefined) route.layout.parent_id = item.uses_layout; + } else { + if (!route.leaf) { + route.leaf = { depth }; + } else if (route.leaf.component) { + throw duplicate_files_error('page component', route.leaf.component); + } + + route.leaf.component = project_relative; + if (item.uses_layout !== undefined) route.leaf.parent_id = item.uses_layout; + } + } else if (item.is_layout) { + if (!route.layout) { + route.layout = { depth, child_pages: [] }; + } else if (route.layout[item.kind]) { + throw duplicate_files_error( + item.kind + ' layout module', + /** @type {string} */ (route.layout[item.kind]) + ); + } + + route.layout[item.kind] = project_relative; + } else if (item.is_page) { + if (!route.leaf) { + route.leaf = { depth }; + } else if (route.leaf[item.kind]) { + throw duplicate_files_error( + item.kind + ' page module', + /** @type {string} */ (route.leaf[item.kind]) + ); + } + + route.leaf[item.kind] = project_relative; + } else { + if (route.endpoint) { + throw duplicate_files_error('endpoint', route.endpoint.file); + } + + route.endpoint = { + file: project_relative + }; + } + } + + // then handle children + for (const file of files) { + if (file.is_dir) { + walk(depth + 1, path.posix.join(id, file.name), file.name, route); + } + } + }; + + walk(0, '/', '', null); + + if (routes.length === 1) { + const root = routes[0]; + if (!root.leaf && !root.error && !root.layout && !root.endpoint) { + throw new Error( + 'No routes found. If you are using a custom src/routes directory, make sure it is specified in svelte.config.js' + ); + } + } + } else { + // If there's no routes directory, we'll just create a single empty route. This ensures the root layout and + // error components are included in the manifest, which is needed for subsequent build/dev commands to work + routes.push({ + id: '/', + segment: '', + pattern: /^$/, + params: [], + parent: null, + layout: null, + error: null, + leaf: null, + page: null, + endpoint: null + }); + } + + prevent_conflicts(routes); + + const root = routes[0]; + + if (!root.layout?.component) { + if (!root.layout) root.layout = { depth: 0, child_pages: [] }; + root.layout.component = posixify(path.relative(cwd, `${fallback}/layout.svelte`)); + } + + if (!root.error?.component) { + if (!root.error) root.error = { depth: 0 }; + root.error.component = posixify(path.relative(cwd, `${fallback}/error.svelte`)); + } + + // we do layouts/errors first as they are more likely to be reused, + // and smaller indexes take fewer bytes. also, this guarantees that + // the default error/layout are 0/1 + for (const route of routes) { + if (route.layout) { + if (!route.layout?.component) { + route.layout.component = posixify(path.relative(cwd, `${fallback}/layout.svelte`)); + } + nodes.push(route.layout); + } + if (route.error) nodes.push(route.error); + } + + for (const route of routes) { + if (route.leaf) nodes.push(route.leaf); + } + + const indexes = new Map(nodes.map((node, i) => [node, i])); + + for (const route of routes) { + if (!route.leaf) continue; + + route.page = { + layouts: [], + errors: [], + leaf: /** @type {number} */ (indexes.get(route.leaf)) + }; + + /** @type {import('types').RouteData | null} */ + let current_route = route; + let current_node = route.leaf; + let parent_id = route.leaf.parent_id; + + while (current_route) { + if (parent_id === undefined || current_route.segment === parent_id) { + if (current_route.layout || current_route.error) { + route.page.layouts.unshift( + current_route.layout ? indexes.get(current_route.layout) : undefined + ); + route.page.errors.unshift( + current_route.error ? indexes.get(current_route.error) : undefined + ); + } + + if (current_route.layout) { + /** @type {import('types').PageNode[]} */ (current_route.layout.child_pages).push( + route.leaf + ); + current_node.parent = current_node = current_route.layout; + parent_id = current_node.parent_id; + } else { + parent_id = undefined; + } + } + + current_route = current_route.parent; + } + + if (parent_id !== undefined) { + throw new Error(`${current_node.component} references missing segment "${parent_id}"`); + } + } + + return { + nodes, + routes: sort_routes(routes) + }; +} + +/** + * @param {string} project_relative + * @param {string} file + * @param {string[]} component_extensions + * @param {string[]} module_extensions + * @returns {import('./types.js').RouteFile} + */ +function analyze(project_relative, file, component_extensions, module_extensions) { + const component_extension = component_extensions.find((ext) => file.endsWith(ext)); + if (component_extension) { + const name = file.slice(0, -component_extension.length); + const pattern = /^\+(?:(page(?:@(.*))?)|(layout(?:@(.*))?)|(error))$/; + const match = pattern.exec(name); + if (!match) { + throw new Error(`Files prefixed with + are reserved (saw ${project_relative})`); + } + + return { + kind: 'component', + is_page: !!match[1], + is_layout: !!match[3], + is_error: !!match[5], + uses_layout: match[2] ?? match[4] + }; + } + + const module_extension = module_extensions.find((ext) => file.endsWith(ext)); + if (module_extension) { + const name = file.slice(0, -module_extension.length); + const pattern = + /^\+(?:(server)|(page(?:(@[a-zA-Z0-9_-]*))?(\.server)?)|(layout(?:(@[a-zA-Z0-9_-]*))?(\.server)?))$/; + const match = pattern.exec(name); + if (!match) { + throw new Error(`Files prefixed with + are reserved (saw ${project_relative})`); + } else if (match[3] || match[6]) { + throw new Error( + // prettier-ignore + `Only Svelte files can reference named layouts. Remove '${match[3] || match[6]}' from ${file} (at ${project_relative})` + ); + } + + const kind = match[1] || match[4] || match[7] ? 'server' : 'universal'; + + return { + kind, + is_page: !!match[2], + is_layout: !!match[5] + }; + } + + throw new Error(`Files and directories prefixed with + are reserved (saw ${project_relative})`); +} + +/** + * @param {string} needle + * @param {string} haystack + */ +function count_occurrences(needle, haystack) { + let count = 0; + for (let i = 0; i < haystack.length; i += 1) { + if (haystack[i] === needle) count += 1; + } + return count; +} + +/** @param {import('types').RouteData[]} routes */ +function prevent_conflicts(routes) { + /** @type {Map} */ + const lookup = new Map(); + + for (const route of routes) { + if (!route.leaf && !route.endpoint) continue; + + const normalized = normalize_route_id(route.id); + + // find all permutations created by optional parameters + const split = normalized.split(/<\?(.+?)>/g); + + let permutations = [/** @type {string} */ (split[0])]; + + // turn `x/[[optional]]/y` into `x/y` and `x/[required]/y` + for (let i = 1; i < split.length; i += 2) { + const matcher = split[i]; + const next = split[i + 1]; + + permutations = permutations.reduce((a, b) => { + a.push(b + next); + if (!(matcher === '*' && b.endsWith('//'))) a.push(b + `<${matcher}>${next}`); + return a; + }, /** @type {string[]} */ ([])); + } + + for (const permutation of permutations) { + // remove leading/trailing/duplicated slashes caused by prior + // manipulation of optional parameters and (groups) + const key = permutation + .replace(/\/{2,}/, '/') + .replace(/^\//, '') + .replace(/\/$/, ''); + + if (lookup.has(key)) { + throw new Error( + `The "${lookup.get(key)}" and "${route.id}" routes conflict with each other` + ); + } + + lookup.set(key, route.id); + } + } +} + +/** @param {string} id */ +function normalize_route_id(id) { + return ( + id + // remove groups + .replace(/(?<=^|\/)\(.+?\)(?=$|\/)/g, '') + + .replace(/\[[ux]\+([0-9a-f]+)\]/g, (_, x) => + String.fromCharCode(parseInt(x, 16)).replace(/\//g, '%2f') + ) + + // replace `[param]` with `<*>`, `[param=x]` with ``, and `[[param]]` with `` + .replace( + /\[(?:(\[)|(\.\.\.))?.+?(=.+?)?\]\]?/g, + (_, optional, rest, matcher) => `<${optional ? '?' : ''}${rest ?? ''}${matcher ?? '*'}>` + ) + ); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/sort.js b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/sort.js new file mode 100644 index 00000000..9addd2c3 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/sort.js @@ -0,0 +1,161 @@ +import { get_route_segments } from '../../../utils/routing.js'; + +/** + * @typedef {{ + * type: 'static' | 'required' | 'optional' | 'rest'; + * content: string; + * matched: boolean; + * }} Part + */ + +/** + * @typedef {Part[]} Segment + */ + +const EMPTY = { type: 'static', content: '', matched: false }; + +/** @param {import('types').RouteData[]} routes */ +export function sort_routes(routes) { + /** @type {Map} */ + const segment_cache = new Map(); + + /** @param {string} segment */ + function get_parts(segment) { + if (!segment_cache.has(segment)) { + segment_cache.set(segment, split(segment)); + } + + return segment_cache.get(segment); + } + + /** @param {string} id */ + function split(id) { + /** @type {Part[]} */ + const parts = []; + + let i = 0; + while (i <= id.length) { + const start = id.indexOf('[', i); + if (start === -1) { + parts.push({ type: 'static', content: id.slice(i), matched: false }); + break; + } + + parts.push({ type: 'static', content: id.slice(i, start), matched: false }); + + const type = id[start + 1] === '[' ? 'optional' : id[start + 1] === '.' ? 'rest' : 'required'; + const delimiter = type === 'optional' ? ']]' : ']'; + const end = id.indexOf(delimiter, start); + + if (end === -1) { + throw new Error(`Invalid route ID ${id}`); + } + + const content = id.slice(start, (i = end + delimiter.length)); + + parts.push({ + type, + content, + matched: content.includes('=') + }); + } + + return parts; + } + + return routes.sort((route_a, route_b) => { + const segments_a = split_route_id(route_a.id).map(get_parts); + const segments_b = split_route_id(route_b.id).map(get_parts); + + for (let i = 0; i < Math.max(segments_a.length, segments_b.length); i += 1) { + const segment_a = segments_a[i] ?? [EMPTY]; + const segment_b = segments_b[i] ?? [EMPTY]; + + for (let j = 0; j < Math.max(segment_a.length, segment_b.length); j += 1) { + const a = segment_a[j]; + const b = segment_b[j]; + + // first part of each segment is always static + // (though it may be the empty string), then + // it alternates between dynamic and static + // (i.e. [foo][bar] is disallowed) + const dynamic = j % 2 === 1; + + if (dynamic) { + if (!a) return -1; + if (!b) return +1; + + // get the next static chunk, so we can handle [...rest] edge cases + const next_a = segment_a[j + 1].content || segments_a[i + 1]?.[0].content; + const next_b = segment_b[j + 1].content || segments_b[i + 1]?.[0].content; + + // `[...rest]/x` outranks `[...rest]` + if (a.type === 'rest' && b.type === 'rest') { + if (next_a && next_b) continue; + if (next_a) return -1; + if (next_b) return +1; + } + + // `[...rest]/x` outranks `[required]` or `[required]/[required]` + // but not `[required]/x` + if (a.type === 'rest') { + return next_a && !next_b ? -1 : +1; + } + + if (b.type === 'rest') { + return next_b && !next_a ? +1 : -1; + } + + // part with matcher outranks one without + if (a.matched !== b.matched) { + return a.matched ? -1 : +1; + } + + if (a.type !== b.type) { + // `[...rest]` has already been accounted for, so here + // we're comparing between `[required]` and `[[optional]]` + if (a.type === 'required') return -1; + if (b.type === 'required') return +1; + } + } else if (a.content !== b.content) { + // shallower path outranks deeper path + if (a === EMPTY) return -1; + if (b === EMPTY) return +1; + + return sort_static(a.content, b.content); + } + } + } + + return route_a.id < route_b.id ? +1 : -1; + }); +} + +/** @param {string} id */ +function split_route_id(id) { + return get_route_segments( + id + // remove all [[optional]] parts unless they're at the very end + .replace(/\[\[[^\]]+\]\](?!$)/g, '') + ).filter(Boolean); +} + +/** + * Sort two strings lexicographically, except `foobar` outranks `foo` + * @param {string} a + * @param {string} b + */ +function sort_static(a, b) { + if (a === b) return 0; + + for (let i = 0; true; i += 1) { + const char_a = a[i]; + const char_b = b[i]; + + if (char_a !== char_b) { + if (char_a === undefined) return +1; + if (char_b === undefined) return -1; + return char_a < char_b ? -1 : +1; + } + } +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/types.d.ts b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/types.d.ts new file mode 100644 index 00000000..ec5c01b8 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/types.d.ts @@ -0,0 +1,37 @@ +import { PageNode } from 'types'; + +interface Part { + dynamic: boolean; + optional: boolean; + rest: boolean; + type: string | null; +} + +interface RouteTreeNode { + error: PageNode | undefined; + layout: PageNode | undefined; +} + +export type RouteTree = Map; + +interface RouteComponent { + kind: 'component'; + is_page: boolean; + is_layout: boolean; + is_error: boolean; + uses_layout: string | undefined; +} + +interface RouteSharedModule { + kind: 'universal'; + is_page: boolean; + is_layout: boolean; +} + +interface RouteServerModule { + kind: 'server'; + is_page: boolean; + is_layout: boolean; +} + +export type RouteFile = RouteComponent | RouteSharedModule | RouteServerModule; diff --git a/node_modules/@sveltejs/kit/src/core/sync/sync.js b/node_modules/@sveltejs/kit/src/core/sync/sync.js new file mode 100644 index 00000000..a96e40bc --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/sync.js @@ -0,0 +1,78 @@ +import path from 'node:path'; +import create_manifest_data from './create_manifest_data/index.js'; +import { write_client_manifest } from './write_client_manifest.js'; +import { write_root } from './write_root.js'; +import { write_tsconfig } from './write_tsconfig.js'; +import { write_types, write_all_types } from './write_types/index.js'; +import { write_ambient } from './write_ambient.js'; +import { write_non_ambient } from './write_non_ambient.js'; +import { write_server } from './write_server.js'; + +/** + * Initialize SvelteKit's generated files. + * @param {import('types').ValidatedConfig} config + * @param {string} mode + */ +export function init(config, mode) { + write_tsconfig(config.kit); + write_ambient(config.kit, mode); + write_non_ambient(config.kit); +} + +/** + * Update SvelteKit's generated files + * @param {import('types').ValidatedConfig} config + */ +export function create(config) { + const manifest_data = create_manifest_data({ config }); + + const output = path.join(config.kit.outDir, 'generated'); + + write_client_manifest(config.kit, manifest_data, `${output}/client`); + write_server(config, output); + write_root(manifest_data, output); + write_all_types(config, manifest_data); + + return { manifest_data }; +} + +/** + * Update SvelteKit's generated files in response to a single file content update. + * Do not call this when the file in question was created/deleted. + * + * @param {import('types').ValidatedConfig} config + * @param {import('types').ManifestData} manifest_data + * @param {string} file + */ +export function update(config, manifest_data, file) { + write_types(config, manifest_data, file); +} + +/** + * Run sync.init and sync.create in series, returning the result from sync.create. + * @param {import('types').ValidatedConfig} config + * @param {string} mode The Vite mode + */ +export function all(config, mode) { + init(config, mode); + return create(config); +} + +/** + * Run sync.init and then generate all type files. + * @param {import('types').ValidatedConfig} config + * @param {string} mode The Vite mode + */ +export function all_types(config, mode) { + init(config, mode); + const manifest_data = create_manifest_data({ config }); + write_all_types(config, manifest_data); +} + +/** + * Regenerate __SERVER__/internal.js in response to src/{app.html,error.html,service-worker.js} changing + * @param {import('types').ValidatedConfig} config + */ +export function server(config) { + write_server(config, path.join(config.kit.outDir, 'generated')); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/ts.js b/node_modules/@sveltejs/kit/src/core/sync/ts.js new file mode 100644 index 00000000..61c79e37 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/ts.js @@ -0,0 +1,6 @@ +/** @type {import('typescript')} */ +// @ts-ignore +export let ts = undefined; +try { + ts = (await import('typescript')).default; +} catch {} diff --git a/node_modules/@sveltejs/kit/src/core/sync/utils.js b/node_modules/@sveltejs/kit/src/core/sync/utils.js new file mode 100644 index 00000000..cf35fadb --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/utils.js @@ -0,0 +1,85 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { mkdirp } from '../../utils/filesystem.js'; +import { resolve_peer_dependency } from '../../utils/import.js'; + +/** @type {string} */ +let VERSION; + +try { + ({ VERSION } = await resolve_peer_dependency('svelte/compiler')); +} catch { + // we can end up here from e.g. unit tests. this is the simplest fix + ({ VERSION } = await import('svelte/compiler')); +} + +/** @type {Map} */ +const previous_contents = new Map(); + +/** + * @param {string} file + * @param {string} code + */ +export function write_if_changed(file, code) { + if (code !== previous_contents.get(file)) { + write(file, code); + } +} + +/** + * @param {string} file + * @param {string} code + */ +export function write(file, code) { + previous_contents.set(file, code); + mkdirp(path.dirname(file)); + fs.writeFileSync(file, code); +} + +/** @type {WeakMap} */ +const dedent_map = new WeakMap(); + +/** + * Allows indenting template strings without the extra indentation ending up in the result. + * Still allows indentation of lines relative to one another in the template string. + * @param {TemplateStringsArray} strings + * @param {any[]} values + */ +export function dedent(strings, ...values) { + let dedented = dedent_map.get(strings); + + if (!dedented) { + const indentation = /** @type {RegExpExecArray} */ (/\n?([ \t]*)/.exec(strings[0]))[1]; + const pattern = new RegExp(`^${indentation}`, 'gm'); + + dedented = { + strings: strings.map((str) => str.replace(pattern, '')), + indents: [] + }; + + let current = '\n'; + + for (let i = 0; i < values.length; i += 1) { + const string = dedented.strings[i]; + const match = /\n([ \t]*)$/.exec(string); + + if (match) current = match[0]; + dedented.indents[i] = current; + } + + dedent_map.set(strings, dedented); + } + + let str = dedented.strings[0]; + for (let i = 0; i < values.length; i += 1) { + str += String(values[i]).replace(/\n/g, dedented.indents[i]) + dedented.strings[i + 1]; + } + + str = str.trim(); + + return str; +} + +export function isSvelte5Plus() { + return Number(VERSION[0]) >= 5; +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_ambient.js b/node_modules/@sveltejs/kit/src/core/sync/write_ambient.js new file mode 100644 index 00000000..40a871cb --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_ambient.js @@ -0,0 +1,63 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { get_env } from '../../exports/vite/utils.js'; +import { GENERATED_COMMENT } from '../../constants.js'; +import { create_dynamic_types, create_static_types } from '../env.js'; +import { write_if_changed } from './utils.js'; + +// TODO these types should be described in a neutral place, rather than +// inside either `packages/kit` or `kit.svelte.dev` +const descriptions_dir = fileURLToPath(new URL('../../../src/types/synthetic', import.meta.url)); + +/** @param {string} filename */ +function read_description(filename) { + const content = fs.readFileSync(`${descriptions_dir}/${filename}`, 'utf8'); + return `/**\n${content + .trim() + .split('\n') + .map((line) => ` * ${line}`) + .join('\n')}\n */`; +} + +/** + * @param {import('types').Env} env + * @param {{ + * public_prefix: string; + * private_prefix: string; + * }} prefixes + */ +const template = (env, prefixes) => ` +${GENERATED_COMMENT} + +/// + +${read_description('$env+static+private.md')} +${create_static_types('private', env)} + +${read_description('$env+static+public.md')} +${create_static_types('public', env)} + +${read_description('$env+dynamic+private.md')} +${create_dynamic_types('private', env, prefixes)} + +${read_description('$env+dynamic+public.md')} +${create_dynamic_types('public', env, prefixes)} +`; + +/** + * Writes ambient declarations including types reference to @sveltejs/kit, + * and the existing environment variables in process.env to + * $env/static/private and $env/static/public + * @param {import('types').ValidatedKitConfig} config + * @param {string} mode The Vite mode + */ +export function write_ambient(config, mode) { + const env = get_env(config.env, mode); + const { publicPrefix: public_prefix, privatePrefix: private_prefix } = config.env; + + write_if_changed( + path.join(config.outDir, 'ambient.d.ts'), + template(env, { public_prefix, private_prefix }) + ); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_client_manifest.js b/node_modules/@sveltejs/kit/src/core/sync/write_client_manifest.js new file mode 100644 index 00000000..1b97ed02 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_client_manifest.js @@ -0,0 +1,179 @@ +import path from 'node:path'; +import { relative_path, resolve_entry } from '../../utils/filesystem.js'; +import { s } from '../../utils/misc.js'; +import { dedent, isSvelte5Plus, write_if_changed } from './utils.js'; +import colors from 'kleur'; + +/** + * Writes the client manifest to disk. The manifest is used to power the router. It contains the + * list of routes and corresponding Svelte components (i.e. pages and layouts). + * @param {import('types').ValidatedKitConfig} kit + * @param {import('types').ManifestData} manifest_data + * @param {string} output + * @param {Array<{ has_server_load: boolean }>} [metadata] + */ +export function write_client_manifest(kit, manifest_data, output, metadata) { + /** + * Creates a module that exports a `CSRPageNode` + * @param {import('types').PageNode} node + */ + function generate_node(node) { + const declarations = []; + + if (node.universal) { + declarations.push( + `import * as universal from ${s(relative_path(`${output}/nodes`, node.universal))};`, + 'export { universal };' + ); + } + + if (node.component) { + declarations.push( + `export { default as component } from ${s( + relative_path(`${output}/nodes`, node.component) + )};` + ); + } + + return declarations.join('\n'); + } + + /** @type {Map} */ + const indices = new Map(); + const nodes = manifest_data.nodes + .map((node, i) => { + indices.set(node, i); + + write_if_changed(`${output}/nodes/${i}.js`, generate_node(node)); + return `() => import('./nodes/${i}')`; + }) + .join(',\n'); + + const layouts_with_server_load = new Set(); + + const dictionary = dedent` + { + ${manifest_data.routes + .map((route) => { + if (route.page) { + const errors = route.page.errors.slice(1).map((n) => n ?? ''); + const layouts = route.page.layouts.slice(1).map((n) => n ?? ''); + + while (layouts.at(-1) === '') layouts.pop(); + while (errors.at(-1) === '') errors.pop(); + + let leaf_has_server_load = false; + if (route.leaf) { + if (metadata) { + const i = /** @type {number} */ (indices.get(route.leaf)); + + leaf_has_server_load = metadata[i].has_server_load; + } else if (route.leaf.server) { + leaf_has_server_load = true; + } + } + + // Encode whether or not the route uses server data + // using the ones' complement, to save space + const array = [`${leaf_has_server_load ? '~' : ''}${route.page.leaf}`]; + + // Encode whether or not the layout uses server data. + // It's a different method compared to pages because layouts + // are reused across pages, so we save space by doing it this way. + route.page.layouts.forEach((layout) => { + if (layout == undefined) return; + + let layout_has_server_load = false; + + if (metadata) { + layout_has_server_load = metadata[layout].has_server_load; + } else if (manifest_data.nodes[layout].server) { + layout_has_server_load = true; + } + + if (layout_has_server_load) { + layouts_with_server_load.add(layout); + } + }); + + // only include non-root layout/error nodes if they exist + if (layouts.length > 0 || errors.length > 0) array.push(`[${layouts.join(',')}]`); + if (errors.length > 0) array.push(`[${errors.join(',')}]`); + + return `${s(route.id)}: [${array.join(',')}]`; + } + }) + .filter(Boolean) + .join(',\n')} + } + `; + + const client_hooks_file = resolve_entry(kit.files.hooks.client); + const universal_hooks_file = resolve_entry(kit.files.hooks.universal); + + const typo = resolve_entry('src/+hooks.client'); + if (typo) { + console.log( + colors + .bold() + .yellow( + `Unexpected + prefix. Did you mean ${typo.split('/').at(-1)?.slice(1)}?` + + ` at ${path.resolve(typo)}` + ) + ); + } + + write_if_changed( + `${output}/app.js`, + dedent` + ${ + client_hooks_file + ? `import * as client_hooks from '${relative_path(output, client_hooks_file)}';` + : '' + } + ${ + universal_hooks_file + ? `import * as universal_hooks from '${relative_path(output, universal_hooks_file)}';` + : '' + } + + export { matchers } from './matchers.js'; + + export const nodes = [ + ${nodes} + ]; + + export const server_loads = [${[...layouts_with_server_load].join(',')}]; + + export const dictionary = ${dictionary}; + + export const hooks = { + handleError: ${ + client_hooks_file ? 'client_hooks.handleError || ' : '' + }(({ error }) => { console.error(error) }), + + reroute: ${universal_hooks_file ? 'universal_hooks.reroute || ' : ''}(() => {}) + }; + + export { default as root } from '../root.${isSvelte5Plus() ? 'js' : 'svelte'}'; + ` + ); + + // write matchers to a separate module so that we don't + // need to worry about name conflicts + const imports = []; + const matchers = []; + + for (const key in manifest_data.matchers) { + const src = manifest_data.matchers[key]; + + imports.push(`import { match as ${key} } from ${s(relative_path(output, src))};`); + matchers.push(key); + } + + const module = imports.length + ? `${imports.join('\n')}\n\nexport const matchers = { ${matchers.join(', ')} };` + : 'export const matchers = {};'; + + write_if_changed(`${output}/matchers.js`, module); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_non_ambient.js b/node_modules/@sveltejs/kit/src/core/sync/write_non_ambient.js new file mode 100644 index 00000000..a191495a --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_non_ambient.js @@ -0,0 +1,42 @@ +import path from 'node:path'; +import { GENERATED_COMMENT } from '../../constants.js'; +import { write_if_changed } from './utils.js'; + +// `declare module "svelte/elements"` needs to happen in a non-ambient module, and dts-buddy generates one big ambient module, +// so we can't add it there - therefore generate the typings ourselves here. +// We're not using the `declare namespace svelteHTML` variant because that one doesn't augment the HTMLAttributes interface +// people could use to type their own components. +// The T generic is needed or else there's a "all declarations must have identical type parameters" error. +const template = ` +${GENERATED_COMMENT} + +declare module "svelte/elements" { + export interface HTMLAttributes { + 'data-sveltekit-keepfocus'?: true | '' | 'off' | undefined | null; + 'data-sveltekit-noscroll'?: true | '' | 'off' | undefined | null; + 'data-sveltekit-preload-code'?: + | true + | '' + | 'eager' + | 'viewport' + | 'hover' + | 'tap' + | 'off' + | undefined + | null; + 'data-sveltekit-preload-data'?: true | '' | 'hover' | 'tap' | 'off' | undefined | null; + 'data-sveltekit-reload'?: true | '' | 'off' | undefined | null; + 'data-sveltekit-replacestate'?: true | '' | 'off' | undefined | null; + } +} + +export {}; +`; + +/** + * Writes non-ambient declarations to the output directory + * @param {import('types').ValidatedKitConfig} config + */ +export function write_non_ambient(config) { + write_if_changed(path.join(config.outDir, 'non-ambient.d.ts'), template); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_root.js b/node_modules/@sveltejs/kit/src/core/sync/write_root.js new file mode 100644 index 00000000..4440d53b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_root.js @@ -0,0 +1,159 @@ +import { dedent, isSvelte5Plus, write_if_changed } from './utils.js'; + +/** + * @param {import('types').ManifestData} manifest_data + * @param {string} output + */ +export function write_root(manifest_data, output) { + // TODO remove default layout altogether + + const max_depth = Math.max( + ...manifest_data.routes.map((route) => + route.page ? route.page.layouts.filter(Boolean).length + 1 : 0 + ), + 1 + ); + + const levels = []; + for (let i = 0; i <= max_depth; i += 1) { + levels.push(i); + } + + let l = max_depth; + + let pyramid = dedent` + ${ + isSvelte5Plus() + ? ` + ` + : `` + }`; + + while (l--) { + pyramid = dedent` + {#if constructors[${l + 1}]} + ${ + isSvelte5Plus() + ? dedent`{@const Pyramid_${l} = constructors[${l}]} + + + ${pyramid} + ` + : dedent` + ${pyramid} + ` + } + + {:else} + ${ + isSvelte5Plus() + ? dedent` + {@const Pyramid_${l} = constructors[${l}]} + + + ` + : dedent`` + } + + {/if} + `; + } + + write_if_changed( + `${output}/root.svelte`, + dedent` + + ${isSvelte5Plus() ? '' : ''} + + + ${pyramid} + + {#if mounted} +
+ {#if navigated} + {title} + {/if} +
+ {/if} + ` + ); + + if (isSvelte5Plus()) { + write_if_changed( + `${output}/root.js`, + dedent` + import { asClassComponent } from 'svelte/legacy'; + import Root from './root.svelte'; + export default asClassComponent(Root); + ` + ); + } +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_server.js b/node_modules/@sveltejs/kit/src/core/sync/write_server.js new file mode 100644 index 00000000..eb50bfd4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_server.js @@ -0,0 +1,119 @@ +import path from 'node:path'; +import process from 'node:process'; +import { hash } from '../../runtime/hash.js'; +import { posixify, resolve_entry } from '../../utils/filesystem.js'; +import { s } from '../../utils/misc.js'; +import { load_error_page, load_template } from '../config/index.js'; +import { runtime_directory } from '../utils.js'; +import { isSvelte5Plus, write_if_changed } from './utils.js'; +import colors from 'kleur'; + +/** + * @param {{ + * server_hooks: string | null; + * universal_hooks: string | null; + * config: import('types').ValidatedConfig; + * has_service_worker: boolean; + * runtime_directory: string; + * template: string; + * error_page: string; + * }} opts + */ +const server_template = ({ + config, + server_hooks, + universal_hooks, + has_service_worker, + runtime_directory, + template, + error_page +}) => ` +import root from '../root.${isSvelte5Plus() ? 'js' : 'svelte'}'; +import { set_building, set_prerendering } from '__sveltekit/environment'; +import { set_assets } from '__sveltekit/paths'; +import { set_manifest, set_read_implementation } from '__sveltekit/server'; +import { set_private_env, set_public_env, set_safe_public_env } from '${runtime_directory}/shared-server.js'; + +export const options = { + app_dir: ${s(config.kit.appDir)}, + app_template_contains_nonce: ${template.includes('%sveltekit.nonce%')}, + csp: ${s(config.kit.csp)}, + csrf_check_origin: ${s(config.kit.csrf.checkOrigin)}, + embedded: ${config.kit.embedded}, + env_public_prefix: '${config.kit.env.publicPrefix}', + env_private_prefix: '${config.kit.env.privatePrefix}', + hooks: null, // added lazily, via \`get_hooks\` + preload_strategy: ${s(config.kit.output.preloadStrategy)}, + root, + service_worker: ${has_service_worker}, + templates: { + app: ({ head, body, assets, nonce, env }) => ${s(template) + .replace('%sveltekit.head%', '" + head + "') + .replace('%sveltekit.body%', '" + body + "') + .replace(/%sveltekit\.assets%/g, '" + assets + "') + .replace(/%sveltekit\.nonce%/g, '" + nonce + "') + .replace( + /%sveltekit\.env\.([^%]+)%/g, + (_match, capture) => `" + (env[${s(capture)}] ?? "") + "` + )}, + error: ({ status, message }) => ${s(error_page) + .replace(/%sveltekit\.status%/g, '" + status + "') + .replace(/%sveltekit\.error\.message%/g, '" + message + "')} + }, + version_hash: ${s(hash(config.kit.version.name))} +}; + +export async function get_hooks() { + return { + ${server_hooks ? `...(await import(${s(server_hooks)})),` : ''} + ${universal_hooks ? `...(await import(${s(universal_hooks)})),` : ''} + }; +} + +export { set_assets, set_building, set_manifest, set_prerendering, set_private_env, set_public_env, set_read_implementation, set_safe_public_env }; +`; + +// TODO need to re-run this whenever src/app.html or src/error.html are +// created or changed, or src/service-worker.js is created or deleted. +// Also, need to check that updating hooks.server.js works + +/** + * Write server configuration to disk + * @param {import('types').ValidatedConfig} config + * @param {string} output + */ +export function write_server(config, output) { + const server_hooks_file = resolve_entry(config.kit.files.hooks.server); + const universal_hooks_file = resolve_entry(config.kit.files.hooks.universal); + + const typo = resolve_entry('src/+hooks.server'); + if (typo) { + console.log( + colors + .bold() + .yellow( + `Unexpected + prefix. Did you mean ${typo.split('/').at(-1)?.slice(1)}?` + + ` at ${path.resolve(typo)}` + ) + ); + } + + /** @param {string} file */ + function relative(file) { + return posixify(path.relative(`${output}/server`, file)); + } + + write_if_changed( + `${output}/server/internal.js`, + server_template({ + config, + server_hooks: server_hooks_file ? relative(server_hooks_file) : null, + universal_hooks: universal_hooks_file ? relative(universal_hooks_file) : null, + has_service_worker: + config.kit.serviceWorker.register && !!resolve_entry(config.kit.files.serviceWorker), + runtime_directory: relative(runtime_directory), + template: load_template(process.cwd(), config), + error_page: load_error_page(config) + }) + ); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_tsconfig.js b/node_modules/@sveltejs/kit/src/core/sync/write_tsconfig.js new file mode 100644 index 00000000..48114dd5 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_tsconfig.js @@ -0,0 +1,238 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import process from 'node:process'; +import colors from 'kleur'; +import { posixify } from '../../utils/filesystem.js'; +import { write_if_changed } from './utils.js'; + +/** + * @param {string} cwd + * @param {string} file + */ +function maybe_file(cwd, file) { + const resolved = path.resolve(cwd, file); + if (fs.existsSync(resolved)) { + return resolved; + } +} + +/** + * @param {string} file + */ +function project_relative(file) { + return posixify(path.relative('.', file)); +} + +/** + * @param {string} file + */ +function remove_trailing_slashstar(file) { + if (file.endsWith('/*')) { + return file.slice(0, -2); + } else { + return file; + } +} + +/** + * Generates the tsconfig that the user's tsconfig inherits from. + * @param {import('types').ValidatedKitConfig} kit + */ +export function write_tsconfig(kit, cwd = process.cwd()) { + const out = path.join(kit.outDir, 'tsconfig.json'); + + const user_config = load_user_tsconfig(cwd); + if (user_config) validate_user_config(cwd, out, user_config); + + write_if_changed(out, JSON.stringify(get_tsconfig(kit), null, '\t')); +} + +/** + * Generates the tsconfig that the user's tsconfig inherits from. + * @param {import('types').ValidatedKitConfig} kit + */ +export function get_tsconfig(kit) { + /** @param {string} file */ + const config_relative = (file) => posixify(path.relative(kit.outDir, file)); + + const include = new Set([ + 'ambient.d.ts', // careful: changing this name would be a breaking change, because it's referenced in the service-workers documentation + 'non-ambient.d.ts', + './types/**/$types.d.ts', + config_relative('vite.config.js'), + config_relative('vite.config.ts') + ]); + // TODO(v2): find a better way to include all src files. We can't just use routes/lib only because + // people might have other folders/files in src that they want included. + const src_includes = [kit.files.routes, kit.files.lib, path.resolve('src')].filter((dir) => { + const relative = path.relative(path.resolve('src'), dir); + return !relative || relative.startsWith('..'); + }); + for (const dir of src_includes) { + include.add(config_relative(`${dir}/**/*.js`)); + include.add(config_relative(`${dir}/**/*.ts`)); + include.add(config_relative(`${dir}/**/*.svelte`)); + } + + // Test folder is a special case - we advocate putting tests in a top-level test folder + // and it's not configurable (should we make it?) + const test_folder = project_relative('tests'); + include.add(config_relative(`${test_folder}/**/*.js`)); + include.add(config_relative(`${test_folder}/**/*.ts`)); + include.add(config_relative(`${test_folder}/**/*.svelte`)); + + const exclude = [config_relative('node_modules/**')]; + // Add service worker to exclude list so that worker types references in it don't spill over into the rest of the app + // (i.e. suddenly ServiceWorkerGlobalScope would be available throughout the app, and some types might even clash) + if (path.extname(kit.files.serviceWorker)) { + exclude.push(config_relative(kit.files.serviceWorker)); + } else { + exclude.push(config_relative(`${kit.files.serviceWorker}.js`)); + exclude.push(config_relative(`${kit.files.serviceWorker}/**/*.js`)); + exclude.push(config_relative(`${kit.files.serviceWorker}.ts`)); + exclude.push(config_relative(`${kit.files.serviceWorker}/**/*.ts`)); + exclude.push(config_relative(`${kit.files.serviceWorker}.d.ts`)); + exclude.push(config_relative(`${kit.files.serviceWorker}/**/*.d.ts`)); + } + + const config = { + compilerOptions: { + // generated options + paths: get_tsconfig_paths(kit), + rootDirs: [config_relative('.'), './types'], + + // essential options + // svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript + // to enforce using \`import type\` instead of \`import\` for Types. + // Also, TypeScript doesn't know about import usages in the template because it only sees the + // script of a Svelte file. Therefore preserve all value imports. + verbatimModuleSyntax: true, + // Vite compiles modules one at a time + isolatedModules: true, + + // This is required for svelte-package to work as expected + // Can be overwritten + lib: ['esnext', 'DOM', 'DOM.Iterable'], + moduleResolution: 'bundler', + module: 'esnext', + noEmit: true, // prevent tsconfig error "overwriting input files" - Vite handles the build and ignores this + target: 'esnext' + }, + include: [...include], + exclude + }; + + return kit.typescript.config(config) ?? config; +} + +/** @param {string} cwd */ +function load_user_tsconfig(cwd) { + const file = maybe_file(cwd, 'tsconfig.json') || maybe_file(cwd, 'jsconfig.json'); + + if (!file) return; + + // we have to eval the file, since it's not parseable as JSON (contains comments) + const json = fs.readFileSync(file, 'utf-8'); + + return { + kind: path.basename(file), + options: (0, eval)(`(${json})`) + }; +} + +/** + * @param {string} cwd + * @param {string} out + * @param {{ kind: string, options: any }} config + */ +function validate_user_config(cwd, out, config) { + // we need to check that the user's tsconfig extends the framework config + const extend = config.options.extends; + const extends_framework_config = + typeof extend === 'string' + ? path.resolve(cwd, extend) === out + : Array.isArray(extend) + ? extend.some((e) => path.resolve(cwd, e) === out) + : false; + + const options = config.options.compilerOptions || {}; + + if (extends_framework_config) { + const { paths, baseUrl } = options; + + if (baseUrl || paths) { + console.warn( + colors + .bold() + .yellow( + `You have specified a baseUrl and/or paths in your ${config.kind} which interferes with SvelteKit's auto-generated tsconfig.json. ` + + 'Remove it to avoid problems with intellisense. For path aliases, use `kit.alias` instead: https://kit.svelte.dev/docs/configuration#alias' + ) + ); + } + } else { + let relative = posixify(path.relative('.', out)); + if (!relative.startsWith('./')) relative = './' + relative; + + console.warn( + colors + .bold() + .yellow(`Your ${config.kind} should extend the configuration generated by SvelteKit:`) + ); + console.warn(`{\n "extends": "${relative}"\n}`); + } +} + +// +const alias_regex = /^(.+?)(\/\*)?$/; +// +const value_regex = /^(.*?)((\/\*)|(\.\w+))?$/; + +/** + * Generates tsconfig path aliases from kit's aliases. + * Related to vite alias creation. + * + * @param {import('types').ValidatedKitConfig} config + */ +function get_tsconfig_paths(config) { + /** @param {string} file */ + const config_relative = (file) => { + let relative_path = path.relative(config.outDir, file); + if (!relative_path.startsWith('..')) { + relative_path = './' + relative_path; + } + return posixify(relative_path); + }; + + const alias = { ...config.alias }; + if (fs.existsSync(project_relative(config.files.lib))) { + alias['$lib'] = project_relative(config.files.lib); + } + + /** @type {Record} */ + const paths = {}; + + for (const [key, value] of Object.entries(alias)) { + const key_match = alias_regex.exec(key); + if (!key_match) throw new Error(`Invalid alias key: ${key}`); + + const value_match = value_regex.exec(value); + if (!value_match) throw new Error(`Invalid alias value: ${value}`); + + const rel_path = config_relative(remove_trailing_slashstar(value)); + const slashstar = key_match[2]; + + if (slashstar) { + paths[key] = [rel_path + '/*']; + } else { + paths[key] = [rel_path]; + const fileending = value_match[4]; + + if (!fileending && !(key + '/*' in alias)) { + paths[key + '/*'] = [rel_path + '/*']; + } + } + } + + return paths; +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_types/index.js b/node_modules/@sveltejs/kit/src/core/sync/write_types/index.js new file mode 100644 index 00000000..42728fea --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_types/index.js @@ -0,0 +1,854 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import process from 'node:process'; +import MagicString from 'magic-string'; +import { posixify, rimraf, walk } from '../../../utils/filesystem.js'; +import { compact } from '../../../utils/array.js'; +import { ts } from '../ts.js'; + +/** + * @typedef {{ + * file_name: string; + * modified: boolean; + * code: string; + * exports: any[]; + * } | null} Proxy + * + * @typedef {{ + * server: Proxy, + * universal: Proxy + * }} Proxies + * + * @typedef {Map} RoutesMap + */ + +const cwd = process.cwd(); + +/** + * Creates types for the whole manifest + * @param {import('types').ValidatedConfig} config + * @param {import('types').ManifestData} manifest_data + */ +export function write_all_types(config, manifest_data) { + if (!ts) return; + + const types_dir = `${config.kit.outDir}/types`; + + // empty out files that no longer need to exist + const routes_dir = posixify(path.relative('.', config.kit.files.routes)).replace(/\.\.\//g, ''); + const expected_directories = new Set( + manifest_data.routes.map((route) => path.join(routes_dir, route.id)) + ); + + if (fs.existsSync(types_dir)) { + for (const file of walk(types_dir)) { + const dir = path.dirname(file); + if (!expected_directories.has(dir)) { + rimraf(path.join(types_dir, file)); + } + } + } + + // Read/write meta data on each invocation, not once per node process, + // it could be invoked by another process in the meantime. + const meta_data_file = `${types_dir}/route_meta_data.json`; + const has_meta_data = fs.existsSync(meta_data_file); + const meta_data = has_meta_data + ? /** @type {Record} */ (JSON.parse(fs.readFileSync(meta_data_file, 'utf-8'))) + : {}; + const routes_map = create_routes_map(manifest_data); + // For each directory, write $types.d.ts + for (const route of manifest_data.routes) { + if (!route.leaf && !route.layout && !route.endpoint) continue; // nothing to do + + const outdir = path.join(config.kit.outDir, 'types', routes_dir, route.id); + + // check if the types are out of date + /** @type {string[]} */ + const input_files = []; + + /** @type {import('types').PageNode | null} */ + let node = route.leaf; + while (node) { + if (node.universal) input_files.push(node.universal); + if (node.server) input_files.push(node.server); + node = node.parent ?? null; + } + + /** @type {import('types').PageNode | null} */ + node = route.layout; + while (node) { + if (node.universal) input_files.push(node.universal); + if (node.server) input_files.push(node.server); + node = node.parent ?? null; + } + + if (route.endpoint) { + input_files.push(route.endpoint.file); + } + + try { + fs.mkdirSync(outdir, { recursive: true }); + } catch {} + + const output_files = compact( + fs.readdirSync(outdir).map((name) => { + const stats = fs.statSync(path.join(outdir, name)); + if (stats.isDirectory()) return; + return { + name, + updated: stats.mtimeMs + }; + }) + ); + + const source_last_updated = Math.max( + // ctimeMs includes move operations whereas mtimeMs does not + ...input_files.map((file) => fs.statSync(file).ctimeMs) + ); + const types_last_updated = Math.max(...output_files.map((file) => file.updated)); + + const should_generate = + // source files were generated more recently than the types + source_last_updated > types_last_updated || + // no meta data file exists yet + !has_meta_data || + // some file was deleted + !meta_data[route.id]?.every((file) => input_files.includes(file)); + + if (should_generate) { + // track which old files end up being surplus to requirements + const to_delete = new Set(output_files.map((file) => file.name)); + update_types(config, routes_map, route, to_delete); + meta_data[route.id] = input_files; + } + } + + fs.writeFileSync(meta_data_file, JSON.stringify(meta_data, null, '\t')); +} + +/** + * Creates types related to the given file. This should only be called + * if the file in question was edited, not if it was created/deleted/moved. + * @param {import('types').ValidatedConfig} config + * @param {import('types').ManifestData} manifest_data + * @param {string} file + */ +export function write_types(config, manifest_data, file) { + if (!ts) return; + + if (!path.basename(file).startsWith('+')) { + // Not a route file + return; + } + + const id = '/' + posixify(path.relative(config.kit.files.routes, path.dirname(file))); + + const route = manifest_data.routes.find((route) => route.id === id); + if (!route) return; + if (!route.leaf && !route.layout && !route.endpoint) return; // nothing to do + + update_types(config, create_routes_map(manifest_data), route); +} + +/** + * Collect all leafs into a leaf -> route map + * @param {import('types').ManifestData} manifest_data + */ +function create_routes_map(manifest_data) { + /** @type {RoutesMap} */ + const map = new Map(); + for (const route of manifest_data.routes) { + if (route.leaf) { + map.set(route.leaf, { route, proxies: { server: null, universal: null } }); + } + } + return map; +} + +/** + * Update types for a specific route + * @param {import('types').ValidatedConfig} config + * @param {RoutesMap} routes + * @param {import('types').RouteData} route + * @param {Set} [to_delete] + */ +function update_types(config, routes, route, to_delete = new Set()) { + const routes_dir = posixify(path.relative('.', config.kit.files.routes)).replace(/\.\.\//g, ''); + const outdir = path.join(config.kit.outDir, 'types', routes_dir, route.id); + + // now generate new types + const imports = ["import type * as Kit from '@sveltejs/kit';"]; + + /** @type {string[]} */ + const declarations = []; + + /** @type {string[]} */ + const exports = []; + + // add 'Expand' helper + // Makes sure a type is "repackaged" and therefore more readable + declarations.push('type Expand = T extends infer O ? { [K in keyof O]: O[K] } : never;'); + + // returns the predicate of a matcher's type guard - or string if there is no type guard + declarations.push( + // TS complains on infer U, which seems weird, therefore ts-ignore it + [ + '// @ts-ignore', + 'type MatcherParam = M extends (param : string) => param is infer U ? U extends string ? U : string : string;' + ].join('\n') + ); + + declarations.push( + 'type RouteParams = ' + generate_params_type(route.params, outdir, config) + ';' + ); + + if (route.params.length > 0) { + exports.push( + 'export type EntryGenerator = () => Promise> | Array;' + ); + } + + declarations.push(`type RouteId = '${route.id}';`); + + // These could also be placed in our public types, but it would bloat them unnecessarily and we may want to change these in the future + if (route.layout || route.leaf) { + declarations.push( + // If T extends the empty object, void is also allowed as a return type + 'type MaybeWithVoid = {} extends T ? T | void : T;', + + // Returns the key of the object whose values are required. + 'export type RequiredKeys = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];', + + // Helper type to get the correct output type for load functions. It should be passed the parent type to check what types from App.PageData are still required. + // If none, void is also allowed as a return type. + 'type OutputDataShape = MaybeWithVoid> & Partial> & Record>', + + // null & {} == null, we need to prevent that in some situations + 'type EnsureDefined = T extends null | undefined ? {} : T;', + + // Takes a union type and returns a union type where each type also has all properties + // of all possible types (typed as undefined), making accessing them more ergonomic + 'type OptionalUnion, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude]?: never } & U : never;', + + // Re-export `Snapshot` from @sveltejs/kit — in future we could use this to infer from the return type of `snapshot.capture` + 'export type Snapshot = Kit.Snapshot;' + ); + } + + if (route.leaf) { + let route_info = routes.get(route.leaf); + if (!route_info) { + // This should be defined, but belts and braces + route_info = { route, proxies: { server: null, universal: null } }; + routes.set(route.leaf, route_info); + } + + const { + declarations: d, + exports: e, + proxies + } = process_node(route.leaf, outdir, true, route_info.proxies); + + exports.push(...e); + declarations.push(...d); + + if (proxies.server) { + route_info.proxies.server = proxies.server; + if (proxies.server?.modified) to_delete.delete(proxies.server.file_name); + } + if (proxies.universal) { + route_info.proxies.universal = proxies.universal; + if (proxies.universal?.modified) to_delete.delete(proxies.universal.file_name); + } + + if (route.leaf.server) { + exports.push( + 'export type Action | void = Record | void> = Kit.Action' + ); + exports.push( + 'export type Actions | void = Record | void> = Kit.Actions' + ); + } + } + + if (route.layout) { + let all_pages_have_load = true; + /** @type {import('types').RouteParam[]} */ + const layout_params = []; + const ids = ['RouteId']; + + route.layout.child_pages?.forEach((page) => { + const leaf = routes.get(page); + if (leaf) { + if (leaf.route.page) ids.push(`"${leaf.route.id}"`); + + for (const param of leaf.route.params) { + // skip if already added + if (layout_params.some((p) => p.name === param.name)) continue; + layout_params.push({ ...param, optional: true }); + } + + ensureProxies(page, leaf.proxies); + + if ( + // Be defensive - if a proxy doesn't exist (because it couldn't be created), assume a load function exists. + // If we didn't and it's a false negative, the user could wrongfully get a type error on layouts. + (leaf.proxies.server && !leaf.proxies.server.exports.includes('load')) || + (leaf.proxies.universal && !leaf.proxies.universal.exports.includes('load')) + ) { + all_pages_have_load = false; + } + } + if (!page.server && !page.universal) { + all_pages_have_load = false; + } + }); + + if (route.id === '/') { + // root layout is used for fallback error page, where ID can be null + ids.push('null'); + } + + declarations.push(`type LayoutRouteId = ${ids.join(' | ')}`); + + declarations.push( + 'type LayoutParams = RouteParams & ' + generate_params_type(layout_params, outdir, config) + ); + + const { + exports: e, + declarations: d, + proxies + } = process_node( + route.layout, + outdir, + false, + { server: null, universal: null }, + all_pages_have_load + ); + + exports.push(...e); + declarations.push(...d); + + if (proxies.server?.modified) to_delete.delete(proxies.server.file_name); + if (proxies.universal?.modified) to_delete.delete(proxies.universal.file_name); + } + + if (route.endpoint) { + exports.push('export type RequestHandler = Kit.RequestHandler;'); + } + + if (route.leaf?.server || route.layout?.server || route.endpoint) { + exports.push('export type RequestEvent = Kit.RequestEvent;'); + } + + const output = [imports.join('\n'), declarations.join('\n'), exports.join('\n')] + .filter(Boolean) + .join('\n\n'); + + fs.writeFileSync(`${outdir}/$types.d.ts`, output); + to_delete.delete('$types.d.ts'); + + for (const file of to_delete) { + fs.unlinkSync(path.join(outdir, file)); + } +} + +/** + * @param {import('types').PageNode} node + * @param {string} outdir + * @param {boolean} is_page + * @param {Proxies} proxies + * @param {boolean} [all_pages_have_load] + */ +function process_node(node, outdir, is_page, proxies, all_pages_have_load = true) { + const params = `${is_page ? 'Route' : 'Layout'}Params`; + const prefix = is_page ? 'Page' : 'Layout'; + + const route_id = is_page ? 'RouteId' : 'LayoutRouteId'; + + /** @type {string[]} */ + const declarations = []; + /** @type {string[]} */ + const exports = []; + + /** @type {string} */ + let server_data; + /** @type {string} */ + let data; + + ensureProxies(node, proxies); + + if (node.server) { + const basename = path.basename(node.server); + const proxy = proxies.server; + if (proxy?.modified) { + fs.writeFileSync(`${outdir}/proxy${basename}`, proxy.code); + } + + server_data = get_data_type(node.server, 'null', proxy, true); + + const parent_type = `${prefix}ServerParentData`; + + declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutServerData')};`); + + // +page.js load present -> server can return all-optional data + const output_data_shape = + node.universal || (!is_page && all_pages_have_load) + ? 'Partial & Record | void' + : `OutputDataShape<${parent_type}>`; + exports.push( + `export type ${prefix}ServerLoad = Kit.ServerLoad<${params}, ${parent_type}, OutputData, ${route_id}>;` + ); + + exports.push(`export type ${prefix}ServerLoadEvent = Parameters<${prefix}ServerLoad>[0];`); + + if (is_page) { + let type = 'unknown'; + if (proxy && proxy.exports.includes('actions')) { + // If the file wasn't tweaked, we can use the return type of the original file. + // The advantage is that type updates are reflected without saving. + const from = proxy.modified + ? `./proxy${replace_ext_with_js(basename)}` + : path_to_original(outdir, node.server); + + exports.push( + 'type ExcludeActionFailure = T extends Kit.ActionFailure ? never : T extends void ? never : T;', + 'type ActionsSuccess any>> = { [Key in keyof T]: ExcludeActionFailure>>; }[keyof T];', + 'type ExtractActionFailure = T extends Kit.ActionFailure ? X extends void ? never : X : never;', + 'type ActionsFailure any>> = { [Key in keyof T]: Exclude>>, void>; }[keyof T];', + `type ActionsExport = typeof import('${from}').actions`, + 'export type SubmitFunction = Kit.SubmitFunction>, Expand>>' + ); + + type = 'Expand> | null'; + } + exports.push(`export type ActionData = ${type};`); + } + } else { + server_data = 'null'; + } + exports.push(`export type ${prefix}ServerData = ${server_data};`); + + const parent_type = `${prefix}ParentData`; + declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutData')};`); + + if (node.universal) { + const proxy = proxies.universal; + if (proxy?.modified) { + fs.writeFileSync(`${outdir}/proxy${path.basename(node.universal)}`, proxy.code); + } + + const type = get_data_type( + node.universal, + `${parent_type} & EnsureDefined<${prefix}ServerData>`, + proxy + ); + + data = `Expand & OptionalUnion>>`; + + const output_data_shape = + !is_page && all_pages_have_load + ? 'Partial & Record | void' + : `OutputDataShape<${parent_type}>`; + exports.push( + `export type ${prefix}Load = Kit.Load<${params}, ${prefix}ServerData, ${parent_type}, OutputData, ${route_id}>;` + ); + + exports.push(`export type ${prefix}LoadEvent = Parameters<${prefix}Load>[0];`); + } else if (server_data === 'null') { + data = `Expand<${parent_type}>`; + } else { + data = `Expand & EnsureDefined<${prefix}ServerData>>`; + } + + exports.push(`export type ${prefix}Data = ${data};`); + + return { declarations, exports, proxies }; + + /** + * @param {string} file_path + * @param {string} fallback + * @param {Proxy} proxy + * @param {boolean} expand + */ + function get_data_type(file_path, fallback, proxy, expand = false) { + if (proxy) { + if (proxy.exports.includes('load')) { + // If the file wasn't tweaked, we can use the return type of the original file. + // The advantage is that type updates are reflected without saving. + const from = proxy.modified + ? `./proxy${replace_ext_with_js(path.basename(file_path))}` + : path_to_original(outdir, file_path); + const type = `Kit.LoadProperties>>`; + return expand ? `Expand>>` : type; + } else { + return fallback; + } + } else { + return 'unknown'; + } + } +} + +/** + * This function populates the proxies object, if necessary and not already done. + * Proxies are used to tweak the code of a file before it's typechecked. + * They are needed in two places - when generating the types for a page or layout. + * To not do the same work twice, we generate the proxies once and pass them around. + * + * @param {import('types').PageNode} node + * @param {Proxies} proxies + */ +function ensureProxies(node, proxies) { + if (node.server && !proxies.server) { + proxies.server = createProxy(node.server, true); + } + + if (node.universal && !proxies.universal) { + proxies.universal = createProxy(node.universal, false); + } +} + +/** + * @param {string} file_path + * @param {boolean} is_server + * @returns {Proxy} + */ +function createProxy(file_path, is_server) { + const proxy = tweak_types(fs.readFileSync(file_path, 'utf8'), is_server); + if (proxy) { + return { + ...proxy, + file_name: `proxy${path.basename(file_path)}` + }; + } else { + return null; + } +} + +/** + * Get the parent type string by recursively looking up the parent layout and accumulate them to one type. + * @param {import('types').PageNode} node + * @param {string} type + */ +function get_parent_type(node, type) { + const parent_imports = []; + + let parent = node.parent; + + while (parent) { + const d = node.depth - parent.depth; + // unshift because we need it the other way round for the import string + parent_imports.unshift( + `${d === 0 ? '' : `import('${'../'.repeat(d)}${'$types.js'}').`}${type}` + ); + parent = parent.parent; + } + + let parent_str = `EnsureDefined<${parent_imports[0] || '{}'}>`; + for (let i = 1; i < parent_imports.length; i++) { + // Omit is necessary because a parent could have a property with the same key which would + // cause a type conflict. At runtime the child overwrites the parent property in this case, + // so reflect that in the type definition. + // EnsureDefined is necessary because {something: string} & null becomes null. + // Output types of server loads can be null but when passed in through the `parent` parameter they are the empty object instead. + parent_str = `Omit<${parent_str}, keyof ${parent_imports[i]}> & EnsureDefined<${parent_imports[i]}>`; + } + return parent_str; +} + +/** + * @param {string} outdir + * @param {string} file_path + */ +function path_to_original(outdir, file_path) { + return posixify(path.relative(outdir, path.join(cwd, replace_ext_with_js(file_path)))); +} + +/** + * @param {string} file_path + */ +function replace_ext_with_js(file_path) { + // Another extension than `.js` (or nothing, but that fails with node16 moduleResolution) + // will result in TS failing to lookup the file + const ext = path.extname(file_path); + return file_path.slice(0, -ext.length) + '.js'; +} + +/** + * @param {import('types').RouteParam[]} params + * @param {string} outdir + * @param {import('types').ValidatedConfig} config + */ +function generate_params_type(params, outdir, config) { + /** @param {string} matcher */ + const path_to_matcher = (matcher) => + posixify(path.relative(outdir, path.join(config.kit.files.params, matcher))); + + return `{ ${params + .map( + (param) => + `${param.name}${param.optional ? '?' : ''}: ${ + param.matcher + ? `MatcherParam` + : 'string' + }` + ) + .join('; ')} }`; +} + +/** + * @param {string} content + * @param {boolean} is_server + * @returns {Omit, 'file_name'> | null} + */ +export function tweak_types(content, is_server) { + const names = new Set(is_server ? ['load', 'actions'] : ['load']); + + try { + let modified = false; + + const ast = ts.createSourceFile( + 'filename.ts', + content, + ts.ScriptTarget.Latest, + false, + ts.ScriptKind.TS + ); + + const code = new MagicString(content); + + const exports = new Map(); + + ast.forEachChild((node) => { + if ( + ts.isExportDeclaration(node) && + node.exportClause && + ts.isNamedExports(node.exportClause) + ) { + node.exportClause.elements.forEach((element) => { + const exported = element.name; + if (names.has(element.name.text)) { + const local = element.propertyName || element.name; + exports.set(exported.text, local.text); + } + }); + } + + if ( + ts.canHaveModifiers(node) && + ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) + ) { + if (ts.isFunctionDeclaration(node) && node.name?.text && names.has(node.name?.text)) { + exports.set(node.name.text, node.name.text); + } + + if (ts.isVariableStatement(node)) { + node.declarationList.declarations.forEach((declaration) => { + if (ts.isIdentifier(declaration.name) && names.has(declaration.name.text)) { + exports.set(declaration.name.text, declaration.name.text); + } + }); + } + } + }); + + /** + * @param {import('typescript').Node} node + * @param {import('typescript').Node} value + */ + function replace_jsdoc_type_tags(node, value) { + let _modified = false; + // @ts-ignore + if (node.jsDoc) { + // @ts-ignore + for (const comment of node.jsDoc) { + for (const tag of comment.tags ?? []) { + if (ts.isJSDocTypeTag(tag)) { + const is_fn = + ts.isFunctionDeclaration(value) || + ts.isFunctionExpression(value) || + ts.isArrowFunction(value); + + if (is_fn && value.parameters?.length > 0) { + const name = ts.isIdentifier(value.parameters[0].name) + ? value.parameters[0].name.text + : 'event'; + code.overwrite(tag.tagName.pos, tag.tagName.end, 'param'); + code.prependRight(tag.typeExpression.pos + 1, 'Parameters<'); + code.appendLeft(tag.typeExpression.end - 1, '>[0]'); + code.appendLeft(tag.typeExpression.end, ` ${name}`); + } else { + code.overwrite(tag.pos, tag.end, ''); + } + _modified = true; + } + } + } + } + modified = modified || _modified; + return _modified; + } + + ast.forEachChild((node) => { + if (ts.isFunctionDeclaration(node) && node.name?.text && node.name?.text === 'load') { + // remove JSDoc comment above `export function load ...` + replace_jsdoc_type_tags(node, node); + } + + if (ts.isVariableStatement(node)) { + // remove JSDoc comment above `export const load = ...` + if ( + ts.isIdentifier(node.declarationList.declarations[0].name) && + names.has(node.declarationList.declarations[0].name.text) && + node.declarationList.declarations[0].initializer + ) { + replace_jsdoc_type_tags(node, node.declarationList.declarations[0].initializer); + } + + for (const declaration of node.declarationList.declarations) { + if ( + ts.isIdentifier(declaration.name) && + declaration.name.text === 'load' && + declaration.initializer + ) { + // edge case — remove JSDoc comment above individual export + replace_jsdoc_type_tags(declaration, declaration.initializer); + + // remove type from `export const load: Load ...` + if (declaration.type) { + let a = declaration.type.pos; + const b = declaration.type.end; + while (/\s/.test(content[a])) a += 1; + + const type = content.slice(a, b); + code.remove(declaration.name.end, declaration.type.end); + + const rhs = declaration.initializer; + + if ( + rhs && + (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) && + rhs.parameters.length + ) { + const arg = rhs.parameters[0]; + const add_parens = content[arg.pos - 1] !== '('; + + if (add_parens) code.prependRight(arg.pos, '('); + + if (arg && !arg.type) { + code.appendLeft( + arg.name.end, + `: Parameters<${type}>[0]` + (add_parens ? ')' : '') + ); + } else { + // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs + code.append(`;null as any as ${type};`); + } + } else { + // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs + code.append(`;null as any as ${type};`); + } + + modified = true; + } + } else if ( + is_server && + ts.isIdentifier(declaration.name) && + declaration.name?.text === 'actions' && + declaration.initializer + ) { + // remove JSDoc comment from `export const actions = ..` + const removed = replace_jsdoc_type_tags(node, declaration.initializer); + // ... and move type to each individual action + if (removed) { + const rhs = declaration.initializer; + if (ts.isObjectLiteralExpression(rhs)) { + for (const prop of rhs.properties) { + if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) { + const rhs = prop.initializer; + const replaced = replace_jsdoc_type_tags(prop, rhs); + if ( + !replaced && + rhs && + (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) && + rhs.parameters?.[0] + ) { + const name = ts.isIdentifier(rhs.parameters[0].name) + ? rhs.parameters[0].name.text + : 'event'; + code.prependRight( + rhs.pos, + `/** @param {import('./$types').RequestEvent} ${name} */ ` + ); + } + } + } + } + } + + // remove type from `export const actions: Actions ...` + if (declaration.type) { + let a = declaration.type.pos; + const b = declaration.type.end; + while (/\s/.test(content[a])) a += 1; + + const type = content.slice(a, b); + code.remove(declaration.name.end, declaration.type.end); + code.append(`;null as any as ${type};`); + modified = true; + + // ... and move type to each individual action + const rhs = declaration.initializer; + if (ts.isObjectLiteralExpression(rhs)) { + for (const prop of rhs.properties) { + if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) { + const rhs = prop.initializer; + + if ( + rhs && + (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) && + rhs.parameters.length + ) { + const arg = rhs.parameters[0]; + const add_parens = content[arg.pos - 1] !== '('; + + if (add_parens) code.prependRight(arg.pos, '('); + + if (arg && !arg.type) { + code.appendLeft( + arg.name.end, + ": import('./$types').RequestEvent" + (add_parens ? ')' : '') + ); + } + } + } + } + } + } + } + } + } + }); + + if (modified) { + // Ignore all type errors so they don't show up twice when svelte-check runs + // Account for possible @ts-check which would overwrite @ts-nocheck + if (code.original.startsWith('// @ts-check')) { + code.prependLeft('// @ts-check'.length, '\n// @ts-nocheck\n'); + } else { + code.prepend('// @ts-nocheck\n'); + } + } + + return { + modified, + code: code.toString(), + exports: Array.from(exports.keys()) + }; + } catch { + return null; + } +} diff --git a/node_modules/@sveltejs/kit/src/core/utils.js b/node_modules/@sveltejs/kit/src/core/utils.js new file mode 100644 index 00000000..668306e9 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/utils.js @@ -0,0 +1,87 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import process from 'node:process'; +import { fileURLToPath } from 'node:url'; +import colors from 'kleur'; +import { posixify, to_fs } from '../utils/filesystem.js'; + +/** + * Resolved path of the `runtime` directory + * + * TODO Windows issue: + * Vite or sth else somehow sets the driver letter inconsistently to lower or upper case depending on the run environment. + * In playwright debug mode run through VS Code this a root-to-lowercase conversion is needed in order for the tests to run. + * If we do this conversion in other cases it has the opposite effect though and fails. + */ +export const runtime_directory = posixify(fileURLToPath(new URL('../runtime', import.meta.url))); + +/** + * This allows us to import SvelteKit internals that aren't exposed via `pkg.exports` in a + * way that works whether `@sveltejs/kit` is installed inside the project's `node_modules` + * or in a workspace root + */ +export const runtime_base = runtime_directory.startsWith(process.cwd()) + ? `/${path.relative('.', runtime_directory)}` + : to_fs(runtime_directory); + +function noop() {} + +/** @param {{ verbose: boolean }} opts */ +export function logger({ verbose }) { + /** @type {import('types').Logger} */ + const log = (msg) => console.log(msg.replace(/^/gm, ' ')); + + /** @param {string} msg */ + const err = (msg) => console.error(msg.replace(/^/gm, ' ')); + + log.success = (msg) => log(colors.green(`✔ ${msg}`)); + log.error = (msg) => err(colors.bold().red(msg)); + log.warn = (msg) => log(colors.bold().yellow(msg)); + + log.minor = verbose ? (msg) => log(colors.grey(msg)) : noop; + log.info = verbose ? log : noop; + + return log; +} + +/** @param {import('types').ManifestData} manifest_data */ +export function get_mime_lookup(manifest_data) { + /** @type {Record} */ + const mime = {}; + + manifest_data.assets.forEach((asset) => { + if (asset.type) { + const ext = path.extname(asset.file); + mime[ext] = asset.type; + } + }); + + return mime; +} + +/** + * @param {string} dir + * @param {(file: string) => boolean} [filter] + */ +export function list_files(dir, filter) { + /** @type {string[]} */ + const files = []; + + /** @param {string} current */ + function walk(current) { + for (const file of fs.readdirSync(path.resolve(dir, current))) { + const child = path.posix.join(current, file); + if (fs.statSync(path.resolve(dir, child)).isDirectory()) { + walk(child); + } else { + if (!filter || filter(child)) { + files.push(child); + } + } + } + } + + if (fs.existsSync(dir)) walk(''); + + return files; +} diff --git a/node_modules/@sveltejs/kit/src/exports/hooks/index.js b/node_modules/@sveltejs/kit/src/exports/hooks/index.js new file mode 100644 index 00000000..98e1e53a --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/hooks/index.js @@ -0,0 +1 @@ +export { sequence } from './sequence.js'; diff --git a/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js b/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js new file mode 100644 index 00000000..2e1e3248 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js @@ -0,0 +1,120 @@ +/** + * A helper function for sequencing multiple `handle` calls in a middleware-like manner. + * The behavior for the `handle` options is as follows: + * - `transformPageChunk` is applied in reverse order and merged + * - `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called + * - `filterSerializedResponseHeaders` behaves the same as `preload` + * + * ```js + * /// file: src/hooks.server.js + * import { sequence } from '@sveltejs/kit/hooks'; + * + * /// type: import('@sveltejs/kit').Handle + * async function first({ event, resolve }) { + * console.log('first pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * // transforms are applied in reverse order + * console.log('first transform'); + * return html; + * }, + * preload: () => { + * // this one wins as it's the first defined in the chain + * console.log('first preload'); + * } + * }); + * console.log('first post-processing'); + * return result; + * } + * + * /// type: import('@sveltejs/kit').Handle + * async function second({ event, resolve }) { + * console.log('second pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * console.log('second transform'); + * return html; + * }, + * preload: () => { + * console.log('second preload'); + * }, + * filterSerializedResponseHeaders: () => { + * // this one wins as it's the first defined in the chain + * console.log('second filterSerializedResponseHeaders'); + * } + * }); + * console.log('second post-processing'); + * return result; + * } + * + * export const handle = sequence(first, second); + * ``` + * + * The example above would print: + * + * ``` + * first pre-processing + * first preload + * second pre-processing + * second filterSerializedResponseHeaders + * second transform + * first transform + * second post-processing + * first post-processing + * ``` + * + * @param {...import('@sveltejs/kit').Handle} handlers The chain of `handle` functions + * @returns {import('@sveltejs/kit').Handle} + */ +export function sequence(...handlers) { + const length = handlers.length; + if (!length) return ({ event, resolve }) => resolve(event); + + return ({ event, resolve }) => { + return apply_handle(0, event, {}); + + /** + * @param {number} i + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('@sveltejs/kit').ResolveOptions | undefined} parent_options + * @returns {import('types').MaybePromise} + */ + function apply_handle(i, event, parent_options) { + const handle = handlers[i]; + + return handle({ + event, + resolve: (event, options) => { + /** @type {import('@sveltejs/kit').ResolveOptions['transformPageChunk']} */ + const transformPageChunk = async ({ html, done }) => { + if (options?.transformPageChunk) { + html = (await options.transformPageChunk({ html, done })) ?? ''; + } + + if (parent_options?.transformPageChunk) { + html = (await parent_options.transformPageChunk({ html, done })) ?? ''; + } + + return html; + }; + + /** @type {import('@sveltejs/kit').ResolveOptions['filterSerializedResponseHeaders']} */ + const filterSerializedResponseHeaders = + parent_options?.filterSerializedResponseHeaders ?? + options?.filterSerializedResponseHeaders; + + /** @type {import('@sveltejs/kit').ResolveOptions['preload']} */ + const preload = parent_options?.preload ?? options?.preload; + + return i < length - 1 + ? apply_handle(i + 1, event, { + transformPageChunk, + filterSerializedResponseHeaders, + preload + }) + : resolve(event, { transformPageChunk, filterSerializedResponseHeaders, preload }); + } + }); + } + }; +} diff --git a/node_modules/@sveltejs/kit/src/exports/index.js b/node_modules/@sveltejs/kit/src/exports/index.js new file mode 100644 index 00000000..32fb827d --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/index.js @@ -0,0 +1,192 @@ +import { HttpError, Redirect, ActionFailure } from '../runtime/control.js'; +import { BROWSER, DEV } from 'esm-env'; + +export { VERSION } from '../version.js'; + +// TODO 3.0: remove these types as they are not used anymore (we can't remove them yet because that would be a breaking change) +/** + * @template {number} TNumber + * @template {any[]} [TArray=[]] + * @typedef {TNumber extends TArray['length'] ? TArray[number] : LessThan} LessThan + */ + +/** + * @template {number} TStart + * @template {number} TEnd + * @typedef {Exclude, LessThan>} NumericRange + */ + +// Keep the status codes as `number` because restricting to certain numbers makes it unnecessarily hard to use compared to the benefits +// (we have runtime errors already to check for invalid codes). Also see https://github.com/sveltejs/kit/issues/11780 + +// we have to repeat the JSDoc because the display for function overloads is broken +// see https://github.com/microsoft/TypeScript/issues/55056 + +/** + * Throws an error with a HTTP status code and an optional message. + * When called during request handling, this will cause SvelteKit to + * return an error response without invoking `handleError`. + * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {App.Error} body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. + * @overload + * @param {number} status + * @param {App.Error} body + * @return {never} + * @throws {HttpError} This error instructs SvelteKit to initiate HTTP error handling. + * @throws {Error} If the provided status is invalid (not between 400 and 599). + */ +/** + * Throws an error with a HTTP status code and an optional message. + * When called during request handling, this will cause SvelteKit to + * return an error response without invoking `handleError`. + * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} [body] An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. + * @overload + * @param {number} status + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} [body] + * @return {never} + * @throws {HttpError} This error instructs SvelteKit to initiate HTTP error handling. + * @throws {Error} If the provided status is invalid (not between 400 and 599). + */ +/** + * Throws an error with a HTTP status code and an optional message. + * When called during request handling, this will cause SvelteKit to + * return an error response without invoking `handleError`. + * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. + * @return {never} + * @throws {HttpError} This error instructs SvelteKit to initiate HTTP error handling. + * @throws {Error} If the provided status is invalid (not between 400 and 599). + */ +export function error(status, body) { + if ((!BROWSER || DEV) && (isNaN(status) || status < 400 || status > 599)) { + throw new Error(`HTTP error status codes must be between 400 and 599 — ${status} is invalid`); + } + + throw new HttpError(status, body); +} + +/** + * Checks whether this is an error thrown by {@link error}. + * @template {number} T + * @param {unknown} e + * @param {T} [status] The status to filter for. + * @return {e is (HttpError & { status: T extends undefined ? never : T })} + */ +export function isHttpError(e, status) { + if (!(e instanceof HttpError)) return false; + return !status || e.status === status; +} + +/** + * Redirect a request. When called during request handling, SvelteKit will return a redirect response. + * Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it. + * @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number)} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308. + * @param {string | URL} location The location to redirect to. + * @throws {Redirect} This error instructs SvelteKit to redirect to the specified location. + * @throws {Error} If the provided status is invalid. + * @return {never} + */ +export function redirect(status, location) { + if ((!BROWSER || DEV) && (isNaN(status) || status < 300 || status > 308)) { + throw new Error('Invalid status code'); + } + + throw new Redirect( + // @ts-ignore + status, + location.toString() + ); +} + +/** + * Checks whether this is a redirect thrown by {@link redirect}. + * @param {unknown} e The object to check. + * @return {e is Redirect} + */ +export function isRedirect(e) { + return e instanceof Redirect; +} + +/** + * Create a JSON `Response` object from the supplied data. + * @param {any} data The value that will be serialized as JSON. + * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically. + */ +export function json(data, init) { + // TODO deprecate this in favour of `Response.json` when it's + // more widely supported + const body = JSON.stringify(data); + + // we can't just do `text(JSON.stringify(data), init)` because + // it will set a default `content-type` header. duplicated code + // means less duplicated work + const headers = new Headers(init?.headers); + if (!headers.has('content-length')) { + headers.set('content-length', encoder.encode(body).byteLength.toString()); + } + + if (!headers.has('content-type')) { + headers.set('content-type', 'application/json'); + } + + return new Response(body, { + ...init, + headers + }); +} + +const encoder = new TextEncoder(); + +/** + * Create a `Response` object from the supplied body. + * @param {string} body The value that will be used as-is. + * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically. + */ +export function text(body, init) { + const headers = new Headers(init?.headers); + if (!headers.has('content-length')) { + const encoded = encoder.encode(body); + headers.set('content-length', encoded.byteLength.toString()); + return new Response(encoded, { + ...init, + headers + }); + } + + return new Response(body, { + ...init, + headers + }); +} + +/** + * Create an `ActionFailure` object. + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @overload + * @param {number} status + * @returns {import('./public.js').ActionFailure} + */ +/** + * Create an `ActionFailure` object. + * @template {Record | undefined} [T=undefined] + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {T} data Data associated with the failure (e.g. validation errors) + * @overload + * @param {number} status + * @param {T} data + * @returns {import('./public.js').ActionFailure} + */ +/** + * Create an `ActionFailure` object. + * @param {number} status + * @param {any} [data] + * @returns {import('./public.js').ActionFailure} + */ +export function fail(status, data) { + // @ts-expect-error unique symbol missing + return new ActionFailure(status, data); +} diff --git a/node_modules/@sveltejs/kit/src/exports/node/index.js b/node_modules/@sveltejs/kit/src/exports/node/index.js new file mode 100644 index 00000000..b3fe17c5 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/node/index.js @@ -0,0 +1,210 @@ +import { createReadStream } from 'node:fs'; +import { Readable } from 'node:stream'; +import * as set_cookie_parser from 'set-cookie-parser'; +import { SvelteKitError } from '../../runtime/control.js'; + +/** + * @param {import('http').IncomingMessage} req + * @param {number} [body_size_limit] + */ +function get_raw_body(req, body_size_limit) { + const h = req.headers; + + if (!h['content-type']) { + return null; + } + + const content_length = Number(h['content-length']); + + // check if no request body + if ( + (req.httpVersionMajor === 1 && isNaN(content_length) && h['transfer-encoding'] == null) || + content_length === 0 + ) { + return null; + } + + if (req.destroyed) { + const readable = new ReadableStream(); + readable.cancel(); + return readable; + } + + let size = 0; + let cancelled = false; + + return new ReadableStream({ + start(controller) { + if (body_size_limit !== undefined && content_length > body_size_limit) { + let message = `Content-length of ${content_length} exceeds limit of ${body_size_limit} bytes.`; + + if (body_size_limit === 0) { + // https://github.com/sveltejs/kit/pull/11589 + // TODO this exists to aid migration — remove in a future version + message += ' To disable body size limits, specify Infinity rather than 0.'; + } + + const error = new SvelteKitError(413, 'Payload Too Large', message); + + controller.error(error); + return; + } + + req.on('error', (error) => { + cancelled = true; + controller.error(error); + }); + + req.on('end', () => { + if (cancelled) return; + controller.close(); + }); + + req.on('data', (chunk) => { + if (cancelled) return; + + size += chunk.length; + if (size > content_length) { + cancelled = true; + + const constraint = content_length ? 'content-length' : 'BODY_SIZE_LIMIT'; + const message = `request body size exceeded ${constraint} of ${content_length}`; + + const error = new SvelteKitError(413, 'Payload Too Large', message); + controller.error(error); + + return; + } + + controller.enqueue(chunk); + + if (controller.desiredSize === null || controller.desiredSize <= 0) { + req.pause(); + } + }); + }, + + pull() { + req.resume(); + }, + + cancel(reason) { + cancelled = true; + req.destroy(reason); + } + }); +} + +/** + * @param {{ + * request: import('http').IncomingMessage; + * base: string; + * bodySizeLimit?: number; + * }} options + * @returns {Promise} + */ +// TODO 3.0 make the signature synchronous? +// eslint-disable-next-line @typescript-eslint/require-await +export async function getRequest({ request, base, bodySizeLimit }) { + return new Request(base + request.url, { + // @ts-expect-error + duplex: 'half', + method: request.method, + headers: /** @type {Record} */ (request.headers), + body: + request.method === 'GET' || request.method === 'HEAD' + ? undefined + : get_raw_body(request, bodySizeLimit) + }); +} + +/** + * @param {import('http').ServerResponse} res + * @param {Response} response + * @returns {Promise} + */ +// TODO 3.0 make the signature synchronous? +// eslint-disable-next-line @typescript-eslint/require-await +export async function setResponse(res, response) { + for (const [key, value] of response.headers) { + try { + res.setHeader( + key, + key === 'set-cookie' + ? set_cookie_parser.splitCookiesString( + // This is absurd but necessary, TODO: investigate why + /** @type {string}*/ (response.headers.get(key)) + ) + : value + ); + } catch (error) { + res.getHeaderNames().forEach((name) => res.removeHeader(name)); + res.writeHead(500).end(String(error)); + return; + } + } + + res.writeHead(response.status); + + if (!response.body) { + res.end(); + return; + } + + if (response.body.locked) { + res.end( + 'Fatal error: Response body is locked. ' + + "This can happen when the response was already read (for example through 'response.json()' or 'response.text()')." + ); + return; + } + + const reader = response.body.getReader(); + + if (res.destroyed) { + reader.cancel(); + return; + } + + const cancel = (/** @type {Error|undefined} */ error) => { + res.off('close', cancel); + res.off('error', cancel); + + // If the reader has already been interrupted with an error earlier, + // then it will appear here, it is useless, but it needs to be catch. + reader.cancel(error).catch(() => {}); + if (error) res.destroy(error); + }; + + res.on('close', cancel); + res.on('error', cancel); + + next(); + async function next() { + try { + for (;;) { + const { done, value } = await reader.read(); + + if (done) break; + + if (!res.write(value)) { + res.once('drain', next); + return; + } + } + res.end(); + } catch (error) { + cancel(error instanceof Error ? error : new Error(String(error))); + } + } +} + +/** + * Converts a file on disk to a readable stream + * @param {string} file + * @returns {ReadableStream} + * @since 2.4.0 + */ +export function createReadableStream(file) { + return /** @type {ReadableStream} */ (Readable.toWeb(createReadStream(file))); +} diff --git a/node_modules/@sveltejs/kit/src/exports/node/polyfills.js b/node_modules/@sveltejs/kit/src/exports/node/polyfills.js new file mode 100644 index 00000000..347c68ce --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/node/polyfills.js @@ -0,0 +1,30 @@ +import buffer from 'node:buffer'; +import { webcrypto as crypto } from 'node:crypto'; + +// `buffer.File` was added in Node 18.13.0 while the `File` global was added in Node 20.0.0 +const File = /** @type {import('node:buffer') & { File?: File}} */ (buffer).File; + +/** @type {Record} */ +const globals = { + crypto, + File +}; + +// exported for dev/preview and node environments +/** + * Make various web APIs available as globals: + * - `crypto` + * - `File` + */ +export function installPolyfills() { + for (const name in globals) { + if (name in globalThis) continue; + + Object.defineProperty(globalThis, name, { + enumerable: true, + configurable: true, + writable: true, + value: globals[name] + }); + } +} diff --git a/node_modules/@sveltejs/kit/src/exports/public.d.ts b/node_modules/@sveltejs/kit/src/exports/public.d.ts new file mode 100644 index 00000000..861aff32 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/public.d.ts @@ -0,0 +1,1372 @@ +import 'svelte'; // pick up `declare module "*.svelte"` +import 'vite/client'; // pick up `declare module "*.jpg"`, etc. +import '../types/ambient.js'; + +import { CompileOptions } from 'svelte/compiler'; +import { + AdapterEntry, + CspDirectives, + HttpMethod, + Logger, + MaybePromise, + Prerendered, + PrerenderEntryGeneratorMismatchHandlerValue, + PrerenderHttpErrorHandlerValue, + PrerenderMissingIdHandlerValue, + PrerenderOption, + RequestOptions, + RouteSegment +} from '../types/private.js'; +import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from 'types'; +import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; + +export { PrerenderOption } from '../types/private.js'; + +/** + * [Adapters](https://kit.svelte.dev/docs/adapters) are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing. + */ +export interface Adapter { + /** + * The name of the adapter, using for logging. Will typically correspond to the package name. + */ + name: string; + /** + * This function is called after SvelteKit has built your app. + * @param builder An object provided by SvelteKit that contains methods for adapting the app + */ + adapt(builder: Builder): MaybePromise; + /** + * Checks called during dev and build to determine whether specific features will work in production with this adapter + */ + supports?: { + /** + * Test support for `read` from `$app/server` + * @param config The merged route config + */ + read?: (details: { config: any; route: { id: string } }) => boolean; + }; + /** + * Creates an `Emulator`, which allows the adapter to influence the environment + * during dev, build and prerendering + */ + emulate?(): MaybePromise; +} + +export type LoadProperties | void> = input extends void + ? undefined // needs to be undefined, because void will break intellisense + : input extends Record + ? input + : unknown; + +export type AwaitedActions any>> = OptionalUnion< + { + [Key in keyof T]: UnpackValidationError>>; + }[keyof T] +>; + +// Takes a union type and returns a union type where each type also has all properties +// of all possible types (typed as undefined), making accessing them more ergonomic +type OptionalUnion< + U extends Record, // not unknown, else interfaces don't satisfy this constraint + A extends keyof U = U extends U ? keyof U : never +> = U extends unknown ? { [P in Exclude]?: never } & U : never; + +declare const uniqueSymbol: unique symbol; + +export interface ActionFailure | undefined = undefined> { + status: number; + data: T; + [uniqueSymbol]: true; // necessary or else UnpackValidationError could wrongly unpack objects with the same shape as ActionFailure +} + +type UnpackValidationError = + T extends ActionFailure + ? X + : T extends void + ? undefined // needs to be undefined, because void will corrupt union type + : T; + +/** + * This object is passed to the `adapt` function of adapters. + * It contains various methods and properties that are useful for adapting the app. + */ +export interface Builder { + /** Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`. */ + log: Logger; + /** Remove `dir` and all its contents. */ + rimraf(dir: string): void; + /** Create `dir` and any required parent directories. */ + mkdirp(dir: string): void; + + /** The fully resolved `svelte.config.js`. */ + config: ValidatedConfig; + /** Information about prerendered pages and assets, if any. */ + prerendered: Prerendered; + /** An array of all routes (including prerendered) */ + routes: RouteDefinition[]; + + // TODO 3.0 remove this method + /** + * Create separate functions that map to one or more routes of your app. + * @param fn A function that groups a set of routes into an entry point + * @deprecated Use `builder.routes` instead + */ + createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise; + + /** + * Find all the assets imported by server files belonging to `routes` + */ + findServerAssets(routes: RouteDefinition[]): string[]; + + /** + * Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps. + */ + generateFallback(dest: string): Promise; + + /** + * Generate a module exposing build-time environment variables as `$env/dynamic/public`. + */ + generateEnvModule(): void; + + /** + * Generate a server-side manifest to initialise the SvelteKit [server](https://kit.svelte.dev/docs/types#public-types-server) with. + * @param opts a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated + */ + generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string; + + /** + * Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`. + * @param name path to the file, relative to the build directory + */ + getBuildDirectory(name: string): string; + /** Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory. */ + getClientDirectory(): string; + /** Get the fully resolved path to the directory containing server-side code. */ + getServerDirectory(): string; + /** Get the application path including any configured `base` path, e.g. `my-base-path/_app`. */ + getAppPath(): string; + + /** + * Write client assets to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writeClient(dest: string): string[]; + /** + * Write prerendered files to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writePrerendered(dest: string): string[]; + /** + * Write server-side code to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writeServer(dest: string): string[]; + /** + * Copy a file or directory. + * @param from the source file or directory + * @param to the destination file or directory + * @param opts.filter a function to determine whether a file or directory should be copied + * @param opts.replace a map of strings to replace + * @returns an array of files that were copied + */ + copy( + from: string, + to: string, + opts?: { + filter?(basename: string): boolean; + replace?: Record; + } + ): string[]; + + /** + * Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals. + * @param {string} directory The directory containing the files to be compressed + */ + compress(directory: string): Promise; +} + +export interface Config { + /** + * Options passed to [`svelte.compile`](https://svelte.dev/docs#compile-time-svelte-compile). + * @default {} + */ + compilerOptions?: CompileOptions; + /** + * List of file extensions that should be treated as Svelte files. + * @default [".svelte"] + */ + extensions?: string[]; + /** SvelteKit options */ + kit?: KitConfig; + /** Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. */ + preprocess?: any; + /** `vite-plugin-svelte` plugin options. */ + vitePlugin?: PluginOptions; + /** Any additional options required by tooling that integrates with Svelte. */ + [key: string]: any; +} + +export interface Cookies { + /** + * Gets a cookie that was previously set with `cookies.set`, or from the request headers. + * @param name the name of the cookie + * @param opts the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) + */ + get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined; + + /** + * Gets all cookies that were previously set with `cookies.set`, or from the request headers. + * @param opts the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) + */ + getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>; + + /** + * Sets a cookie. This will add a `set-cookie` header to the response, but also make the cookie available via `cookies.get` or `cookies.getAll` during the current request. + * + * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. + * + * You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children + * @param name the name of the cookie + * @param value the cookie value + * @param opts the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + set( + name: string, + value: string, + opts: import('cookie').CookieSerializeOptions & { path: string } + ): void; + + /** + * Deletes a cookie by setting its value to an empty string and setting the expiry date in the past. + * + * You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children + * @param name the name of the cookie + * @param opts the options, passed directly to `cookie.serialize`. The `path` must match the path of the cookie you want to delete. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + delete(name: string, opts: import('cookie').CookieSerializeOptions & { path: string }): void; + + /** + * Serialize a cookie name-value pair into a `Set-Cookie` header string, but don't apply it to the response. + * + * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. + * + * You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children + * + * @param name the name of the cookie + * @param value the cookie value + * @param opts the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + serialize( + name: string, + value: string, + opts: import('cookie').CookieSerializeOptions & { path: string } + ): string; +} + +/** + * A collection of functions that influence the environment during dev, build and prerendering + */ +export interface Emulator { + /** + * A function that is called with the current route `config` and `prerender` option + * and returns an `App.Platform` object + */ + platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise; +} + +export interface KitConfig { + /** + * Your [adapter](https://kit.svelte.dev/docs/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. + * @default undefined + */ + adapter?: Adapter; + /** + * An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. + * + * ```js + * /// file: svelte.config.js + * /// type: import('@sveltejs/kit').Config + * const config = { + * kit: { + * alias: { + * // this will match a file + * 'my-file': 'path/to/my-file.js', + * + * // this will match a directory and its contents + * // (`my-directory/x` resolves to `path/to/my-directory/x`) + * 'my-directory': 'path/to/my-directory', + * + * // an alias ending /* will only match + * // the contents of a directory, not the directory itself + * 'my-directory/*': 'path/to/my-directory/*' + * } + * } + * }; + * ``` + * + * > The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging. + * + * > You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`. + * @default {} + */ + alias?: Record; + /** + * The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes. + * + * If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`. + * @default "_app" + */ + appDir?: string; + /** + * [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this... + * + * ```js + * /// file: svelte.config.js + * /// type: import('@sveltejs/kit').Config + * const config = { + * kit: { + * csp: { + * directives: { + * 'script-src': ['self'] + * }, + * reportOnly: { + * 'script-src': ['self'] + * } + * } + * } + * }; + * + * export default config; + * ``` + * + * ...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates. + * + * To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example ` + * ``` + * + * If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the [`updated`](/docs/modules#$app-stores-updated) store to `true` when it detects one. + */ + version?: { + /** + * The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build. + * + * For example, to use the current commit hash, you could do use `git rev-parse HEAD`: + * + * ```js + * /// file: svelte.config.js + * import * as child_process from 'node:child_process'; + * + * export default { + * kit: { + * version: { + * name: child_process.execSync('git rev-parse HEAD').toString().trim() + * } + * } + * }; + * ``` + */ + name?: string; + /** + * The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. + * @default 0 + */ + pollInterval?: number; + }; +} + +/** + * The [`handle`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) hook runs every time the SvelteKit server receives a [request](https://kit.svelte.dev/docs/web-standards#fetch-apis-request) and + * determines the [response](https://kit.svelte.dev/docs/web-standards#fetch-apis-response). + * It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`. + * This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example). + */ +export type Handle = (input: { + event: RequestEvent; + resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; +}) => MaybePromise; + +/** + * The server-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while responding to a request. + * + * If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. + * Make sure that this function _never_ throws an error. + */ +export type HandleServerError = (input: { + error: unknown; + event: RequestEvent; + status: number; + message: string; +}) => MaybePromise; + +/** + * The client-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while navigating. + * + * If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. + * Make sure that this function _never_ throws an error. + */ +export type HandleClientError = (input: { + error: unknown; + event: NavigationEvent; + status: number; + message: string; +}) => MaybePromise; + +/** + * The [`handleFetch`](https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch) hook allows you to modify (or replace) a `fetch` request that happens inside a `load` function that runs on the server (or during pre-rendering) + */ +export type HandleFetch = (input: { + event: RequestEvent; + request: Request; + fetch: typeof fetch; +}) => MaybePromise; + +/** + * The [`reroute`](https://kit.svelte.dev/docs/hooks#universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render. + * @since 2.3.0 + */ +export type Reroute = (event: { url: URL }) => void | string; + +/** + * The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `Load` directly. + */ +export type Load< + Params extends Partial> = Partial>, + InputData extends Record | null = Record | null, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null +> = (event: LoadEvent) => MaybePromise; + +/** + * The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `LoadEvent` directly. + */ +export interface LoadEvent< + Params extends Partial> = Partial>, + Data extends Record | null = Record | null, + ParentData extends Record = Record, + RouteId extends string | null = string | null +> extends NavigationEvent { + /** + * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: + * + * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. + * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). + * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. + * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) + * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. + * + * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) + */ + fetch: typeof fetch; + /** + * Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any. + */ + data: Data; + /** + * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: + * + * ```js + * /// file: src/routes/blog/+page.js + * export async function load({ fetch, setHeaders }) { + * const url = `https://cms.example.com/articles.json`; + * const response = await fetch(url); + * + * setHeaders({ + * age: response.headers.get('age'), + * 'cache-control': response.headers.get('cache-control') + * }); + * + * return response.json(); + * } + * ``` + * + * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. + * + * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API in a server-only `load` function instead. + * + * `setHeaders` has no effect when a `load` function runs in the browser. + */ + setHeaders(headers: Record): void; + /** + * `await parent()` returns data from parent `+layout.js` `load` functions. + * Implicitly, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will return and forward data from parent `+layout.server.js` files. + * + * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. + */ + parent(): Promise; + /** + * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. + * + * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. + * + * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). + * + * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). + * + * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. + * + * ```js + * /// file: src/routes/+page.js + * let count = 0; + * export async function load({ depends }) { + * depends('increase:count'); + * + * return { count: count++ }; + * } + * ``` + * + * ```html + * /// file: src/routes/+page.svelte + * + * + *

{data.count}

+ * + * ``` + */ + depends(...deps: Array<`${string}:${string}`>): void; + /** + * Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: + * + * ```js + * /// file: src/routes/+page.server.js + * export async function load({ untrack, url }) { + * // Untrack url.pathname so that path changes don't trigger a rerun + * if (untrack(() => url.pathname === '/')) { + * return { message: 'Welcome!' }; + * } + * } + * ``` + */ + untrack(fn: () => T): T; +} + +export interface NavigationEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null +> { + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * The URL of the current page + */ + url: URL; +} + +/** + * Information about the target of a specific navigation. + */ +export interface NavigationTarget { + /** + * Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object. + * Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route). + */ + params: Record | null; + /** + * Info about the target route + */ + route: { id: string | null }; + /** + * The URL that is navigated to + */ + url: URL; +} + +/** + * - `enter`: The app has hydrated + * - `form`: The user submitted a `

` with a GET method + * - `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ +export type NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'; + +export interface Navigation { + /** + * Where navigation was triggered from + */ + from: NavigationTarget | null; + /** + * Where navigation is going to/has gone to + */ + to: NavigationTarget | null; + /** + * The type of navigation: + * - `form`: The user submitted a `` + * - `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Exclude; + /** + * Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) + */ + willUnload: boolean; + /** + * In case of a history back/forward navigation, the number of steps to go back/forward + */ + delta?: number; + /** + * A promise that resolves once the navigation is complete, and rejects if the navigation + * fails or is aborted. In the case of a `willUnload` navigation, the promise will never resolve + */ + complete: Promise; +} + +/** + * The argument passed to [`beforeNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-beforenavigate) callbacks. + */ +export interface BeforeNavigate extends Navigation { + /** + * Call this to prevent the navigation from starting. + */ + cancel(): void; +} + +/** + * The argument passed to [`onNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-onnavigate) callbacks. + */ +export interface OnNavigate extends Navigation { + /** + * The type of navigation: + * - `form`: The user submitted a `` + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Exclude; + /** + * Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page. + */ + willUnload: false; +} + +/** + * The argument passed to [`afterNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-afternavigate) callbacks. + */ +export interface AfterNavigate extends Omit { + /** + * The type of navigation: + * - `enter`: The app has hydrated + * - `form`: The user submitted a `` + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Exclude; + /** + * Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page. + */ + willUnload: false; +} + +/** + * The shape of the `$page` store + */ +export interface Page< + Params extends Record = Record, + RouteId extends string | null = string | null +> { + /** + * The URL of the current page + */ + url: URL; + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * Http status code of the current page + */ + status: number; + /** + * The error object of the current page, if any. Filled from the `handleError` hooks. + */ + error: App.Error | null; + /** + * The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`. + */ + data: App.PageData & Record; + /** + * The page state, which can be manipulated using the [`pushState`](https://kit.svelte.dev/docs/modules#$app-navigation-pushstate) and [`replaceState`](https://kit.svelte.dev/docs/modules#$app-navigation-replacestate) functions from `$app/navigation`. + */ + state: App.PageState; + /** + * Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. + */ + form: any; +} + +/** + * The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. + */ +export type ParamMatcher = (param: string) => boolean; + +export interface RequestEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null +> { + /** + * Get or set cookies related to the current request + */ + cookies: Cookies; + /** + * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: + * + * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. + * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). + * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. + * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) + * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. + * + * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) + */ + fetch: typeof fetch; + /** + * The client's IP address, set by the adapter. + */ + getClientAddress(): string; + /** + * Contains custom data that was added to the request within the [`handle hook`](https://kit.svelte.dev/docs/hooks#server-hooks-handle). + */ + locals: App.Locals; + /** + * The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Additional data made available through the adapter. + */ + platform: Readonly | undefined; + /** + * The original request object + */ + request: Request; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: + * + * ```js + * /// file: src/routes/blog/+page.js + * export async function load({ fetch, setHeaders }) { + * const url = `https://cms.example.com/articles.json`; + * const response = await fetch(url); + * + * setHeaders({ + * age: response.headers.get('age'), + * 'cache-control': response.headers.get('cache-control') + * }); + * + * return response.json(); + * } + * ``` + * + * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. + * + * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API instead. + */ + setHeaders(headers: Record): void; + /** + * The requested URL. + */ + url: URL; + /** + * `true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information + * related to the data request in this case. Use this property instead if the distinction is important to you. + */ + isDataRequest: boolean; + /** + * `true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server. + */ + isSubRequest: boolean; +} + +/** + * A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method. + * + * It receives `Params` as the first generic argument, which you can skip by using [generated types](https://kit.svelte.dev/docs/types#generated-types) instead. + */ +export type RequestHandler< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null +> = (event: RequestEvent) => MaybePromise; + +export interface ResolveOptions { + /** + * Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML + * (they could include an element's opening tag but not its closing tag, for example) + * but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components. + * @param input the html chunk and the info if this is the last chunk + */ + transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; + /** + * Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. + * By default, none will be included. + * @param name header name + * @param value header value + */ + filterSerializedResponseHeaders?(name: string, value: string): boolean; + /** + * Determines what should be added to the `` tag to preload it. + * By default, `js` and `css` files will be preloaded. + * @param input the type of the file and its path + */ + preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; +} + +export interface RouteDefinition { + id: string; + api: { + methods: Array; + }; + page: { + methods: Array>; + }; + pattern: RegExp; + prerender: PrerenderOption; + segments: RouteSegment[]; + methods: Array; + config: Config; +} + +export class Server { + constructor(manifest: SSRManifest); + init(options: ServerInitOptions): Promise; + respond(request: Request, options: RequestOptions): Promise; +} + +export interface ServerInitOptions { + /** A map of environment variables */ + env: Record; + /** A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work */ + read?: (file: string) => ReadableStream; +} + +export interface SSRManifest { + appDir: string; + appPath: string; + assets: Set; + mimeTypes: Record; + + /** private fields */ + _: { + client: NonNullable; + nodes: SSRNodeLoader[]; + routes: SSRRoute[]; + matchers(): Promise>; + /** A `[file]: size` map of all assets imported by server code */ + server_assets: Record; + }; +} + +/** + * The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `ServerLoad` directly. + */ +export type ServerLoad< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null +> = (event: ServerLoadEvent) => MaybePromise; + +export interface ServerLoadEvent< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + RouteId extends string | null = string | null +> extends RequestEvent { + /** + * `await parent()` returns data from parent `+layout.server.js` `load` functions. + * + * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. + */ + parent(): Promise; + /** + * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. + * + * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. + * + * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). + * + * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). + * + * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. + * + * ```js + * /// file: src/routes/+page.js + * let count = 0; + * export async function load({ depends }) { + * depends('increase:count'); + * + * return { count: count++ }; + * } + * ``` + * + * ```html + * /// file: src/routes/+page.svelte + * + * + *

{data.count}

+ * + * ``` + */ + depends(...deps: string[]): void; + /** + * Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: + * + * ```js + * /// file: src/routes/+page.js + * export async function load({ untrack, url }) { + * // Untrack url.pathname so that path changes don't trigger a rerun + * if (untrack(() => url.pathname === '/')) { + * return { message: 'Welcome!' }; + * } + * } + * ``` + */ + untrack(fn: () => T): T; +} + +/** + * Shape of a form action method that is part of `export const actions = {..}` in `+page.server.js`. + * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. + */ +export type Action< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null +> = (event: RequestEvent) => MaybePromise; + +/** + * Shape of the `export const actions = {..}` object in `+page.server.js`. + * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. + */ +export type Actions< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null +> = Record>; + +/** + * When calling a form action via fetch, the response will be one of these shapes. + * ```svelte + * { + * return ({ result }) => { + * // result is of type ActionResult + * }; + * }} + * ``` + */ +export type ActionResult< + Success extends Record | undefined = Record, + Failure extends Record | undefined = Record +> = + | { type: 'success'; status: number; data?: Success } + | { type: 'failure'; status: number; data?: Failure } + | { type: 'redirect'; status: number; location: string } + | { type: 'error'; status?: number; error: any }; + +/** + * The object returned by the [`error`](https://kit.svelte.dev/docs/modules#sveltejs-kit-error) function. + */ +export interface HttpError { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ + status: number; + /** The content of the error. */ + body: App.Error; +} + +/** + * The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function + */ +export interface Redirect { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. */ + status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; + /** The location to redirect to. */ + location: string; +} + +export type SubmitFunction< + Success extends Record | undefined = Record, + Failure extends Record | undefined = Record +> = (input: { + action: URL; + formData: FormData; + formElement: HTMLFormElement; + controller: AbortController; + submitter: HTMLElement | null; + cancel(): void; +}) => MaybePromise< + | void + | ((opts: { + formData: FormData; + formElement: HTMLFormElement; + action: URL; + result: ActionResult; + /** + * Call this to get the default behavior of a form submission response. + * @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. + * @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission. + */ + update(options?: { reset?: boolean; invalidateAll?: boolean }): Promise; + }) => void) +>; + +/** + * The type of `export const snapshot` exported from a page or layout component. + */ +export interface Snapshot { + capture: () => T; + restore: (snapshot: T) => void; +} + +export * from './index.js'; diff --git a/node_modules/@sveltejs/kit/src/exports/vite/build/build_server.js b/node_modules/@sveltejs/kit/src/exports/vite/build/build_server.js new file mode 100644 index 00000000..f13c2987 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/build/build_server.js @@ -0,0 +1,111 @@ +import fs from 'node:fs'; +import { mkdirp } from '../../../utils/filesystem.js'; +import { find_deps, resolve_symlinks } from './utils.js'; +import { s } from '../../../utils/misc.js'; +import { normalizePath } from 'vite'; + +/** + * @param {string} out + * @param {import('types').ValidatedKitConfig} kit + * @param {import('types').ManifestData} manifest_data + * @param {import('vite').Manifest} server_manifest + * @param {import('vite').Manifest | null} client_manifest + * @param {import('vite').Rollup.OutputAsset[] | null} css + */ +export function build_server_nodes(out, kit, manifest_data, server_manifest, client_manifest, css) { + mkdirp(`${out}/server/nodes`); + mkdirp(`${out}/server/stylesheets`); + + const stylesheet_lookup = new Map(); + + if (css) { + css.forEach((asset) => { + if (asset.source.length < kit.inlineStyleThreshold) { + const index = stylesheet_lookup.size; + const file = `${out}/server/stylesheets/${index}.js`; + + fs.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`); + stylesheet_lookup.set(asset.fileName, index); + } + }); + } + + manifest_data.nodes.forEach((node, i) => { + /** @type {string[]} */ + const imports = []; + + // String representation of + /** @type {import('types').SSRNode} */ + /** @type {string[]} */ + const exports = [`export const index = ${i};`]; + + /** @type {string[]} */ + const imported = []; + + /** @type {string[]} */ + const stylesheets = []; + + /** @type {string[]} */ + const fonts = []; + + if (node.component && client_manifest) { + exports.push( + 'let component_cache;', + `export const component = async () => component_cache ??= (await import('../${ + resolve_symlinks(server_manifest, node.component).chunk.file + }')).default;` + ); + } + + if (node.universal) { + imports.push(`import * as universal from '../${server_manifest[node.universal].file}';`); + exports.push('export { universal };'); + exports.push(`export const universal_id = ${s(node.universal)};`); + } + + if (node.server) { + imports.push(`import * as server from '../${server_manifest[node.server].file}';`); + exports.push('export { server };'); + exports.push(`export const server_id = ${s(node.server)};`); + } + + if (client_manifest && (node.universal || node.component)) { + const entry = find_deps( + client_manifest, + `${normalizePath(kit.outDir)}/generated/client-optimized/nodes/${i}.js`, + true + ); + + imported.push(...entry.imports); + stylesheets.push(...entry.stylesheets); + fonts.push(...entry.fonts); + } + + exports.push( + `export const imports = ${s(imported)};`, + `export const stylesheets = ${s(stylesheets)};`, + `export const fonts = ${s(fonts)};` + ); + + /** @type {string[]} */ + const styles = []; + + stylesheets.forEach((file) => { + if (stylesheet_lookup.has(file)) { + const index = stylesheet_lookup.get(file); + const name = `stylesheet_${index}`; + imports.push(`import ${name} from '../stylesheets/${index}.js';`); + styles.push(`\t${s(file)}: ${name}`); + } + }); + + if (styles.length > 0) { + exports.push(`export const inline_styles = () => ({\n${styles.join(',\n')}\n});`); + } + + fs.writeFileSync( + `${out}/server/nodes/${i}.js`, + `${imports.join('\n')}\n\n${exports.join('\n')}\n` + ); + }); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/build/build_service_worker.js b/node_modules/@sveltejs/kit/src/exports/vite/build/build_service_worker.js new file mode 100644 index 00000000..a7c11188 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/build/build_service_worker.js @@ -0,0 +1,128 @@ +import fs from 'node:fs'; +import * as vite from 'vite'; +import { dedent } from '../../../core/sync/utils.js'; +import { s } from '../../../utils/misc.js'; +import { get_config_aliases, strip_virtual_prefix, get_env } from '../utils.js'; +import { create_static_module } from '../../../core/env.js'; +import { env_static_public, service_worker } from '../module_ids.js'; + +/** + * @param {string} out + * @param {import('types').ValidatedKitConfig} kit + * @param {import('vite').ResolvedConfig} vite_config + * @param {import('types').ManifestData} manifest_data + * @param {string} service_worker_entry_file + * @param {import('types').Prerendered} prerendered + * @param {import('vite').Manifest} client_manifest + */ +export async function build_service_worker( + out, + kit, + vite_config, + manifest_data, + service_worker_entry_file, + prerendered, + client_manifest +) { + const build = new Set(); + for (const key in client_manifest) { + const { file, css = [], assets = [] } = client_manifest[key]; + build.add(file); + css.forEach((file) => build.add(file)); + assets.forEach((file) => build.add(file)); + } + + // in a service worker, `location` is the location of the service worker itself, + // which is guaranteed to be `/service-worker.js` + const base = "location.pathname.split('/').slice(0, -1).join('/')"; + + const service_worker_code = dedent` + export const base = /*@__PURE__*/ ${base}; + + export const build = [ + ${Array.from(build) + .map((file) => `base + ${s(`/${file}`)}`) + .join(',\n')} + ]; + + export const files = [ + ${manifest_data.assets + .filter((asset) => kit.serviceWorker.files(asset.file)) + .map((asset) => `base + ${s(`/${asset.file}`)}`) + .join(',\n')} + ]; + + export const prerendered = [ + ${prerendered.paths.map((path) => `base + ${s(path.replace(kit.paths.base, ''))}`).join(',\n')} + ]; + + export const version = ${s(kit.version.name)}; + `; + + const env = get_env(kit.env, vite_config.mode); + + /** + * @type {import('vite').Plugin} + */ + const sw_virtual_modules = { + name: 'service-worker-build-virtual-modules', + resolveId(id) { + if (id.startsWith('$env/') || id.startsWith('$app/') || id === '$service-worker') { + return `\0virtual:${id}`; + } + }, + + load(id) { + if (!id.startsWith('\0virtual:')) return; + + if (id === service_worker) { + return service_worker_code; + } + + if (id === env_static_public) { + return create_static_module('$env/static/public', env.public); + } + + const stripped = strip_virtual_prefix(id); + throw new Error( + `Cannot import ${stripped} into service-worker code. Only the modules $service-worker and $env/static/public are available in service workers.` + ); + } + }; + + await vite.build({ + build: { + modulePreload: false, + rollupOptions: { + input: { + 'service-worker': service_worker_entry_file + }, + output: { + // .mjs so that esbuild doesn't incorrectly inject `export` https://github.com/vitejs/vite/issues/15379 + entryFileNames: 'service-worker.mjs', + assetFileNames: `${kit.appDir}/immutable/assets/[name].[hash][extname]`, + inlineDynamicImports: true + } + }, + outDir: `${out}/client`, + emptyOutDir: false + }, + configFile: false, + define: vite_config.define, + publicDir: false, + plugins: [sw_virtual_modules], + resolve: { + alias: [...get_config_aliases(kit)] + }, + experimental: { + renderBuiltUrl(filename) { + return { + runtime: `new URL(${JSON.stringify(filename)}, location.href).pathname` + }; + } + } + }); + + // rename .mjs to .js to avoid incorrect MIME types with ancient webservers + fs.renameSync(`${out}/client/service-worker.mjs`, `${out}/client/service-worker.js`); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/build/utils.js b/node_modules/@sveltejs/kit/src/exports/vite/build/utils.js new file mode 100644 index 00000000..f2657476 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/build/utils.js @@ -0,0 +1,105 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { normalizePath } from 'vite'; + +/** + * Adds transitive JS and CSS dependencies to the js and css inputs. + * @param {import('vite').Manifest} manifest + * @param {string} entry + * @param {boolean} add_dynamic_css + * @returns {import('types').AssetDependencies} + */ +export function find_deps(manifest, entry, add_dynamic_css) { + /** @type {Set} */ + const seen = new Set(); + + /** @type {Set} */ + const imports = new Set(); + + /** @type {Set} */ + const stylesheets = new Set(); + + /** @type {Set} */ + const imported_assets = new Set(); + + /** + * @param {string} current + * @param {boolean} add_js + */ + function traverse(current, add_js) { + if (seen.has(current)) return; + seen.add(current); + + const { chunk } = resolve_symlinks(manifest, current); + + if (add_js) imports.add(chunk.file); + + if (chunk.assets) { + for (const asset of chunk.assets) { + imported_assets.add(asset); + } + } + + if (chunk.css) { + chunk.css.forEach((file) => stylesheets.add(file)); + } + + if (chunk.imports) { + chunk.imports.forEach((file) => traverse(file, add_js)); + } + + if (add_dynamic_css && chunk.dynamicImports) { + chunk.dynamicImports.forEach((file) => traverse(file, false)); + } + } + + const { chunk, file } = resolve_symlinks(manifest, entry); + + traverse(file, true); + + const assets = Array.from(imported_assets); + + return { + assets, + file: chunk.file, + imports: Array.from(imports), + stylesheets: Array.from(stylesheets), + // TODO do we need this separately? + fonts: assets.filter((asset) => /\.(woff2?|ttf|otf)$/.test(asset)) + }; +} + +/** + * @param {import('vite').Manifest} manifest + * @param {string} file + */ +export function resolve_symlinks(manifest, file) { + while (!manifest[file]) { + const next = normalizePath(path.relative('.', fs.realpathSync(file))); + if (next === file) throw new Error(`Could not find file "${file}" in Vite manifest`); + file = next; + } + + const chunk = manifest[file]; + + return { chunk, file }; +} + +const method_names = new Set(['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'OPTIONS']); + +// If we'd written this in TypeScript, it could be easy... +/** + * @param {string} str + * @returns {str is import('types').HttpMethod} + */ +export function is_http_method(str) { + return method_names.has(str); +} + +/** + * @param {import('types').ValidatedKitConfig} config + * @returns {string} + */ +export function assets_base(config) { + return (config.paths.assets || config.paths.base || '.') + '/'; +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js b/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js new file mode 100644 index 00000000..e9eb23ec --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js @@ -0,0 +1,630 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import process from 'node:process'; +import { URL } from 'node:url'; +import { AsyncLocalStorage } from 'node:async_hooks'; +import colors from 'kleur'; +import sirv from 'sirv'; +import { isCSSRequest, loadEnv, buildErrorMessage } from 'vite'; +import { createReadableStream, getRequest, setResponse } from '../../../exports/node/index.js'; +import { installPolyfills } from '../../../exports/node/polyfills.js'; +import { coalesce_to_error } from '../../../utils/error.js'; +import { from_fs, posixify, resolve_entry, to_fs } from '../../../utils/filesystem.js'; +import { load_error_page } from '../../../core/config/index.js'; +import { SVELTE_KIT_ASSETS } from '../../../constants.js'; +import * as sync from '../../../core/sync/sync.js'; +import { get_mime_lookup, runtime_base } from '../../../core/utils.js'; +import { compact } from '../../../utils/array.js'; +import { not_found } from '../utils.js'; +import { SCHEME } from '../../../utils/url.js'; +import { check_feature } from '../../../utils/features.js'; + +const cwd = process.cwd(); + +/** + * @param {import('vite').ViteDevServer} vite + * @param {import('vite').ResolvedConfig} vite_config + * @param {import('types').ValidatedConfig} svelte_config + * @return {Promise void>>} + */ +export async function dev(vite, vite_config, svelte_config) { + installPolyfills(); + + const async_local_storage = new AsyncLocalStorage(); + + globalThis.__SVELTEKIT_TRACK__ = (label) => { + const context = async_local_storage.getStore(); + if (!context || context.prerender === true) return; + + check_feature(context.event.route.id, context.config, label, svelte_config.kit.adapter); + }; + + const fetch = globalThis.fetch; + globalThis.fetch = (info, init) => { + if (typeof info === 'string' && !SCHEME.test(info)) { + throw new Error( + `Cannot use relative URL (${info}) with global fetch — use \`event.fetch\` instead: https://kit.svelte.dev/docs/web-standards#fetch-apis` + ); + } + + return fetch(info, init); + }; + + sync.init(svelte_config, vite_config.mode); + + /** @type {import('types').ManifestData} */ + let manifest_data; + /** @type {import('@sveltejs/kit').SSRManifest} */ + let manifest; + + /** @type {Error | null} */ + let manifest_error = null; + + /** @param {string} url */ + async function loud_ssr_load_module(url) { + try { + return await vite.ssrLoadModule(url, { fixStacktrace: true }); + } catch (/** @type {any} */ err) { + const msg = buildErrorMessage(err, [colors.red(`Internal server error: ${err.message}`)]); + + if (!vite.config.logger.hasErrorLogged(err)) { + vite.config.logger.error(msg, { error: err }); + } + + vite.ws.send({ + type: 'error', + err: { + ...err, + // these properties are non-enumerable and will + // not be serialized unless we explicitly include them + message: err.message, + stack: err.stack + } + }); + + throw err; + } + } + + /** @param {string} id */ + async function resolve(id) { + const url = id.startsWith('..') ? to_fs(path.posix.resolve(id)) : `/${id}`; + + const module = await loud_ssr_load_module(url); + + const module_node = await vite.moduleGraph.getModuleByUrl(url); + if (!module_node) throw new Error(`Could not find node for ${url}`); + + return { module, module_node, url }; + } + + function update_manifest() { + try { + ({ manifest_data } = sync.create(svelte_config)); + + if (manifest_error) { + manifest_error = null; + vite.ws.send({ type: 'full-reload' }); + } + } catch (error) { + manifest_error = /** @type {Error} */ (error); + + console.error(colors.bold().red(manifest_error.message)); + vite.ws.send({ + type: 'error', + err: { + message: manifest_error.message ?? 'Invalid routes', + stack: '' + } + }); + + return; + } + + manifest = { + appDir: svelte_config.kit.appDir, + appPath: svelte_config.kit.appDir, + assets: new Set(manifest_data.assets.map((asset) => asset.file)), + mimeTypes: get_mime_lookup(manifest_data), + _: { + client: { + start: `${runtime_base}/client/entry.js`, + app: `${to_fs(svelte_config.kit.outDir)}/generated/client/app.js`, + imports: [], + stylesheets: [], + fonts: [], + uses_env_dynamic_public: true + }, + server_assets: new Proxy( + {}, + { + has: (_, /** @type {string} */ file) => fs.existsSync(from_fs(file)), + get: (_, /** @type {string} */ file) => fs.statSync(from_fs(file)).size + } + ), + nodes: manifest_data.nodes.map((node, index) => { + return async () => { + /** @type {import('types').SSRNode} */ + const result = {}; + + /** @type {import('vite').ModuleNode[]} */ + const module_nodes = []; + + result.index = index; + + // these are unused in dev, it's easier to include them + result.imports = []; + result.stylesheets = []; + result.fonts = []; + + if (node.component) { + result.component = async () => { + const { module_node, module } = await resolve( + /** @type {string} */ (node.component) + ); + + module_nodes.push(module_node); + + return module.default; + }; + } + + if (node.universal) { + const { module, module_node } = await resolve(node.universal); + + module_nodes.push(module_node); + + result.universal = module; + result.universal_id = node.universal; + } + + if (node.server) { + const { module } = await resolve(node.server); + result.server = module; + result.server_id = node.server; + } + + // in dev we inline all styles to avoid FOUC. this gets populated lazily so that + // components/stylesheets loaded via import() during `load` are included + result.inline_styles = async () => { + const deps = new Set(); + + for (const module_node of module_nodes) { + await find_deps(vite, module_node, deps); + } + + /** @type {Record} */ + const styles = {}; + + for (const dep of deps) { + const url = new URL(dep.url, 'dummy:/'); + const query = url.searchParams; + + if ( + (isCSSRequest(dep.file) || + (query.has('svelte') && query.get('type') === 'style')) && + !(query.has('raw') || query.has('url') || query.has('inline')) + ) { + try { + query.set('inline', ''); + const mod = await vite.ssrLoadModule( + `${decodeURI(url.pathname)}${url.search}${url.hash}` + ); + styles[dep.url] = mod.default; + } catch { + // this can happen with dynamically imported modules, I think + // because the Vite module graph doesn't distinguish between + // static and dynamic imports? TODO investigate, submit fix + } + } + } + + return styles; + }; + + return result; + }; + }), + routes: compact( + manifest_data.routes.map((route) => { + if (!route.page && !route.endpoint) return null; + + const endpoint = route.endpoint; + + return { + id: route.id, + pattern: route.pattern, + params: route.params, + page: route.page, + endpoint: endpoint + ? async () => { + const url = path.resolve(cwd, endpoint.file); + return await loud_ssr_load_module(url); + } + : null, + endpoint_id: endpoint?.file + }; + }) + ), + matchers: async () => { + /** @type {Record} */ + const matchers = {}; + + for (const key in manifest_data.matchers) { + const file = manifest_data.matchers[key]; + const url = path.resolve(cwd, file); + const module = await vite.ssrLoadModule(url, { fixStacktrace: true }); + + if (module.match) { + matchers[key] = module.match; + } else { + throw new Error(`${file} does not export a \`match\` function`); + } + } + + return matchers; + } + } + }; + } + + /** @param {Error} error */ + function fix_stack_trace(error) { + vite.ssrFixStacktrace(error); + return error.stack; + } + + update_manifest(); + + /** + * @param {string} event + * @param {(file: string) => void} cb + */ + const watch = (event, cb) => { + vite.watcher.on(event, (file) => { + if ( + file.startsWith(svelte_config.kit.files.routes + path.sep) || + file.startsWith(svelte_config.kit.files.params + path.sep) || + // in contrast to server hooks, client hooks are written to the client manifest + // and therefore need rebuilding when they are added/removed + file.startsWith(svelte_config.kit.files.hooks.client) + ) { + cb(file); + } + }); + }; + /** @type {NodeJS.Timeout | null } */ + let timeout = null; + /** @param {() => void} to_run */ + const debounce = (to_run) => { + timeout && clearTimeout(timeout); + timeout = setTimeout(() => { + timeout = null; + to_run(); + }, 100); + }; + + // flag to skip watchers if server is already restarting + let restarting = false; + + // Debounce add/unlink events because in case of folder deletion or moves + // they fire in rapid succession, causing needless invocations. + watch('add', () => debounce(update_manifest)); + watch('unlink', () => debounce(update_manifest)); + watch('change', (file) => { + // Don't run for a single file if the whole manifest is about to get updated + if (timeout || restarting) return; + + sync.update(svelte_config, manifest_data, file); + }); + + const { appTemplate, errorTemplate, serviceWorker, hooks } = svelte_config.kit.files; + + // vite client only executes a full reload if the triggering html file path is index.html + // kit defaults to src/app.html, so unless user changed that to index.html + // send the vite client a full-reload event without path being set + if (appTemplate !== 'index.html') { + vite.watcher.on('change', (file) => { + if (file === appTemplate && !restarting) { + vite.ws.send({ type: 'full-reload' }); + } + }); + } + + vite.watcher.on('all', (_, file) => { + if ( + file === appTemplate || + file === errorTemplate || + file.startsWith(serviceWorker) || + file.startsWith(hooks.server) + ) { + sync.server(svelte_config); + } + }); + + // changing the svelte config requires restarting the dev server + // the config is only read on start and passed on to vite-plugin-svelte + // which needs up-to-date values to operate correctly + vite.watcher.on('change', (file) => { + if (path.basename(file) === 'svelte.config.js') { + console.log(`svelte config changed, restarting vite dev-server. changed file: ${file}`); + restarting = true; + vite.restart(); + } + }); + + const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base; + const asset_server = sirv(svelte_config.kit.files.assets, { + dev: true, + etag: true, + maxAge: 0, + extensions: [], + setHeaders: (res) => { + res.setHeader('access-control-allow-origin', '*'); + } + }); + + async function align_exports() { + // This shameful hack allows us to load runtime server code via Vite + // while apps load `HttpError` and `Redirect` in Node, without + // causing `instanceof` checks to fail + const control_module_node = await import('../../../runtime/control.js'); + const control_module_vite = await vite.ssrLoadModule(`${runtime_base}/control.js`); + + control_module_node.replace_implementations({ + ActionFailure: control_module_vite.ActionFailure, + HttpError: control_module_vite.HttpError, + Redirect: control_module_vite.Redirect, + SvelteKitError: control_module_vite.SvelteKitError + }); + } + align_exports(); + const ws_send = vite.ws.send; + /** @param {any} args */ + vite.ws.send = function (...args) { + // We need to reapply the patch after Vite did dependency optimizations + // because that clears the module resolutions + if (args[0]?.type === 'full-reload' && args[0].path === '*') { + align_exports(); + } + return ws_send.apply(vite.ws, args); + }; + + vite.middlewares.use((req, res, next) => { + try { + const base = `${vite.config.server.https ? 'https' : 'http'}://${ + req.headers[':authority'] || req.headers.host + }`; + + const decoded = decodeURI(new URL(base + req.url).pathname); + + if (decoded.startsWith(assets)) { + const pathname = decoded.slice(assets.length); + const file = svelte_config.kit.files.assets + pathname; + + if (fs.existsSync(file) && !fs.statSync(file).isDirectory()) { + if (has_correct_case(file, svelte_config.kit.files.assets)) { + req.url = encodeURI(pathname); // don't need query/hash + asset_server(req, res); + return; + } + } + } + + next(); + } catch (e) { + const error = coalesce_to_error(e); + res.statusCode = 500; + res.end(fix_stack_trace(error)); + } + }); + + const env = loadEnv(vite_config.mode, svelte_config.kit.env.dir, ''); + const emulator = await svelte_config.kit.adapter?.emulate?.(); + + return () => { + const serve_static_middleware = vite.middlewares.stack.find( + (middleware) => + /** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware' + ); + + // Vite will give a 403 on URLs like /test, /static, and /package.json preventing us from + // serving routes with those names. See https://github.com/vitejs/vite/issues/7363 + remove_static_middlewares(vite.middlewares); + + vite.middlewares.use(async (req, res) => { + // Vite's base middleware strips out the base path. Restore it + const original_url = req.url; + req.url = req.originalUrl; + try { + const base = `${vite.config.server.https ? 'https' : 'http'}://${ + req.headers[':authority'] || req.headers.host + }`; + + const decoded = decodeURI(new URL(base + req.url).pathname); + const file = posixify(path.resolve(decoded.slice(svelte_config.kit.paths.base.length + 1))); + const is_file = fs.existsSync(file) && !fs.statSync(file).isDirectory(); + const allowed = + !vite_config.server.fs.strict || + vite_config.server.fs.allow.some((dir) => file.startsWith(dir)); + + if (is_file && allowed) { + req.url = original_url; + // @ts-expect-error + serve_static_middleware.handle(req, res); + return; + } + + if (!decoded.startsWith(svelte_config.kit.paths.base)) { + return not_found(req, res, svelte_config.kit.paths.base); + } + + if (decoded === svelte_config.kit.paths.base + '/service-worker.js') { + const resolved = resolve_entry(svelte_config.kit.files.serviceWorker); + + if (resolved) { + res.writeHead(200, { + 'content-type': 'application/javascript' + }); + res.end(`import '${to_fs(resolved)}';`); + } else { + res.writeHead(404); + res.end('not found'); + } + + return; + } + + // we have to import `Server` before calling `set_assets` + const { Server } = /** @type {import('types').ServerModule} */ ( + await vite.ssrLoadModule(`${runtime_base}/server/index.js`, { fixStacktrace: true }) + ); + + const { set_fix_stack_trace } = await vite.ssrLoadModule( + `${runtime_base}/shared-server.js` + ); + set_fix_stack_trace(fix_stack_trace); + + const { set_assets } = await vite.ssrLoadModule('__sveltekit/paths'); + set_assets(assets); + + const server = new Server(manifest); + + await server.init({ + env, + read: (file) => createReadableStream(from_fs(file)) + }); + + const request = await getRequest({ + base, + request: req + }); + + if (manifest_error) { + console.error(colors.bold().red(manifest_error.message)); + + const error_page = load_error_page(svelte_config); + + /** @param {{ status: number; message: string }} opts */ + const error_template = ({ status, message }) => { + return error_page + .replace(/%sveltekit\.status%/g, String(status)) + .replace(/%sveltekit\.error\.message%/g, message); + }; + + res.writeHead(500, { + 'Content-Type': 'text/html; charset=utf-8' + }); + res.end( + error_template({ status: 500, message: manifest_error.message ?? 'Invalid routes' }) + ); + + return; + } + + const rendered = await server.respond(request, { + getClientAddress: () => { + const { remoteAddress } = req.socket; + if (remoteAddress) return remoteAddress; + throw new Error('Could not determine clientAddress'); + }, + read: (file) => fs.readFileSync(path.join(svelte_config.kit.files.assets, file)), + before_handle: (event, config, prerender) => { + async_local_storage.enterWith({ event, config, prerender }); + }, + emulator + }); + + if (rendered.status === 404) { + // @ts-expect-error + serve_static_middleware.handle(req, res, () => { + setResponse(res, rendered); + }); + } else { + setResponse(res, rendered); + } + } catch (e) { + const error = coalesce_to_error(e); + res.statusCode = 500; + res.end(fix_stack_trace(error)); + } + }); + }; +} + +/** + * @param {import('connect').Server} server + */ +function remove_static_middlewares(server) { + const static_middlewares = ['viteServeStaticMiddleware', 'viteServePublicMiddleware']; + for (let i = server.stack.length - 1; i > 0; i--) { + // @ts-expect-error using internals + if (static_middlewares.includes(server.stack[i].handle.name)) { + server.stack.splice(i, 1); + } + } +} + +/** + * @param {import('vite').ViteDevServer} vite + * @param {import('vite').ModuleNode} node + * @param {Set} deps + */ +async function find_deps(vite, node, deps) { + // since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous. + // instead of using `await`, we resolve all branches in parallel. + /** @type {Promise[]} */ + const branches = []; + + /** @param {import('vite').ModuleNode} node */ + async function add(node) { + if (!deps.has(node)) { + deps.add(node); + await find_deps(vite, node, deps); + } + } + + /** @param {string} url */ + async function add_by_url(url) { + const node = await vite.moduleGraph.getModuleByUrl(url); + + if (node) { + await add(node); + } + } + + if (node.ssrTransformResult) { + if (node.ssrTransformResult.deps) { + node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url))); + } + + if (node.ssrTransformResult.dynamicDeps) { + node.ssrTransformResult.dynamicDeps.forEach((url) => branches.push(add_by_url(url))); + } + } else { + node.importedModules.forEach((node) => branches.push(add(node))); + } + + await Promise.all(branches); +} + +/** + * Determine if a file is being requested with the correct case, + * to ensure consistent behaviour between dev and prod and across + * operating systems. Note that we can't use realpath here, + * because we don't want to follow symlinks + * @param {string} file + * @param {string} assets + * @returns {boolean} + */ +function has_correct_case(file, assets) { + if (file === assets) return true; + + const parent = path.dirname(file); + + if (fs.readdirSync(parent).includes(path.basename(file))) { + return has_correct_case(parent, assets); + } + + return false; +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/index.js b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/index.js new file mode 100644 index 00000000..a58cc7a7 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/index.js @@ -0,0 +1,109 @@ +import path from 'node:path'; +import { posixify } from '../../../utils/filesystem.js'; +import { strip_virtual_prefix } from '../utils.js'; +import { app_server, env_dynamic_private, env_static_private } from '../module_ids.js'; + +const ILLEGAL_IMPORTS = new Set([env_dynamic_private, env_static_private, app_server]); +const ILLEGAL_MODULE_NAME_PATTERN = /.*\.server\..+/; + +/** + * Checks if given id imports a module that is not allowed to be imported into client-side code. + * @param {string} id + * @param {{ + * cwd: string; + * node_modules: string; + * server: string; + * }} dirs + */ +export function is_illegal(id, dirs) { + if (ILLEGAL_IMPORTS.has(id)) return true; + if (!id.startsWith(dirs.cwd) || id.startsWith(dirs.node_modules)) return false; + return ILLEGAL_MODULE_NAME_PATTERN.test(path.basename(id)) || id.startsWith(dirs.server); +} + +/** + * Creates a guard that checks that no id imports a module that is not allowed to be imported into client-side code. + * @param {import('vite').Rollup.PluginContext} context + * @param {{ cwd: string; lib: string }} paths + */ +export function module_guard(context, { cwd, lib }) { + /** @type {Set} */ + const seen = new Set(); + + const dirs = { + // ids will be posixified, so we need to posixify these, too + cwd: posixify(cwd), + node_modules: posixify(path.join(cwd, 'node_modules')), + server: posixify(path.join(lib, 'server')) + }; + + /** + * @param {string} id + * @param {Array<{ id: string; dynamic: boolean }>} chain + */ + function follow(id, chain) { + if (seen.has(id)) return; + seen.add(id); + + if (is_illegal(id, dirs)) { + chain.shift(); // discard the entry point + id = normalize_id(id, lib, cwd); + + const pyramid = + chain.map(({ id, dynamic }, i) => { + id = normalize_id(id, lib, cwd); + + return `${' '.repeat(i * 2)}- ${strip_virtual_prefix(id)} ${ + dynamic ? 'dynamically imports' : 'imports' + }\n`; + }) + `${' '.repeat(chain.length)}- ${strip_virtual_prefix(id)}`; + + const message = `Cannot import ${strip_virtual_prefix( + id + )} into client-side code:\n${pyramid}`; + + throw new Error(message); + } + + const module = context.getModuleInfo(id); + + if (module) { + for (const child of module.importedIds) { + follow(child, [...chain, { id, dynamic: false }]); + } + + for (const child of module.dynamicallyImportedIds) { + follow(child, [...chain, { id, dynamic: true }]); + } + } + } + + return { + /** @param {string} id should be posixified */ + check: (id) => { + follow(id, []); + } + }; +} + +/** + * Removes cwd/lib path from the start of the id + * @param {string} id + * @param {string} lib + * @param {string} cwd + */ +export function normalize_id(id, lib, cwd) { + if (id.startsWith(lib)) { + id = id.replace(lib, '$lib'); + } + + if (id.startsWith(cwd)) { + id = path.relative(cwd, id); + } + + if (id === app_server) { + return '$app/server'; + } + + return posixify(id); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/types.d.ts b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/types.d.ts new file mode 100644 index 00000000..1239fec4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/types.d.ts @@ -0,0 +1,5 @@ +export interface ImportGraph { + readonly id: string; + readonly dynamic: boolean; + readonly children: Generator; +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/utils.js b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/utils.js new file mode 100644 index 00000000..bdfa7a42 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/utils.js @@ -0,0 +1,6 @@ +const query_pattern = /\?.*$/s; + +/** @param {string} path */ +export function remove_query_from_id(path) { + return path.replace(query_pattern, ''); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/index.js b/node_modules/@sveltejs/kit/src/exports/vite/index.js new file mode 100644 index 00000000..06b1977c --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/index.js @@ -0,0 +1,989 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import process from 'node:process'; + +import colors from 'kleur'; + +import { copy, mkdirp, posixify, read, resolve_entry, rimraf } from '../../utils/filesystem.js'; +import { create_static_module, create_dynamic_module } from '../../core/env.js'; +import * as sync from '../../core/sync/sync.js'; +import { create_assets } from '../../core/sync/create_manifest_data/index.js'; +import { runtime_directory, logger } from '../../core/utils.js'; +import { load_config } from '../../core/config/index.js'; +import { generate_manifest } from '../../core/generate_manifest/index.js'; +import { build_server_nodes } from './build/build_server.js'; +import { build_service_worker } from './build/build_service_worker.js'; +import { assets_base, find_deps } from './build/utils.js'; +import { dev } from './dev/index.js'; +import { is_illegal, module_guard, normalize_id } from './graph_analysis/index.js'; +import { preview } from './preview/index.js'; +import { get_config_aliases, get_env, strip_virtual_prefix } from './utils.js'; +import { write_client_manifest } from '../../core/sync/write_client_manifest.js'; +import prerender from '../../core/postbuild/prerender.js'; +import analyse from '../../core/postbuild/analyse.js'; +import { s } from '../../utils/misc.js'; +import { hash } from '../../runtime/hash.js'; +import { dedent, isSvelte5Plus } from '../../core/sync/utils.js'; +import { + env_dynamic_private, + env_dynamic_public, + env_static_private, + env_static_public, + service_worker, + sveltekit_environment, + sveltekit_paths, + sveltekit_server +} from './module_ids.js'; +import { resolve_peer_dependency } from '../../utils/import.js'; + +const cwd = process.cwd(); + +/** @type {import('./types.js').EnforcedConfig} */ +const enforced_config = { + appType: true, + base: true, + build: { + cssCodeSplit: true, + emptyOutDir: true, + lib: { + entry: true, + name: true, + formats: true + }, + manifest: true, + outDir: true, + rollupOptions: { + input: true, + output: { + format: true, + entryFileNames: true, + chunkFileNames: true, + assetFileNames: true + }, + preserveEntrySignatures: true + }, + ssr: true + }, + publicDir: true, + resolve: { + alias: { + $app: true, + $lib: true, + '$service-worker': true + } + }, + root: true +}; + +const options_regex = /(export\s+const\s+(prerender|csr|ssr|trailingSlash))\s*=/s; + +/** @type {Set} */ +const warned = new Set(); + +/** @type {import('svelte/compiler').PreprocessorGroup} */ +const warning_preprocessor = { + script: ({ content, filename }) => { + if (!filename) return; + + const basename = path.basename(filename); + if (basename.startsWith('+page.') || basename.startsWith('+layout.')) { + const match = content.match(options_regex); + if (match) { + const fixed = basename.replace('.svelte', '(.server).js/ts'); + + const message = + `\n${colors.bold().red(path.relative('.', filename))}\n` + + `\`${match[1]}\` will be ignored — move it to ${fixed} instead. See https://kit.svelte.dev/docs/page-options for more information.`; + + if (!warned.has(message)) { + console.log(message); + warned.add(message); + } + } + } + }, + markup: ({ content, filename }) => { + if (!filename) return; + + const basename = path.basename(filename); + const has_children = + content.includes('\`${isSvelte5Plus() ? ' or `{@render ...}` tag' : ''}` + + ' missing — inner content will not be rendered'; + + if (!warned.has(message)) { + console.log(message); + warned.add(message); + } + } + } +}; + +/** + * Returns the SvelteKit Vite plugins. + * @returns {Promise} + */ +export async function sveltekit() { + const svelte_config = await load_config(); + + /** @type {import('@sveltejs/vite-plugin-svelte').Options['preprocess']} */ + let preprocess = svelte_config.preprocess; + if (Array.isArray(preprocess)) { + preprocess = [...preprocess, warning_preprocessor]; + } else if (preprocess) { + preprocess = [preprocess, warning_preprocessor]; + } else { + preprocess = warning_preprocessor; + } + + /** @type {import('@sveltejs/vite-plugin-svelte').Options} */ + const vite_plugin_svelte_options = { + configFile: false, + extensions: svelte_config.extensions, + preprocess, + onwarn: svelte_config.onwarn, + compilerOptions: { + hydratable: isSvelte5Plus() ? undefined : true, + ...svelte_config.compilerOptions + }, + ...svelte_config.vitePlugin + }; + + const { svelte } = await resolve_peer_dependency('@sveltejs/vite-plugin-svelte'); + + return [...svelte(vite_plugin_svelte_options), ...(await kit({ svelte_config }))]; +} + +// These variables live outside the `kit()` function because it is re-invoked by each Vite build + +let secondary_build_started = false; + +/** @type {import('types').ManifestData} */ +let manifest_data; + +/** + * Returns the SvelteKit Vite plugin. Vite executes Rollup hooks as well as some of its own. + * Background reading is available at: + * - https://vitejs.dev/guide/api-plugin.html + * - https://rollupjs.org/guide/en/#plugin-development + * + * You can get an idea of the lifecycle by looking at the flow charts here: + * - https://rollupjs.org/guide/en/#build-hooks + * - https://rollupjs.org/guide/en/#output-generation-hooks + * + * @param {{ svelte_config: import('types').ValidatedConfig }} options + * @return {Promise} + */ +async function kit({ svelte_config }) { + const vite = await resolve_peer_dependency('vite'); + + const { kit } = svelte_config; + const out = `${kit.outDir}/output`; + + const version_hash = hash(kit.version.name); + + /** @type {import('vite').ResolvedConfig} */ + let vite_config; + + /** @type {import('vite').ConfigEnv} */ + let vite_config_env; + + /** @type {boolean} */ + let is_build; + + /** @type {{ public: Record; private: Record }} */ + let env; + + /** @type {() => Promise} */ + let finalise; + + /** @type {import('vite').UserConfig} */ + let initial_config; + + const service_worker_entry_file = resolve_entry(kit.files.serviceWorker); + const parsed_service_worker = path.parse(kit.files.serviceWorker); + + /** + * A map showing which features (such as `$app/server:read`) are defined + * in which chunks, so that we can later determine which routes use which features + * @type {Record} + */ + const tracked_features = {}; + + const sourcemapIgnoreList = /** @param {string} relative_path */ (relative_path) => + relative_path.includes('node_modules') || relative_path.includes(kit.outDir); + + /** @type {import('vite').Plugin} */ + const plugin_setup = { + name: 'vite-plugin-sveltekit-setup', + + /** + * Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file. + * @see https://vitejs.dev/guide/api-plugin.html#config + */ + config(config, config_env) { + initial_config = config; + vite_config_env = config_env; + is_build = config_env.command === 'build'; + + env = get_env(kit.env, vite_config_env.mode); + + const allow = new Set([ + kit.files.lib, + kit.files.routes, + kit.outDir, + path.resolve('src'), // TODO this isn't correct if user changed all his files to sth else than src (like in test/options) + path.resolve('node_modules'), + path.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules') + ]); + + // We can only add directories to the allow list, so we find out + // if there's a client hooks file and pass its directory + const client_hooks = resolve_entry(kit.files.hooks.client); + if (client_hooks) allow.add(path.dirname(client_hooks)); + + const generated = path.posix.join(kit.outDir, 'generated'); + + // dev and preview config can be shared + /** @type {import('vite').UserConfig} */ + const new_config = { + resolve: { + alias: [ + { find: '__SERVER__', replacement: `${generated}/server` }, + { find: '$app', replacement: `${runtime_directory}/app` }, + ...get_config_aliases(kit) + ] + }, + root: cwd, + server: { + cors: { preflightContinue: true }, + fs: { + allow: [...allow] + }, + sourcemapIgnoreList, + watch: { + ignored: [ + // Ignore all siblings of config.kit.outDir/generated + `${posixify(kit.outDir)}/!(generated)` + ] + } + }, + preview: { + cors: { preflightContinue: true } + }, + optimizeDeps: { + entries: [ + `${kit.files.routes}/**/+*.{svelte,js,ts}`, + `!${kit.files.routes}/**/+*server.*` + ], + exclude: [ + '@sveltejs/kit', + // exclude kit features so that libraries using them work even when they are prebundled + // this does not affect app code, just handling of imported libraries that use $app or $env + '$app', + '$env' + ] + }, + ssr: { + noExternal: [ + // This ensures that esm-env is inlined into the server output with the + // export conditions resolved correctly through Vite. This prevents adapters + // that bundle later on from resolving the export conditions incorrectly + // and for example include browser-only code in the server output + // because they for example use esbuild.build with `platform: 'browser'` + 'esm-env', + // We need this for two reasons: + // 1. Without this, `@sveltejs/kit` imports are kept as-is in the server output, + // and that causes modules and therefore classes like `Redirect` to be imported twice + // under different IDs, which breaks a bunch of stuff because of failing instanceof checks. + // 2. Vitest bypasses Vite when loading external modules, so we bundle + // when it is detected to keep our virtual modules working. + // See https://github.com/sveltejs/kit/pull/9172 + // and https://vitest.dev/config/#deps-registernodeloader + '@sveltejs/kit' + ] + } + }; + + if (is_build) { + if (!new_config.build) new_config.build = {}; + new_config.build.ssr = !secondary_build_started; + + new_config.define = { + __SVELTEKIT_ADAPTER_NAME__: s(kit.adapter?.name), + __SVELTEKIT_APP_VERSION_FILE__: s(`${kit.appDir}/version.json`), + __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: s(kit.version.pollInterval), + __SVELTEKIT_DEV__: 'false', + __SVELTEKIT_EMBEDDED__: kit.embedded ? 'true' : 'false' + }; + + if (!secondary_build_started) { + manifest_data = sync.all(svelte_config, config_env.mode).manifest_data; + } + } else { + new_config.define = { + __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: '0', + __SVELTEKIT_DEV__: 'true', + __SVELTEKIT_EMBEDDED__: kit.embedded ? 'true' : 'false' + }; + + // These Kit dependencies are packaged as CommonJS, which means they must always be externalized. + // Without this, the tests will still pass but `pnpm dev` will fail in projects that link `@sveltejs/kit`. + /** @type {NonNullable} */ (new_config.ssr).external = [ + 'cookie', + 'set-cookie-parser' + ]; + } + + warn_overridden_config(config, new_config); + + return new_config; + }, + + /** + * Stores the final config. + */ + configResolved(config) { + vite_config = config; + } + }; + + /** @type {import('vite').Plugin} */ + const plugin_virtual_modules = { + name: 'vite-plugin-sveltekit-virtual-modules', + + resolveId(id, importer) { + // If importing from a service-worker, only allow $service-worker & $env/static/public, but none of the other virtual modules. + // This check won't catch transitive imports, but it will warn when the import comes from a service-worker directly. + // Transitive imports will be caught during the build. + if (importer) { + const parsed_importer = path.parse(importer); + + const importer_is_service_worker = + parsed_importer.dir === parsed_service_worker.dir && + parsed_importer.name === parsed_service_worker.name; + + if (importer_is_service_worker && id !== '$service-worker' && id !== '$env/static/public') { + throw new Error( + `Cannot import ${id} into service-worker code. Only the modules $service-worker and $env/static/public are available in service workers.` + ); + } + } + + // treat $env/static/[public|private] as virtual + if (id.startsWith('$env/') || id.startsWith('__sveltekit/') || id === '$service-worker') { + return `\0virtual:${id}`; + } + }, + + load(id, options) { + const browser = !options?.ssr; + + const global = is_build + ? `globalThis.__sveltekit_${version_hash}` + : 'globalThis.__sveltekit_dev'; + + if (options?.ssr === false && process.env.TEST !== 'true') { + const normalized_cwd = vite.normalizePath(cwd); + const normalized_lib = vite.normalizePath(kit.files.lib); + if ( + is_illegal(id, { + cwd: normalized_cwd, + node_modules: vite.normalizePath(path.resolve('node_modules')), + server: vite.normalizePath(path.join(normalized_lib, 'server')) + }) + ) { + const relative = normalize_id(id, normalized_lib, normalized_cwd); + throw new Error(`Cannot import ${strip_virtual_prefix(relative)} into client-side code`); + } + } + + switch (id) { + case env_static_private: + return create_static_module('$env/static/private', env.private); + + case env_static_public: + return create_static_module('$env/static/public', env.public); + + case env_dynamic_private: + return create_dynamic_module( + 'private', + vite_config_env.command === 'serve' ? env.private : undefined + ); + + case env_dynamic_public: + // populate `$env/dynamic/public` from `window` + if (browser) { + return `export const env = ${global}.env;`; + } + + return create_dynamic_module( + 'public', + vite_config_env.command === 'serve' ? env.public : undefined + ); + + case service_worker: + return create_service_worker_module(svelte_config); + + // for internal use only. it's published as $app/paths externally + // we use this alias so that we won't collide with user aliases + case sveltekit_paths: { + const { assets, base } = svelte_config.kit.paths; + + // use the values defined in `global`, but fall back to hard-coded values + // for the sake of things like Vitest which may import this module + // outside the context of a page + if (browser) { + return dedent` + export const base = ${global}?.base ?? ${s(base)}; + export const assets = ${global}?.assets ?? ${assets ? s(assets) : 'base'}; + `; + } + + return dedent` + export let base = ${s(base)}; + export let assets = ${assets ? s(assets) : 'base'}; + + export const relative = ${svelte_config.kit.paths.relative}; + + const initial = { base, assets }; + + export function override(paths) { + base = paths.base; + assets = paths.assets; + } + + export function reset() { + base = initial.base; + assets = initial.assets; + } + + /** @param {string} path */ + export function set_assets(path) { + assets = initial.assets = path; + } + `; + } + + case sveltekit_environment: { + const { version } = svelte_config.kit; + + return dedent` + export const version = ${s(version.name)}; + export let building = false; + export let prerendering = false; + + export function set_building() { + building = true; + } + + export function set_prerendering() { + prerendering = true; + } + `; + } + + case sveltekit_server: { + return dedent` + export let read_implementation = null; + + export let manifest = null; + + export function set_read_implementation(fn) { + read_implementation = fn; + } + + export function set_manifest(_) { + manifest = _; + } + `; + } + } + } + }; + + /** + * Ensures that client-side code can't accidentally import server-side code, + * whether in `*.server.js` files, `$app/server`, `$lib/server`, or `$env/[static|dynamic]/private` + * @type {import('vite').Plugin} + */ + const plugin_guard = { + name: 'vite-plugin-sveltekit-guard', + + writeBundle: { + sequential: true, + handler(_options) { + if (vite_config.build.ssr) return; + + const guard = module_guard(this, { + cwd: vite.normalizePath(process.cwd()), + lib: vite.normalizePath(kit.files.lib) + }); + + manifest_data.nodes.forEach((_node, i) => { + const id = vite.normalizePath( + path.resolve(kit.outDir, `generated/client-optimized/nodes/${i}.js`) + ); + + guard.check(id); + }); + } + } + }; + + /** @type {import('vite').Plugin} */ + const plugin_compile = { + name: 'vite-plugin-sveltekit-compile', + + /** + * Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file. + * @see https://vitejs.dev/guide/api-plugin.html#config + */ + config(config) { + /** @type {import('vite').UserConfig} */ + let new_config; + + if (is_build) { + const ssr = /** @type {boolean} */ (config.build?.ssr); + const prefix = `${kit.appDir}/immutable`; + + /** @type {Record} */ + const input = {}; + + if (ssr) { + input.index = `${runtime_directory}/server/index.js`; + input.internal = `${kit.outDir}/generated/server/internal.js`; + + // add entry points for every endpoint... + manifest_data.routes.forEach((route) => { + if (route.endpoint) { + const resolved = path.resolve(route.endpoint.file); + const relative = decodeURIComponent(path.relative(kit.files.routes, resolved)); + const name = posixify(path.join('entries/endpoints', relative.replace(/\.js$/, ''))); + input[name] = resolved; + } + }); + + // ...and every component used by pages... + manifest_data.nodes.forEach((node) => { + for (const file of [node.component, node.universal, node.server]) { + if (file) { + const resolved = path.resolve(file); + const relative = decodeURIComponent(path.relative(kit.files.routes, resolved)); + + const name = relative.startsWith('..') + ? posixify(path.join('entries/fallbacks', path.basename(file))) + : posixify(path.join('entries/pages', relative.replace(/\.js$/, ''))); + input[name] = resolved; + } + } + }); + + // ...and every matcher + Object.entries(manifest_data.matchers).forEach(([key, file]) => { + const name = posixify(path.join('entries/matchers', key)); + input[name] = path.resolve(file); + }); + } else { + input['entry/start'] = `${runtime_directory}/client/entry.js`; + input['entry/app'] = `${kit.outDir}/generated/client-optimized/app.js`; + + manifest_data.nodes.forEach((node, i) => { + if (node.component || node.universal) { + input[`nodes/${i}`] = `${kit.outDir}/generated/client-optimized/nodes/${i}.js`; + } + }); + } + + // see the kit.output.preloadStrategy option for details on why we have multiple options here + const ext = kit.output.preloadStrategy === 'preload-mjs' ? 'mjs' : 'js'; + + // We could always use a relative asset base path here, but it's better for performance not to. + // E.g. Vite generates `new URL('/asset.png', import.meta).href` for a relative path vs just '/asset.png'. + // That's larger and takes longer to run and also causes an HTML diff between SSR and client + // causing us to do a more expensive hydration check. + const client_base = + kit.paths.relative !== false || kit.paths.assets ? './' : kit.paths.base || '/'; + + new_config = { + base: ssr ? assets_base(kit) : client_base, + build: { + copyPublicDir: !ssr, + cssCodeSplit: true, + cssMinify: initial_config.build?.minify == null ? true : !!initial_config.build.minify, + // don't use the default name to avoid collisions with 'static/manifest.json' + manifest: '.vite/manifest.json', // TODO: remove this after bumping peer dep to vite 5 + outDir: `${out}/${ssr ? 'server' : 'client'}`, + rollupOptions: { + input, + output: { + format: 'esm', + entryFileNames: ssr ? '[name].js' : `${prefix}/[name].[hash].${ext}`, + chunkFileNames: ssr ? 'chunks/[name].js' : `${prefix}/chunks/[name].[hash].${ext}`, + assetFileNames: `${prefix}/assets/[name].[hash][extname]`, + hoistTransitiveImports: false, + sourcemapIgnoreList + }, + preserveEntrySignatures: 'strict' + }, + ssrEmitAssets: true, + target: ssr ? 'node18.13' : undefined + }, + publicDir: kit.files.assets, + worker: { + rollupOptions: { + output: { + entryFileNames: `${prefix}/workers/[name]-[hash].js`, + chunkFileNames: `${prefix}/workers/chunks/[name]-[hash].js`, + assetFileNames: `${prefix}/workers/assets/[name]-[hash][extname]`, + hoistTransitiveImports: false + } + } + } + }; + } else { + new_config = { + appType: 'custom', + base: kit.paths.base, + build: { + rollupOptions: { + // Vite dependency crawler needs an explicit JS entry point + // eventhough server otherwise works without it + input: `${runtime_directory}/client/entry.js` + } + }, + publicDir: kit.files.assets + }; + } + + warn_overridden_config(config, new_config); + + return new_config; + }, + + /** + * Adds the SvelteKit middleware to do SSR in dev mode. + * @see https://vitejs.dev/guide/api-plugin.html#configureserver + */ + async configureServer(vite) { + return await dev(vite, vite_config, svelte_config); + }, + + /** + * Adds the SvelteKit middleware to do SSR in preview mode. + * @see https://vitejs.dev/guide/api-plugin.html#configurepreviewserver + */ + configurePreviewServer(vite) { + return preview(vite, vite_config, svelte_config); + }, + + /** + * Clears the output directories. + */ + buildStart() { + if (secondary_build_started) return; + + if (is_build) { + if (!vite_config.build.watch) { + rimraf(out); + } + mkdirp(out); + } + }, + + renderChunk(code, chunk) { + if (code.includes('__SVELTEKIT_TRACK__')) { + return { + code: code.replace(/__SVELTEKIT_TRACK__\('(.+?)'\)/g, (_, label) => { + (tracked_features[chunk.name + '.js'] ??= []).push(label); + // put extra whitespace at the end of the comment to preserve the source size and avoid interfering with source maps + return `/* track ${label} */`; + }), + map: null // TODO we may need to generate a sourcemap in future + }; + } + }, + + generateBundle() { + if (vite_config.build.ssr) return; + + this.emitFile({ + type: 'asset', + fileName: `${kit.appDir}/version.json`, + source: s({ version: kit.version.name }) + }); + }, + + /** + * Vite builds a single bundle. We need three bundles: client, server, and service worker. + * The user's package.json scripts will invoke the Vite CLI to execute the server build. We + * then use this hook to kick off builds for the client and service worker. + */ + writeBundle: { + sequential: true, + async handler(_options) { + if (secondary_build_started) return; // only run this once + + const verbose = vite_config.logLevel === 'info'; + const log = logger({ verbose }); + + /** @type {import('vite').Manifest} */ + const server_manifest = JSON.parse(read(`${out}/server/${vite_config.build.manifest}`)); + + /** @type {import('types').BuildData} */ + const build_data = { + app_dir: kit.appDir, + app_path: `${kit.paths.base.slice(1)}${kit.paths.base ? '/' : ''}${kit.appDir}`, + manifest_data, + out_dir: out, + service_worker: service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable? + client: null, + server_manifest + }; + + const manifest_path = `${out}/server/manifest-full.js`; + fs.writeFileSync( + manifest_path, + `export const manifest = ${generate_manifest({ + build_data, + relative_path: '.', + routes: manifest_data.routes + })};\n` + ); + + // first, build server nodes without the client manifest so we can analyse it + log.info('Analysing routes'); + + build_server_nodes(out, kit, manifest_data, server_manifest, null, null); + + const metadata = await analyse({ + manifest_path, + manifest_data, + server_manifest, + tracked_features, + env: { ...env.private, ...env.public } + }); + + log.info('Building app'); + + // create client build + write_client_manifest( + kit, + manifest_data, + `${kit.outDir}/generated/client-optimized`, + metadata.nodes + ); + + secondary_build_started = true; + + const { output } = /** @type {import('vite').Rollup.RollupOutput} */ ( + await vite.build({ + configFile: vite_config.configFile, + // CLI args + mode: vite_config_env.mode, + logLevel: vite_config.logLevel, + clearScreen: vite_config.clearScreen, + build: { + minify: initial_config.build?.minify, + assetsInlineLimit: vite_config.build.assetsInlineLimit, + sourcemap: vite_config.build.sourcemap + }, + optimizeDeps: { + force: vite_config.optimizeDeps.force + } + }) + ); + + copy( + `${out}/server/${kit.appDir}/immutable/assets`, + `${out}/client/${kit.appDir}/immutable/assets` + ); + + /** @type {import('vite').Manifest} */ + const client_manifest = JSON.parse(read(`${out}/client/${vite_config.build.manifest}`)); + + const deps_of = /** @param {string} f */ (f) => + find_deps(client_manifest, posixify(path.relative('.', f)), false); + const start = deps_of(`${runtime_directory}/client/entry.js`); + const app = deps_of(`${kit.outDir}/generated/client-optimized/app.js`); + + build_data.client = { + start: start.file, + app: app.file, + imports: [...start.imports, ...app.imports], + stylesheets: [...start.stylesheets, ...app.stylesheets], + fonts: [...start.fonts, ...app.fonts], + uses_env_dynamic_public: output.some( + (chunk) => chunk.type === 'chunk' && chunk.modules[env_dynamic_public] + ) + }; + + const css = output.filter( + /** @type {(value: any) => value is import('vite').Rollup.OutputAsset} */ + (value) => value.type === 'asset' && value.fileName.endsWith('.css') + ); + + // regenerate manifest now that we have client entry... + fs.writeFileSync( + manifest_path, + `export const manifest = ${generate_manifest({ + build_data, + relative_path: '.', + routes: manifest_data.routes + })};\n` + ); + + // regenerate nodes with the client manifest... + build_server_nodes(out, kit, manifest_data, server_manifest, client_manifest, css); + + // ...and prerender + const { prerendered, prerender_map } = await prerender({ + out, + manifest_path, + metadata, + verbose, + env: { ...env.private, ...env.public } + }); + + // generate a new manifest that doesn't include prerendered pages + fs.writeFileSync( + `${out}/server/manifest.js`, + `export const manifest = ${generate_manifest({ + build_data, + relative_path: '.', + routes: manifest_data.routes.filter((route) => prerender_map.get(route.id) !== true) + })};\n` + ); + + if (service_worker_entry_file) { + if (kit.paths.assets) { + throw new Error('Cannot use service worker alongside config.kit.paths.assets'); + } + + log.info('Building service worker'); + + await build_service_worker( + out, + kit, + vite_config, + manifest_data, + service_worker_entry_file, + prerendered, + client_manifest + ); + } + + // we need to defer this to closeBundle, so that adapters copy files + // created by other Vite plugins + finalise = async () => { + console.log( + `\nRun ${colors + .bold() + .cyan('npm run preview')} to preview your production build locally.` + ); + + if (kit.adapter) { + const { adapt } = await import('../../core/adapt/index.js'); + await adapt( + svelte_config, + build_data, + metadata, + prerendered, + prerender_map, + log, + vite_config + ); + } else { + console.log(colors.bold().yellow('\nNo adapter specified')); + + const link = colors.bold().cyan('https://kit.svelte.dev/docs/adapters'); + console.log( + `See ${link} to learn how to configure your app to run on the platform of your choosing` + ); + } + + secondary_build_started = false; + }; + } + }, + + /** + * Runs the adapter. + */ + closeBundle: { + sequential: true, + async handler() { + if (!vite_config.build.ssr) return; + await finalise?.(); + } + } + }; + + return [plugin_setup, plugin_virtual_modules, plugin_guard, plugin_compile]; +} + +/** + * @param {Record} config + * @param {Record} resolved_config + */ +function warn_overridden_config(config, resolved_config) { + const overridden = find_overridden_config(config, resolved_config, enforced_config, '', []); + + if (overridden.length > 0) { + console.error( + colors.bold().red('The following Vite config options will be overridden by SvelteKit:') + + overridden.map((key) => `\n - ${key}`).join('') + ); + } +} + +/** + * @param {Record} config + * @param {Record} resolved_config + * @param {import('./types.js').EnforcedConfig} enforced_config + * @param {string} path + * @param {string[]} out used locally to compute the return value + */ +function find_overridden_config(config, resolved_config, enforced_config, path, out) { + if (config == null || resolved_config == null) { + return out; + } + + for (const key in enforced_config) { + if (typeof config === 'object' && key in config && key in resolved_config) { + const enforced = enforced_config[key]; + + if (enforced === true) { + if (config[key] !== resolved_config[key]) { + out.push(path + key); + } + } else { + find_overridden_config(config[key], resolved_config[key], enforced, path + key + '.', out); + } + } + } + return out; +} + +/** + * @param {import('types').ValidatedConfig} config + */ +const create_service_worker_module = (config) => dedent` + if (typeof self === 'undefined' || self instanceof ServiceWorkerGlobalScope === false) { + throw new Error('This module can only be imported inside a service worker'); + } + + export const build = []; + export const files = [ + ${create_assets(config) + .filter((asset) => config.kit.serviceWorker.files(asset.file)) + .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`) + .join(',\n')} + ]; + export const prerendered = []; + export const version = ${s(config.kit.version.name)}; +`; diff --git a/node_modules/@sveltejs/kit/src/exports/vite/module_ids.js b/node_modules/@sveltejs/kit/src/exports/vite/module_ids.js new file mode 100644 index 00000000..3be16f68 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/module_ids.js @@ -0,0 +1,16 @@ +import { fileURLToPath } from 'node:url'; + +export const env_static_private = '\0virtual:$env/static/private'; +export const env_static_public = '\0virtual:$env/static/public'; +export const env_dynamic_private = '\0virtual:$env/dynamic/private'; +export const env_dynamic_public = '\0virtual:$env/dynamic/public'; + +export const service_worker = '\0virtual:$service-worker'; + +export const sveltekit_environment = '\0virtual:__sveltekit/environment'; +export const sveltekit_paths = '\0virtual:__sveltekit/paths'; +export const sveltekit_server = '\0virtual:__sveltekit/server'; + +export const app_server = fileURLToPath( + new URL('../../runtime/app/server/index.js', import.meta.url) +); diff --git a/node_modules/@sveltejs/kit/src/exports/vite/preview/index.js b/node_modules/@sveltejs/kit/src/exports/vite/preview/index.js new file mode 100644 index 00000000..1e70d405 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/preview/index.js @@ -0,0 +1,241 @@ +import fs from 'node:fs'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { lookup } from 'mrmime'; +import sirv from 'sirv'; +import { loadEnv, normalizePath } from 'vite'; +import { createReadableStream, getRequest, setResponse } from '../../../exports/node/index.js'; +import { installPolyfills } from '../../../exports/node/polyfills.js'; +import { SVELTE_KIT_ASSETS } from '../../../constants.js'; +import { not_found } from '../utils.js'; + +/** @typedef {import('http').IncomingMessage} Req */ +/** @typedef {import('http').ServerResponse} Res */ +/** @typedef {(req: Req, res: Res, next: () => void) => void} Handler */ + +/** + * @param {{ middlewares: import('connect').Server }} vite + * @param {import('vite').ResolvedConfig} vite_config + * @param {import('types').ValidatedConfig} svelte_config + */ +export async function preview(vite, vite_config, svelte_config) { + installPolyfills(); + + const { paths } = svelte_config.kit; + const base = paths.base; + const assets = paths.assets ? SVELTE_KIT_ASSETS : paths.base; + + const protocol = vite_config.preview.https ? 'https' : 'http'; + + const etag = `"${Date.now()}"`; + + const dir = join(svelte_config.kit.outDir, 'output/server'); + + if (!fs.existsSync(dir)) { + throw new Error(`Server files not found at ${dir}, did you run \`build\` first?`); + } + + /** @type {import('types').ServerInternalModule} */ + const { set_assets } = await import(pathToFileURL(join(dir, 'internal.js')).href); + + /** @type {import('types').ServerModule} */ + const { Server } = await import(pathToFileURL(join(dir, 'index.js')).href); + + const { manifest } = await import(pathToFileURL(join(dir, 'manifest.js')).href); + + set_assets(assets); + + const server = new Server(manifest); + await server.init({ + env: loadEnv(vite_config.mode, svelte_config.kit.env.dir, ''), + read: (file) => createReadableStream(`${dir}/${file}`) + }); + + const emulator = await svelte_config.kit.adapter?.emulate?.(); + + return () => { + // Remove the base middleware. It screws with the URL. + // It also only lets through requests beginning with the base path, so that requests beginning + // with the assets URL never reach us. We could serve assets separately before the base + // middleware, but we'd need that to occur after the compression and cors middlewares, so would + // need to insert it manually into the stack, which would be at least as bad as doing this. + for (let i = vite.middlewares.stack.length - 1; i > 0; i--) { + // @ts-expect-error using internals + if (vite.middlewares.stack[i].handle.name === 'viteBaseMiddleware') { + vite.middlewares.stack.splice(i, 1); + } + } + + // generated client assets and the contents of `static` + vite.middlewares.use( + scoped( + assets, + sirv(join(svelte_config.kit.outDir, 'output/client'), { + setHeaders: (res, pathname) => { + // only apply to immutable directory, not e.g. version.json + if (pathname.startsWith(`/${svelte_config.kit.appDir}/immutable`)) { + res.setHeader('cache-control', 'public,max-age=31536000,immutable'); + } + } + }) + ) + ); + + vite.middlewares.use((req, res, next) => { + const original_url = /** @type {string} */ (req.url); + const { pathname, search } = new URL(original_url, 'http://dummy'); + + // if `paths.base === '/a/b/c`, then the root route is `/a/b/c/`, + // regardless of the `trailingSlash` route option + if (base.length > 1 && pathname === base) { + let location = base + '/'; + if (search) location += search; + res.writeHead(307, { + location + }); + res.end(); + return; + } + + if (pathname.startsWith(base)) { + next(); + } else { + res.statusCode = 404; + not_found(req, res, base); + } + }); + + // prerendered dependencies + vite.middlewares.use( + scoped(base, mutable(join(svelte_config.kit.outDir, 'output/prerendered/dependencies'))) + ); + + // prerendered pages (we can't just use sirv because we need to + // preserve the correct trailingSlash behaviour) + vite.middlewares.use( + scoped(base, (req, res, next) => { + let if_none_match_value = req.headers['if-none-match']; + + if (if_none_match_value?.startsWith('W/"')) { + if_none_match_value = if_none_match_value.substring(2); + } + + if (if_none_match_value === etag) { + res.statusCode = 304; + res.end(); + return; + } + + const { pathname, search } = new URL(/** @type {string} */ (req.url), 'http://dummy'); + + let filename = normalizePath( + join(svelte_config.kit.outDir, 'output/prerendered/pages' + pathname) + ); + let prerendered = is_file(filename); + + if (!prerendered) { + const has_trailing_slash = pathname.endsWith('/'); + const html_filename = `${filename}${has_trailing_slash ? 'index.html' : '.html'}`; + + /** @type {string | undefined} */ + let redirect; + + if (is_file(html_filename)) { + filename = html_filename; + prerendered = true; + } else if (has_trailing_slash) { + if (is_file(filename.slice(0, -1) + '.html')) { + redirect = pathname.slice(0, -1); + } + } else if (is_file(filename + '/index.html')) { + redirect = pathname + '/'; + } + + if (redirect) { + if (search) redirect += search; + res.writeHead(307, { + location: redirect + }); + + res.end(); + + return; + } + } + + if (prerendered) { + res.writeHead(200, { + 'content-type': lookup(pathname) || 'text/html', + etag + }); + + fs.createReadStream(filename).pipe(res); + } else { + next(); + } + }) + ); + + // SSR + vite.middlewares.use(async (req, res) => { + const host = req.headers['host']; + + const request = await getRequest({ + base: `${protocol}://${host}`, + request: req + }); + + setResponse( + res, + await server.respond(request, { + getClientAddress: () => { + const { remoteAddress } = req.socket; + if (remoteAddress) return remoteAddress; + throw new Error('Could not determine clientAddress'); + }, + read: (file) => fs.readFileSync(join(svelte_config.kit.files.assets, file)), + emulator + }) + ); + }); + }; +} + +/** + * @param {string} dir + * @returns {Handler} + */ +const mutable = (dir) => + fs.existsSync(dir) + ? sirv(dir, { + etag: true, + maxAge: 0 + }) + : (_req, _res, next) => next(); + +/** + * @param {string} scope + * @param {Handler} handler + * @returns {Handler} + */ +function scoped(scope, handler) { + if (scope === '') return handler; + + return (req, res, next) => { + if (req.url?.startsWith(scope)) { + const original_url = req.url; + req.url = req.url.slice(scope.length); + handler(req, res, () => { + req.url = original_url; + next(); + }); + } else { + next(); + } + }; +} + +/** @param {string} path */ +function is_file(path) { + return fs.existsSync(path) && !fs.statSync(path).isDirectory(); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/types.d.ts b/node_modules/@sveltejs/kit/src/exports/vite/types.d.ts new file mode 100644 index 00000000..900aa435 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/types.d.ts @@ -0,0 +1,3 @@ +export interface EnforcedConfig { + [key: string]: EnforcedConfig | true; +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/utils.js b/node_modules/@sveltejs/kit/src/exports/vite/utils.js new file mode 100644 index 00000000..aaa33971 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/utils.js @@ -0,0 +1,101 @@ +import path from 'node:path'; +import { loadEnv } from 'vite'; +import { posixify } from '../../utils/filesystem.js'; +import { negotiate } from '../../utils/http.js'; +import { filter_private_env, filter_public_env } from '../../utils/env.js'; + +/** + * Transforms kit.alias to a valid vite.resolve.alias array. + * + * Related to tsconfig path alias creation. + * + * @param {import('types').ValidatedKitConfig} config + * */ +export function get_config_aliases(config) { + /** @type {import('vite').Alias[]} */ + const alias = [ + // For now, we handle `$lib` specially here rather than make it a default value for + // `config.kit.alias` since it has special meaning for packaging, etc. + { find: '$lib', replacement: config.files.lib } + ]; + + for (let [key, value] of Object.entries(config.alias)) { + value = posixify(value); + if (value.endsWith('/*')) { + value = value.slice(0, -2); + } + if (key.endsWith('/*')) { + // Doing just `{ find: key.slice(0, -2) ,..}` would mean `import .. from "key"` would also be matched, which we don't want + alias.push({ + find: new RegExp(`^${escape_for_regexp(key.slice(0, -2))}\\/(.+)$`), + replacement: `${path.resolve(value)}/$1` + }); + } else if (key + '/*' in config.alias) { + // key and key/* both exist -> the replacement for key needs to happen _only_ on import .. from "key" + alias.push({ + find: new RegExp(`^${escape_for_regexp(key)}$`), + replacement: path.resolve(value) + }); + } else { + alias.push({ find: key, replacement: path.resolve(value) }); + } + } + + return alias; +} + +/** + * @param {string} str + */ +function escape_for_regexp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, (match) => '\\' + match); +} + +/** + * Load environment variables from process.env and .env files + * @param {import('types').ValidatedKitConfig['env']} env_config + * @param {string} mode + */ +export function get_env(env_config, mode) { + const { publicPrefix: public_prefix, privatePrefix: private_prefix } = env_config; + const env = loadEnv(mode, env_config.dir, ''); + + return { + public: filter_public_env(env, { public_prefix, private_prefix }), + private: filter_private_env(env, { public_prefix, private_prefix }) + }; +} + +/** + * @param {import('http').IncomingMessage} req + * @param {import('http').ServerResponse} res + * @param {string} base + */ +export function not_found(req, res, base) { + const type = negotiate(req.headers.accept ?? '*', ['text/plain', 'text/html']); + + // special case — handle `/` request automatically + if (req.url === '/' && type === 'text/html') { + res.statusCode = 307; + res.setHeader('location', base); + res.end(); + return; + } + + res.statusCode = 404; + + const prefixed = base + req.url; + + if (type === 'text/html') { + res.setHeader('Content-Type', 'text/html'); + res.end( + `The server is configured with a public base URL of ${base} - did you mean to visit ${prefixed} instead?` + ); + } else { + res.end( + `The server is configured with a public base URL of ${base} - did you mean to visit ${prefixed} instead?` + ); + } +} + +export const strip_virtual_prefix = /** @param {string} id */ (id) => id.replace('\0virtual:', ''); diff --git a/node_modules/@sveltejs/kit/src/runtime/app/environment/index.js b/node_modules/@sveltejs/kit/src/runtime/app/environment/index.js new file mode 100644 index 00000000..2b546194 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/environment/index.js @@ -0,0 +1,6 @@ +import { BROWSER, DEV } from 'esm-env'; +export { building, version } from '__sveltekit/environment'; + +export const browser = BROWSER; + +export const dev = DEV; diff --git a/node_modules/@sveltejs/kit/src/runtime/app/environment/types.d.ts b/node_modules/@sveltejs/kit/src/runtime/app/environment/types.d.ts new file mode 100644 index 00000000..da76eae4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/environment/types.d.ts @@ -0,0 +1,19 @@ +/** + * `true` if the app is running in the browser. + */ +export const browser: boolean; + +/** + * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. + */ +export const dev: boolean; + +/** + * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. + */ +export const building: boolean; + +/** + * The value of `config.kit.version.name`. + */ +export const version: string; diff --git a/node_modules/@sveltejs/kit/src/runtime/app/forms.js b/node_modules/@sveltejs/kit/src/runtime/app/forms.js new file mode 100644 index 00000000..bdb4f0fa --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/forms.js @@ -0,0 +1,228 @@ +import * as devalue from 'devalue'; +import { DEV } from 'esm-env'; +import { invalidateAll } from './navigation.js'; +import { applyAction } from '../client/client.js'; + +export { applyAction }; + +/** + * Use this function to deserialize the response from a form submission. + * Usage: + * + * ```js + * import { deserialize } from '$app/forms'; + * + * async function handleSubmit(event) { + * const response = await fetch('/form?/action', { + * method: 'POST', + * body: new FormData(event.target) + * }); + * + * const result = deserialize(await response.text()); + * // ... + * } + * ``` + * @template {Record | undefined} Success + * @template {Record | undefined} Failure + * @param {string} result + * @returns {import('@sveltejs/kit').ActionResult} + */ +export function deserialize(result) { + const parsed = JSON.parse(result); + if (parsed.data) { + parsed.data = devalue.parse(parsed.data); + } + return parsed; +} + +/** + * Shallow clone an element, so that we can access e.g. `form.action` without worrying + * that someone has added an `` (https://github.com/sveltejs/kit/issues/7593) + * @template {HTMLElement} T + * @param {T} element + * @returns {T} + */ +function clone(element) { + return /** @type {T} */ (HTMLElement.prototype.cloneNode.call(element)); +} + +/** + * This action enhances a `` element that otherwise would work without JavaScript. + * + * The `submit` function is called upon submission with the given FormData and the `action` that should be triggered. + * If `cancel` is called, the form will not be submitted. + * You can use the abort `controller` to cancel the submission in case another one starts. + * If a function is returned, that function is called with the response from the server. + * If nothing is returned, the fallback will be used. + * + * If this function or its return value isn't set, it + * - falls back to updating the `form` prop with the returned data if the action is on the same page as the form + * - updates `$page.status` + * - resets the `` element and invalidates all data in case of successful submission with no redirect response + * - redirects in case of a redirect response + * - redirects to the nearest error page in case of an unexpected error + * + * If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. + * @template {Record | undefined} Success + * @template {Record | undefined} Failure + * @param {HTMLFormElement} form_element The form element + * @param {import('@sveltejs/kit').SubmitFunction} submit Submit callback + */ +export function enhance(form_element, submit = () => {}) { + if (DEV && clone(form_element).method !== 'post') { + throw new Error('use:enhance can only be used on fields with method="POST"'); + } + + /** + * @param {{ + * action: URL; + * invalidateAll?: boolean; + * result: import('@sveltejs/kit').ActionResult; + * reset?: boolean + * }} opts + */ + const fallback_callback = async ({ + action, + result, + reset = true, + invalidateAll: shouldInvalidateAll = true + }) => { + if (result.type === 'success') { + if (reset) { + // We call reset from the prototype to avoid DOM clobbering + HTMLFormElement.prototype.reset.call(form_element); + } + if (shouldInvalidateAll) { + await invalidateAll(); + } + } + + // For success/failure results, only apply action if it belongs to the + // current page, otherwise `form` will be updated erroneously + if ( + location.origin + location.pathname === action.origin + action.pathname || + result.type === 'redirect' || + result.type === 'error' + ) { + applyAction(result); + } + }; + + /** @param {SubmitEvent} event */ + async function handle_submit(event) { + const method = event.submitter?.hasAttribute('formmethod') + ? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formMethod + : clone(form_element).method; + if (method !== 'post') return; + + event.preventDefault(); + + const action = new URL( + // We can't do submitter.formAction directly because that property is always set + event.submitter?.hasAttribute('formaction') + ? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formAction + : clone(form_element).action + ); + + const enctype = event.submitter?.hasAttribute('formenctype') + ? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formEnctype + : clone(form_element).enctype; + + const form_data = new FormData(form_element); + + if (DEV && enctype !== 'multipart/form-data') { + for (const value of form_data.values()) { + if (value instanceof File) { + throw new Error( + 'Your form contains fields, but is missing the necessary `enctype="multipart/form-data"` attribute. This will lead to inconsistent behavior between enhanced and native forms. For more details, see https://github.com/sveltejs/kit/issues/9819.' + ); + } + } + } + + const submitter_name = event.submitter?.getAttribute('name'); + if (submitter_name) { + form_data.append(submitter_name, event.submitter?.getAttribute('value') ?? ''); + } + + const controller = new AbortController(); + + let cancelled = false; + const cancel = () => (cancelled = true); + + const callback = + (await submit({ + action, + cancel, + controller, + formData: form_data, + formElement: form_element, + submitter: event.submitter + })) ?? fallback_callback; + if (cancelled) return; + + /** @type {import('@sveltejs/kit').ActionResult} */ + let result; + + try { + const headers = new Headers({ + accept: 'application/json', + 'x-sveltekit-action': 'true' + }); + + // do not explicitly set the `Content-Type` header when sending `FormData` + // or else it will interfere with the browser's header setting + // see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects#sect4 + if (enctype !== 'multipart/form-data') { + headers.set( + 'Content-Type', + /^(:?application\/x-www-form-urlencoded|text\/plain)$/.test(enctype) + ? enctype + : 'application/x-www-form-urlencoded' + ); + } + + // @ts-expect-error `URLSearchParams(form_data)` is kosher, but typescript doesn't know that + const body = enctype === 'multipart/form-data' ? form_data : new URLSearchParams(form_data); + + const response = await fetch(action, { + method: 'POST', + headers, + cache: 'no-store', + body, + signal: controller.signal + }); + + result = deserialize(await response.text()); + if (result.type === 'error') result.status = response.status; + } catch (error) { + if (/** @type {any} */ (error)?.name === 'AbortError') return; + result = { type: 'error', error }; + } + + callback({ + action, + formData: form_data, + formElement: form_element, + update: (opts) => + fallback_callback({ + action, + result, + reset: opts?.reset, + invalidateAll: opts?.invalidateAll + }), + // @ts-expect-error generic constraints stuff we don't care about + result + }); + } + + // @ts-expect-error + HTMLFormElement.prototype.addEventListener.call(form_element, 'submit', handle_submit); + + return { + destroy() { + // @ts-expect-error + HTMLFormElement.prototype.removeEventListener.call(form_element, 'submit', handle_submit); + } + }; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/app/navigation.js b/node_modules/@sveltejs/kit/src/runtime/app/navigation.js new file mode 100644 index 00000000..ca3f95dd --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/navigation.js @@ -0,0 +1,13 @@ +export { + afterNavigate, + beforeNavigate, + disableScrollHandling, + goto, + invalidate, + invalidateAll, + onNavigate, + preloadCode, + preloadData, + pushState, + replaceState +} from '../client/client.js'; diff --git a/node_modules/@sveltejs/kit/src/runtime/app/paths/index.js b/node_modules/@sveltejs/kit/src/runtime/app/paths/index.js new file mode 100644 index 00000000..5a150fbf --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/paths/index.js @@ -0,0 +1,8 @@ +export { base, assets } from '__sveltekit/paths'; +import { base } from '__sveltekit/paths'; +import { resolve_route } from '../../../utils/routing.js'; + +/** @type {import('./types.d.ts').resolveRoute} */ +export function resolveRoute(id, params) { + return base + resolve_route(id, params); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/app/paths/types.d.ts b/node_modules/@sveltejs/kit/src/runtime/app/paths/types.d.ts new file mode 100644 index 00000000..0bc521a9 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/paths/types.d.ts @@ -0,0 +1,28 @@ +/** + * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). + * + * Example usage: `Link` + */ +export let base: '' | `/${string}`; + +/** + * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/configuration#paths). + * + * > If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL. + */ +export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; + +/** + * Populate a route ID with params to resolve a pathname. + * @example + * ```js + * resolveRoute( + * `/blog/[slug]/[...somethingElse]`, + * { + * slug: 'hello-world', + * somethingElse: 'something/else' + * } + * ); // `/blog/hello-world/something/else` + * ``` + */ +export function resolveRoute(id: string, params: Record): string; diff --git a/node_modules/@sveltejs/kit/src/runtime/app/server/index.js b/node_modules/@sveltejs/kit/src/runtime/app/server/index.js new file mode 100644 index 00000000..33c9b0a0 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/server/index.js @@ -0,0 +1,73 @@ +import { read_implementation, manifest } from '__sveltekit/server'; +import { base } from '__sveltekit/paths'; +import { DEV } from 'esm-env'; +import { b64_decode } from '../../utils.js'; + +/** + * Read the contents of an imported asset from the filesystem + * @example + * ```js + * import { read } from '$app/server'; + * import somefile from './somefile.txt'; + * + * const asset = read(somefile); + * const text = await asset.text(); + * ``` + * @param {string} asset + * @returns {Response} + * @since 2.4.0 + */ +export function read(asset) { + __SVELTEKIT_TRACK__('$app/server:read'); + + if (!read_implementation) { + throw new Error( + 'No `read` implementation was provided. Please ensure that your adapter is up to date and supports this feature' + ); + } + + // handle inline assets internally + const match = /^data:([^;,]+)?(;base64)?,/.exec(asset); + if (match) { + const type = match[1] ?? 'application/octet-stream'; + const data = asset.slice(match[0].length); + + if (match[2] !== undefined) { + const decoded = b64_decode(data); + + return new Response(decoded, { + headers: { + 'Content-Length': decoded.byteLength.toString(), + 'Content-Type': type + } + }); + } + + const decoded = decodeURIComponent(data); + + return new Response(decoded, { + headers: { + 'Content-Length': decoded.length.toString(), + 'Content-Type': type + } + }); + } + + const file = decodeURIComponent( + DEV && asset.startsWith('/@fs') ? asset : asset.slice(base.length + 1) + ); + + if (file in manifest._.server_assets) { + const length = manifest._.server_assets[file]; + const type = manifest.mimeTypes[file.slice(file.lastIndexOf('.'))]; + + return new Response(read_implementation(file), { + headers: { + 'Content-Length': '' + length, + 'Content-Type': type + } + }); + } + + throw new Error(`Asset does not exist: ${file}`); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/app/stores.js b/node_modules/@sveltejs/kit/src/runtime/app/stores.js new file mode 100644 index 00000000..554d653c --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/stores.js @@ -0,0 +1,94 @@ +import { getContext } from 'svelte'; +import { BROWSER } from 'esm-env'; +import { stores as browser_stores } from '../client/client.js'; + +/** + * A function that returns all of the contextual stores. On the server, this must be called during component initialization. + * Only use this if you need to defer store subscription until after the component has mounted, for some reason. + */ +export const getStores = () => { + const stores = BROWSER ? browser_stores : getContext('__svelte__'); + + return { + /** @type {typeof page} */ + page: { + subscribe: stores.page.subscribe + }, + /** @type {typeof navigating} */ + navigating: { + subscribe: stores.navigating.subscribe + }, + /** @type {typeof updated} */ + updated: stores.updated + }; +}; + +/** + * A readable store whose value contains page data. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * + * @type {import('svelte/store').Readable} + */ +export const page = { + subscribe(fn) { + const store = __SVELTEKIT_DEV__ ? get_store('page') : getStores().page; + return store.subscribe(fn); + } +}; + +/** + * A readable store. + * When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. + * When navigating finishes, its value reverts to `null`. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * @type {import('svelte/store').Readable} + */ +export const navigating = { + subscribe(fn) { + const store = __SVELTEKIT_DEV__ ? get_store('navigating') : getStores().navigating; + return store.subscribe(fn); + } +}; + +/** + * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * @type {import('svelte/store').Readable & { check(): Promise }} + */ +export const updated = { + subscribe(fn) { + const store = __SVELTEKIT_DEV__ ? get_store('updated') : getStores().updated; + + if (BROWSER) { + updated.check = store.check; + } + + return store.subscribe(fn); + }, + check: () => { + throw new Error( + BROWSER + ? 'Cannot check updated store before subscribing' + : 'Can only check updated store in browser' + ); + } +}; + +/** + * @template {keyof ReturnType} Name + * @param {Name} name + * @returns {ReturnType[Name]} + */ +function get_store(name) { + try { + return getStores()[name]; + } catch { + throw new Error( + `Cannot subscribe to '${name}' store on the server outside of a Svelte component, as it is bound to the current request via component context. This prevents state from leaking between users.` + + 'For more information, see https://kit.svelte.dev/docs/state-management#avoid-shared-state-on-the-server' + ); + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/client.js b/node_modules/@sveltejs/kit/src/runtime/client/client.js new file mode 100644 index 00000000..cd5288db --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/client.js @@ -0,0 +1,2665 @@ +import { BROWSER, DEV } from 'esm-env'; +import { onMount, tick } from 'svelte'; +import { + add_data_suffix, + decode_params, + decode_pathname, + strip_hash, + make_trackable, + normalize_path +} from '../../utils/url.js'; +import { + initial_fetch, + lock_fetch, + native_fetch, + subsequent_fetch, + unlock_fetch +} from './fetcher.js'; +import { parse } from './parse.js'; +import * as storage from './session-storage.js'; +import { + find_anchor, + resolve_url, + get_link_info, + get_router_options, + is_external_url, + origin, + scroll_state, + notifiable_store, + create_updated_store +} from './utils.js'; +import { base } from '__sveltekit/paths'; +import * as devalue from 'devalue'; +import { + HISTORY_INDEX, + NAVIGATION_INDEX, + PRELOAD_PRIORITIES, + SCROLL_KEY, + STATES_KEY, + SNAPSHOT_KEY, + PAGE_URL_KEY +} from './constants.js'; +import { validate_page_exports } from '../../utils/exports.js'; +import { compact } from '../../utils/array.js'; +import { HttpError, Redirect, SvelteKitError } from '../control.js'; +import { INVALIDATED_PARAM, TRAILING_SLASH_PARAM, validate_depends } from '../shared.js'; +import { get_message, get_status } from '../../utils/error.js'; +import { writable } from 'svelte/store'; + +let errored = false; + +// We track the scroll position associated with each history entry in sessionStorage, +// rather than on history.state itself, because when navigation is driven by +// popstate it's too late to update the scroll position associated with the +// state we're navigating from +/** + * history index -> { x, y } + * @type {Record} + */ +const scroll_positions = storage.get(SCROLL_KEY) ?? {}; + +/** + * navigation index -> any + * @type {Record} + */ +const snapshots = storage.get(SNAPSHOT_KEY) ?? {}; + +if (DEV && BROWSER) { + let warned = false; + + const current_module_url = import.meta.url.split('?')[0]; // remove query params that vite adds to the URL when it is loaded from node_modules + + const warn = () => { + if (warned) return; + + // Rather than saving a pointer to the original history methods, which would prevent monkeypatching by other libs, + // inspect the stack trace to see if we're being called from within SvelteKit. + let stack = new Error().stack?.split('\n'); + if (!stack) return; + if (!stack[0].includes('https:') && !stack[0].includes('http:')) stack = stack.slice(1); // Chrome includes the error message in the stack + stack = stack.slice(2); // remove `warn` and the place where `warn` was called + // Can be falsy if was called directly from an anonymous function + if (stack[0]?.includes(current_module_url)) return; + + warned = true; + + console.warn( + "Avoid using `history.pushState(...)` and `history.replaceState(...)` as these will conflict with SvelteKit's router. Use the `pushState` and `replaceState` imports from `$app/navigation` instead." + ); + }; + + const push_state = history.pushState; + history.pushState = (...args) => { + warn(); + return push_state.apply(history, args); + }; + + const replace_state = history.replaceState; + history.replaceState = (...args) => { + warn(); + return replace_state.apply(history, args); + }; +} + +export const stores = { + url: /* @__PURE__ */ notifiable_store({}), + page: /* @__PURE__ */ notifiable_store({}), + navigating: /* @__PURE__ */ writable( + /** @type {import('@sveltejs/kit').Navigation | null} */ (null) + ), + updated: /* @__PURE__ */ create_updated_store() +}; + +/** @param {number} index */ +function update_scroll_positions(index) { + scroll_positions[index] = scroll_state(); +} + +/** + * @param {number} current_history_index + * @param {number} current_navigation_index + */ +function clear_onward_history(current_history_index, current_navigation_index) { + // if we navigated back, then pushed a new state, we can + // release memory by pruning the scroll/snapshot lookup + let i = current_history_index + 1; + while (scroll_positions[i]) { + delete scroll_positions[i]; + i += 1; + } + + i = current_navigation_index + 1; + while (snapshots[i]) { + delete snapshots[i]; + i += 1; + } +} + +/** + * Loads `href` the old-fashioned way, with a full page reload. + * Returns a `Promise` that never resolves (to prevent any + * subsequent work, e.g. history manipulation, from happening) + * @param {URL} url + */ +function native_navigation(url) { + location.href = url.href; + return new Promise(() => {}); +} + +function noop() {} + +/** @type {import('types').CSRRoute[]} */ +let routes; +/** @type {import('types').CSRPageNodeLoader} */ +let default_layout_loader; +/** @type {import('types').CSRPageNodeLoader} */ +let default_error_loader; +/** @type {HTMLElement} */ +let container; +/** @type {HTMLElement} */ +let target; +/** @type {import('./types.js').SvelteKitApp} */ +let app; + +/** @type {Array<((url: URL) => boolean)>} */ +const invalidated = []; + +/** + * An array of the `+layout.svelte` and `+page.svelte` component instances + * that currently live on the page — used for capturing and restoring snapshots. + * It's updated/manipulated through `bind:this` in `Root.svelte`. + * @type {import('svelte').SvelteComponent[]} + */ +const components = []; + +/** @type {{id: string, token: {}, promise: Promise} | null} */ +let load_cache = null; + +/** @type {Array<(navigation: import('@sveltejs/kit').BeforeNavigate) => void>} */ +const before_navigate_callbacks = []; + +/** @type {Array<(navigation: import('@sveltejs/kit').OnNavigate) => import('types').MaybePromise<(() => void) | void>>} */ +const on_navigate_callbacks = []; + +/** @type {Array<(navigation: import('@sveltejs/kit').AfterNavigate) => void>} */ +let after_navigate_callbacks = []; + +/** @type {import('./types.js').NavigationState} */ +let current = { + branch: [], + error: null, + // @ts-ignore - we need the initial value to be null + url: null +}; + +/** this being true means we SSR'd */ +let hydrated = false; +let started = false; +let autoscroll = true; +let updating = false; +let navigating = false; +let hash_navigating = false; +/** True as soon as there happened one client-side navigation (excluding the SvelteKit-initialized initial one when in SPA mode) */ +let has_navigated = false; + +let force_invalidation = false; + +/** @type {import('svelte').SvelteComponent} */ +let root; + +/** @type {number} keeping track of the history index in order to prevent popstate navigation events if needed */ +let current_history_index; + +/** @type {number} */ +let current_navigation_index; + +/** @type {import('@sveltejs/kit').Page} */ +let page; + +/** @type {{}} */ +let token; + +/** + * A set of tokens which are associated to current preloads. + * If a preload becomes a real navigation, it's removed from the set. + * If a preload token is in the set and the preload errors, the error + * handling logic (for example reloading) is skipped. + */ +const preload_tokens = new Set(); + +/** @type {Promise | null} */ +let pending_invalidate; + +/** + * @param {import('./types.js').SvelteKitApp} _app + * @param {HTMLElement} _target + * @param {Parameters[1]} [hydrate] + */ +export async function start(_app, _target, hydrate) { + if (DEV && _target === document.body) { + console.warn( + 'Placing %sveltekit.body% directly inside is not recommended, as your app may break for users who have certain browser extensions installed.\n\nConsider wrapping it in an element:\n\n

\n %sveltekit.body%\n
' + ); + } + + // detect basic auth credentials in the current URL + // https://github.com/sveltejs/kit/pull/11179 + // if so, refresh the page without credentials + if (document.URL !== location.href) { + // eslint-disable-next-line no-self-assign + location.href = location.href; + } + + app = _app; + routes = parse(_app); + container = __SVELTEKIT_EMBEDDED__ ? _target : document.documentElement; + target = _target; + + // we import the root layout/error nodes eagerly, so that + // connectivity errors after initialisation don't nuke the app + default_layout_loader = _app.nodes[0]; + default_error_loader = _app.nodes[1]; + default_layout_loader(); + default_error_loader(); + + current_history_index = history.state?.[HISTORY_INDEX]; + current_navigation_index = history.state?.[NAVIGATION_INDEX]; + + if (!current_history_index) { + // we use Date.now() as an offset so that cross-document navigations + // within the app don't result in data loss + current_history_index = current_navigation_index = Date.now(); + + // create initial history entry, so we can return here + history.replaceState( + { + ...history.state, + [HISTORY_INDEX]: current_history_index, + [NAVIGATION_INDEX]: current_navigation_index + }, + '' + ); + } + + // if we reload the page, or Cmd-Shift-T back to it, + // recover scroll position + const scroll = scroll_positions[current_history_index]; + if (scroll) { + history.scrollRestoration = 'manual'; + scrollTo(scroll.x, scroll.y); + } + + if (hydrate) { + await _hydrate(target, hydrate); + } else { + goto(location.href, { replaceState: true }); + } + + _start_router(); +} + +async function _invalidate() { + // Accept all invalidations as they come, don't swallow any while another invalidation + // is running because subsequent invalidations may make earlier ones outdated, + // but batch multiple synchronous invalidations. + await (pending_invalidate ||= Promise.resolve()); + if (!pending_invalidate) return; + pending_invalidate = null; + + const intent = get_navigation_intent(current.url, true); + + // Clear preload, it might be affected by the invalidation. + // Also solves an edge case where a preload is triggered, the navigation for it + // was then triggered and is still running while the invalidation kicks in, + // at which point the invalidation should take over and "win". + load_cache = null; + + const nav_token = (token = {}); + const navigation_result = intent && (await load_route(intent)); + if (!navigation_result || nav_token !== token) return; + + if (navigation_result.type === 'redirect') { + return _goto(new URL(navigation_result.location, current.url).href, {}, 1, nav_token); + } + + if (navigation_result.props.page) { + page = navigation_result.props.page; + } + current = navigation_result.state; + reset_invalidation(); + root.$set(navigation_result.props); +} + +function reset_invalidation() { + invalidated.length = 0; + force_invalidation = false; +} + +/** @param {number} index */ +function capture_snapshot(index) { + if (components.some((c) => c?.snapshot)) { + snapshots[index] = components.map((c) => c?.snapshot?.capture()); + } +} + +/** @param {number} index */ +function restore_snapshot(index) { + snapshots[index]?.forEach((value, i) => { + components[i]?.snapshot?.restore(value); + }); +} + +function persist_state() { + update_scroll_positions(current_history_index); + storage.set(SCROLL_KEY, scroll_positions); + + capture_snapshot(current_navigation_index); + storage.set(SNAPSHOT_KEY, snapshots); +} + +/** + * @param {string | URL} url + * @param {{ replaceState?: boolean; noScroll?: boolean; keepFocus?: boolean; invalidateAll?: boolean; state?: Record }} options + * @param {number} redirect_count + * @param {{}} [nav_token] + */ +async function _goto(url, options, redirect_count, nav_token) { + return navigate({ + type: 'goto', + url: resolve_url(url), + keepfocus: options.keepFocus, + noscroll: options.noScroll, + replace_state: options.replaceState, + state: options.state, + redirect_count, + nav_token, + accept: () => { + if (options.invalidateAll) { + force_invalidation = true; + } + } + }); +} + +/** @param {import('./types.js').NavigationIntent} intent */ +async function _preload_data(intent) { + // Reuse the existing pending preload if it's for the same navigation. + // Prevents an edge case where same preload is triggered multiple times, + // then a later one is becoming the real navigation and the preload tokens + // get out of sync. + if (intent.id !== load_cache?.id) { + const preload = {}; + preload_tokens.add(preload); + load_cache = { + id: intent.id, + token: preload, + promise: load_route({ ...intent, preload }).then((result) => { + preload_tokens.delete(preload); + if (result.type === 'loaded' && result.state.error) { + // Don't cache errors, because they might be transient + load_cache = null; + } + return result; + }) + }; + } + + return load_cache.promise; +} + +/** @param {string} pathname */ +async function _preload_code(pathname) { + const route = routes.find((route) => route.exec(get_url_path(pathname))); + + if (route) { + await Promise.all([...route.layouts, route.leaf].map((load) => load?.[1]())); + } +} + +/** + * @param {import('./types.js').NavigationFinished} result + * @param {HTMLElement} target + * @param {boolean} hydrate + */ +function initialize(result, target, hydrate) { + if (DEV && result.state.error && document.querySelector('vite-error-overlay')) return; + + current = result.state; + + const style = document.querySelector('style[data-sveltekit]'); + if (style) style.remove(); + + page = /** @type {import('@sveltejs/kit').Page} */ (result.props.page); + + root = new app.root({ + target, + props: { ...result.props, stores, components }, + hydrate, + // @ts-ignore Svelte 5 specific: asynchronously instantiate the component, i.e. don't call flushSync + sync: false + }); + + restore_snapshot(current_navigation_index); + + /** @type {import('@sveltejs/kit').AfterNavigate} */ + const navigation = { + from: null, + to: { + params: current.params, + route: { id: current.route?.id ?? null }, + url: new URL(location.href) + }, + willUnload: false, + type: 'enter', + complete: Promise.resolve() + }; + + after_navigate_callbacks.forEach((fn) => fn(navigation)); + + started = true; +} + +/** + * + * @param {{ + * url: URL; + * params: Record; + * branch: Array; + * status: number; + * error: App.Error | null; + * route: import('types').CSRRoute | null; + * form?: Record | null; + * }} opts + */ +function get_navigation_result_from_branch({ url, params, branch, status, error, route, form }) { + /** @type {import('types').TrailingSlash} */ + let slash = 'never'; + + // if `paths.base === '/a/b/c`, then the root route is always `/a/b/c/`, regardless of + // the `trailingSlash` route option, so that relative paths to JS and CSS work + if (base && (url.pathname === base || url.pathname === base + '/')) { + slash = 'always'; + } else { + for (const node of branch) { + if (node?.slash !== undefined) slash = node.slash; + } + } + + url.pathname = normalize_path(url.pathname, slash); + + // eslint-disable-next-line + url.search = url.search; // turn `/?` into `/` + + /** @type {import('./types.js').NavigationFinished} */ + const result = { + type: 'loaded', + state: { + url, + params, + branch, + error, + route + }, + props: { + // @ts-ignore Somehow it's getting SvelteComponent and SvelteComponentDev mixed up + constructors: compact(branch).map((branch_node) => branch_node.node.component), + page + } + }; + + if (form !== undefined) { + result.props.form = form; + } + + let data = {}; + let data_changed = !page; + + let p = 0; + + for (let i = 0; i < Math.max(branch.length, current.branch.length); i += 1) { + const node = branch[i]; + const prev = current.branch[i]; + + if (node?.data !== prev?.data) data_changed = true; + if (!node) continue; + + data = { ...data, ...node.data }; + + // Only set props if the node actually updated. This prevents needless rerenders. + if (data_changed) { + result.props[`data_${p}`] = data; + } + + p += 1; + } + + const page_changed = + !current.url || + url.href !== current.url.href || + current.error !== error || + (form !== undefined && form !== page.form) || + data_changed; + + if (page_changed) { + result.props.page = { + error, + params, + route: { + id: route?.id ?? null + }, + state: {}, + status, + url: new URL(url), + form: form ?? null, + // The whole page store is updated, but this way the object reference stays the same + data: data_changed ? data : page.data + }; + } + + return result; +} + +/** + * Call the load function of the given node, if it exists. + * If `server_data` is passed, this is treated as the initial run and the page endpoint is not requested. + * + * @param {{ + * loader: import('types').CSRPageNodeLoader; + * parent: () => Promise>; + * url: URL; + * params: Record; + * route: { id: string | null }; + * server_data_node: import('./types.js').DataNode | null; + * }} options + * @returns {Promise} + */ +async function load_node({ loader, parent, url, params, route, server_data_node }) { + /** @type {Record | null} */ + let data = null; + + let is_tracking = true; + + /** @type {import('types').Uses} */ + const uses = { + dependencies: new Set(), + params: new Set(), + parent: false, + route: false, + url: false, + search_params: new Set() + }; + + const node = await loader(); + + if (DEV) { + validate_page_exports(node.universal); + } + + if (node.universal?.load) { + /** @param {string[]} deps */ + function depends(...deps) { + for (const dep of deps) { + if (DEV) validate_depends(/** @type {string} */ (route.id), dep); + + const { href } = new URL(dep, url); + uses.dependencies.add(href); + } + } + + /** @type {import('@sveltejs/kit').LoadEvent} */ + const load_input = { + route: new Proxy(route, { + get: (target, key) => { + if (is_tracking) { + uses.route = true; + } + return target[/** @type {'id'} */ (key)]; + } + }), + params: new Proxy(params, { + get: (target, key) => { + if (is_tracking) { + uses.params.add(/** @type {string} */ (key)); + } + return target[/** @type {string} */ (key)]; + } + }), + data: server_data_node?.data ?? null, + url: make_trackable( + url, + () => { + if (is_tracking) { + uses.url = true; + } + }, + (param) => { + if (is_tracking) { + uses.search_params.add(param); + } + } + ), + async fetch(resource, init) { + /** @type {URL | string} */ + let requested; + + if (resource instanceof Request) { + requested = resource.url; + + // we're not allowed to modify the received `Request` object, so in order + // to fixup relative urls we create a new equivalent `init` object instead + init = { + // the request body must be consumed in memory until browsers + // implement streaming request bodies and/or the body getter + body: + resource.method === 'GET' || resource.method === 'HEAD' + ? undefined + : await resource.blob(), + cache: resource.cache, + credentials: resource.credentials, + headers: resource.headers, + integrity: resource.integrity, + keepalive: resource.keepalive, + method: resource.method, + mode: resource.mode, + redirect: resource.redirect, + referrer: resource.referrer, + referrerPolicy: resource.referrerPolicy, + signal: resource.signal, + ...init + }; + } else { + requested = resource; + } + + // we must fixup relative urls so they are resolved from the target page + const resolved = new URL(requested, url); + if (is_tracking) { + depends(resolved.href); + } + + // match ssr serialized data url, which is important to find cached responses + if (resolved.origin === url.origin) { + requested = resolved.href.slice(url.origin.length); + } + + // prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be resolved + return started + ? subsequent_fetch(requested, resolved.href, init) + : initial_fetch(requested, init); + }, + setHeaders: () => {}, // noop + depends, + parent() { + if (is_tracking) { + uses.parent = true; + } + return parent(); + }, + untrack(fn) { + is_tracking = false; + try { + return fn(); + } finally { + is_tracking = true; + } + } + }; + + if (DEV) { + try { + lock_fetch(); + data = (await node.universal.load.call(null, load_input)) ?? null; + if (data != null && Object.getPrototypeOf(data) !== Object.prototype) { + throw new Error( + `a load function related to route '${route.id}' returned ${ + typeof data !== 'object' + ? `a ${typeof data}` + : data instanceof Response + ? 'a Response object' + : Array.isArray(data) + ? 'an array' + : 'a non-plain object' + }, but must return a plain object at the top level (i.e. \`return {...}\`)` + ); + } + } finally { + unlock_fetch(); + } + } else { + data = (await node.universal.load.call(null, load_input)) ?? null; + } + } + + return { + node, + loader, + server: server_data_node, + universal: node.universal?.load ? { type: 'data', data, uses } : null, + data: data ?? server_data_node?.data ?? null, + slash: node.universal?.trailingSlash ?? server_data_node?.slash + }; +} + +/** + * @param {boolean} parent_changed + * @param {boolean} route_changed + * @param {boolean} url_changed + * @param {Set} search_params_changed + * @param {import('types').Uses | undefined} uses + * @param {Record} params + */ +function has_changed( + parent_changed, + route_changed, + url_changed, + search_params_changed, + uses, + params +) { + if (force_invalidation) return true; + + if (!uses) return false; + + if (uses.parent && parent_changed) return true; + if (uses.route && route_changed) return true; + if (uses.url && url_changed) return true; + + for (const tracked_params of uses.search_params) { + if (search_params_changed.has(tracked_params)) return true; + } + + for (const param of uses.params) { + if (params[param] !== current.params[param]) return true; + } + + for (const href of uses.dependencies) { + if (invalidated.some((fn) => fn(new URL(href)))) return true; + } + + return false; +} + +/** + * @param {import('types').ServerDataNode | import('types').ServerDataSkippedNode | null} node + * @param {import('./types.js').DataNode | null} [previous] + * @returns {import('./types.js').DataNode | null} + */ +function create_data_node(node, previous) { + if (node?.type === 'data') return node; + if (node?.type === 'skip') return previous ?? null; + return null; +} + +/** + * + * @param {URL | null} old_url + * @param {URL} new_url + */ +function diff_search_params(old_url, new_url) { + if (!old_url) return new Set(new_url.searchParams.keys()); + + const changed = new Set([...old_url.searchParams.keys(), ...new_url.searchParams.keys()]); + + for (const key of changed) { + const old_values = old_url.searchParams.getAll(key); + const new_values = new_url.searchParams.getAll(key); + + if ( + old_values.every((value) => new_values.includes(value)) && + new_values.every((value) => old_values.includes(value)) + ) { + changed.delete(key); + } + } + + return changed; +} + +/** + * @param {Omit & { error: App.Error }} opts + * @returns {import('./types.js').NavigationFinished} + */ +function preload_error({ error, url, route, params }) { + return { + type: 'loaded', + state: { + error, + url, + route, + params, + branch: [] + }, + props: { page, constructors: [] } + }; +} + +/** + * @param {import('./types.js').NavigationIntent & { preload?: {} }} intent + * @returns {Promise} + */ +async function load_route({ id, invalidating, url, params, route, preload }) { + if (load_cache?.id === id) { + // the preload becomes the real navigation + preload_tokens.delete(load_cache.token); + return load_cache.promise; + } + + const { errors, layouts, leaf } = route; + + const loaders = [...layouts, leaf]; + + // preload modules to avoid waterfall, but handle rejections + // so they don't get reported to Sentry et al (we don't need + // to act on the failures at this point) + errors.forEach((loader) => loader?.().catch(() => {})); + loaders.forEach((loader) => loader?.[1]().catch(() => {})); + + /** @type {import('types').ServerNodesResponse | import('types').ServerRedirectNode | null} */ + let server_data = null; + const url_changed = current.url ? id !== current.url.pathname + current.url.search : false; + const route_changed = current.route ? route.id !== current.route.id : false; + const search_params_changed = diff_search_params(current.url, url); + + let parent_invalid = false; + const invalid_server_nodes = loaders.map((loader, i) => { + const previous = current.branch[i]; + + const invalid = + !!loader?.[0] && + (previous?.loader !== loader[1] || + has_changed( + parent_invalid, + route_changed, + url_changed, + search_params_changed, + previous.server?.uses, + params + )); + + if (invalid) { + // For the next one + parent_invalid = true; + } + + return invalid; + }); + + if (invalid_server_nodes.some(Boolean)) { + try { + server_data = await load_data(url, invalid_server_nodes); + } catch (error) { + const handled_error = await handle_error(error, { url, params, route: { id } }); + + if (preload_tokens.has(preload)) { + return preload_error({ error: handled_error, url, params, route }); + } + + return load_root_error_page({ + status: get_status(error), + error: handled_error, + url, + route + }); + } + + if (server_data.type === 'redirect') { + return server_data; + } + } + + const server_data_nodes = server_data?.nodes; + + let parent_changed = false; + + const branch_promises = loaders.map(async (loader, i) => { + if (!loader) return; + + /** @type {import('./types.js').BranchNode | undefined} */ + const previous = current.branch[i]; + + const server_data_node = server_data_nodes?.[i]; + + // re-use data from previous load if it's still valid + const valid = + (!server_data_node || server_data_node.type === 'skip') && + loader[1] === previous?.loader && + !has_changed( + parent_changed, + route_changed, + url_changed, + search_params_changed, + previous.universal?.uses, + params + ); + if (valid) return previous; + + parent_changed = true; + + if (server_data_node?.type === 'error') { + // rethrow and catch below + throw server_data_node; + } + + return load_node({ + loader: loader[1], + url, + params, + route, + parent: async () => { + const data = {}; + for (let j = 0; j < i; j += 1) { + Object.assign(data, (await branch_promises[j])?.data); + } + return data; + }, + server_data_node: create_data_node( + // server_data_node is undefined if it wasn't reloaded from the server; + // and if current loader uses server data, we want to reuse previous data. + server_data_node === undefined && loader[0] ? { type: 'skip' } : server_data_node ?? null, + loader[0] ? previous?.server : undefined + ) + }); + }); + + // if we don't do this, rejections will be unhandled + for (const p of branch_promises) p.catch(() => {}); + + /** @type {Array} */ + const branch = []; + + for (let i = 0; i < loaders.length; i += 1) { + if (loaders[i]) { + try { + branch.push(await branch_promises[i]); + } catch (err) { + if (err instanceof Redirect) { + return { + type: 'redirect', + location: err.location + }; + } + + if (preload_tokens.has(preload)) { + return preload_error({ + error: await handle_error(err, { params, url, route: { id: route.id } }), + url, + params, + route + }); + } + + let status = get_status(err); + /** @type {App.Error} */ + let error; + + if (server_data_nodes?.includes(/** @type {import('types').ServerErrorNode} */ (err))) { + // this is the server error rethrown above, reconstruct but don't invoke + // the client error handler; it should've already been handled on the server + status = /** @type {import('types').ServerErrorNode} */ (err).status ?? status; + error = /** @type {import('types').ServerErrorNode} */ (err).error; + } else if (err instanceof HttpError) { + error = err.body; + } else { + // Referenced node could have been removed due to redeploy, check + const updated = await stores.updated.check(); + if (updated) { + return await native_navigation(url); + } + + error = await handle_error(err, { params, url, route: { id: route.id } }); + } + + const error_load = await load_nearest_error_page(i, branch, errors); + if (error_load) { + return get_navigation_result_from_branch({ + url, + params, + branch: branch.slice(0, error_load.idx).concat(error_load.node), + status, + error, + route + }); + } else { + return await server_fallback(url, { id: route.id }, error, status); + } + } + } else { + // push an empty slot so we can rewind past gaps to the + // layout that corresponds with an +error.svelte page + branch.push(undefined); + } + } + + return get_navigation_result_from_branch({ + url, + params, + branch, + status: 200, + error: null, + route, + // Reset `form` on navigation, but not invalidation + form: invalidating ? undefined : null + }); +} + +/** + * @param {number} i Start index to backtrack from + * @param {Array} branch Branch to backtrack + * @param {Array} errors All error pages for this branch + * @returns {Promise<{idx: number; node: import('./types.js').BranchNode} | undefined>} + */ +async function load_nearest_error_page(i, branch, errors) { + while (i--) { + if (errors[i]) { + let j = i; + while (!branch[j]) j -= 1; + try { + return { + idx: j + 1, + node: { + node: await /** @type {import('types').CSRPageNodeLoader } */ (errors[i])(), + loader: /** @type {import('types').CSRPageNodeLoader } */ (errors[i]), + data: {}, + server: null, + universal: null + } + }; + } catch { + continue; + } + } + } +} + +/** + * @param {{ + * status: number; + * error: App.Error; + * url: URL; + * route: { id: string | null } + * }} opts + * @returns {Promise} + */ +async function load_root_error_page({ status, error, url, route }) { + /** @type {Record} */ + const params = {}; // error page does not have params + + /** @type {import('types').ServerDataNode | null} */ + let server_data_node = null; + + const default_layout_has_server_load = app.server_loads[0] === 0; + + if (default_layout_has_server_load) { + // TODO post-https://github.com/sveltejs/kit/discussions/6124 we can use + // existing root layout data + try { + const server_data = await load_data(url, [true]); + + if ( + server_data.type !== 'data' || + (server_data.nodes[0] && server_data.nodes[0].type !== 'data') + ) { + throw 0; + } + + server_data_node = server_data.nodes[0] ?? null; + } catch { + // at this point we have no choice but to fall back to the server, if it wouldn't + // bring us right back here, turning this into an endless loop + if (url.origin !== origin || url.pathname !== location.pathname || hydrated) { + await native_navigation(url); + } + } + } + + const root_layout = await load_node({ + loader: default_layout_loader, + url, + params, + route, + parent: () => Promise.resolve({}), + server_data_node: create_data_node(server_data_node) + }); + + /** @type {import('./types.js').BranchNode} */ + const root_error = { + node: await default_error_loader(), + loader: default_error_loader, + universal: null, + server: null, + data: null + }; + + return get_navigation_result_from_branch({ + url, + params, + branch: [root_layout, root_error], + status, + error, + route: null + }); +} + +/** + * Resolve the full info (which route, params, etc.) for a client-side navigation from the URL, + * taking the reroute hook into account. If this isn't a client-side-navigation (or the URL is undefined), + * returns undefined. + * @param {URL | undefined} url + * @param {boolean} invalidating + */ +function get_navigation_intent(url, invalidating) { + if (!url) return undefined; + if (is_external_url(url, base)) return; + + // reroute could alter the given URL, so we pass a copy + let rerouted; + try { + rerouted = app.hooks.reroute({ url: new URL(url) }) ?? url.pathname; + } catch (e) { + if (DEV) { + // in development, print the error... + console.error(e); + + // ...and pause execution, since otherwise we will immediately reload the page + debugger; // eslint-disable-line + } + + // fall back to native navigation + return undefined; + } + + const path = get_url_path(rerouted); + + for (const route of routes) { + const params = route.exec(path); + + if (params) { + const id = url.pathname + url.search; + /** @type {import('./types.js').NavigationIntent} */ + const intent = { + id, + invalidating, + route, + params: decode_params(params), + url + }; + return intent; + } + } +} + +/** @param {string} pathname */ +function get_url_path(pathname) { + return decode_pathname(pathname.slice(base.length) || '/'); +} + +/** + * @param {{ + * url: URL; + * type: import('@sveltejs/kit').Navigation["type"]; + * intent?: import('./types.js').NavigationIntent; + * delta?: number; + * }} opts + */ +function _before_navigate({ url, type, intent, delta }) { + let should_block = false; + + const nav = create_navigation(current, intent, url, type); + + if (delta !== undefined) { + nav.navigation.delta = delta; + } + + const cancellable = { + ...nav.navigation, + cancel: () => { + should_block = true; + nav.reject(new Error('navigation cancelled')); + } + }; + + if (!navigating) { + // Don't run the event during redirects + before_navigate_callbacks.forEach((fn) => fn(cancellable)); + } + + return should_block ? null : nav; +} + +/** + * @param {{ + * type: import('@sveltejs/kit').Navigation["type"]; + * url: URL; + * popped?: { + * state: Record; + * scroll: { x: number, y: number }; + * delta: number; + * }; + * keepfocus?: boolean; + * noscroll?: boolean; + * replace_state?: boolean; + * state?: Record; + * redirect_count?: number; + * nav_token?: {}; + * accept?: () => void; + * block?: () => void; + * }} opts + */ +async function navigate({ + type, + url, + popped, + keepfocus, + noscroll, + replace_state, + state = {}, + redirect_count = 0, + nav_token = {}, + accept = noop, + block = noop +}) { + const intent = get_navigation_intent(url, false); + const nav = _before_navigate({ url, type, delta: popped?.delta, intent }); + + if (!nav) { + block(); + return; + } + + // store this before calling `accept()`, which may change the index + const previous_history_index = current_history_index; + const previous_navigation_index = current_navigation_index; + + accept(); + + navigating = true; + + if (started) { + stores.navigating.set(nav.navigation); + } + + token = nav_token; + let navigation_result = intent && (await load_route(intent)); + + if (!navigation_result) { + if (is_external_url(url, base)) { + return await native_navigation(url); + } + navigation_result = await server_fallback( + url, + { id: null }, + await handle_error(new SvelteKitError(404, 'Not Found', `Not found: ${url.pathname}`), { + url, + params: {}, + route: { id: null } + }), + 404 + ); + } + + // if this is an internal navigation intent, use the normalized + // URL for the rest of the function + url = intent?.url || url; + + // abort if user navigated during update + if (token !== nav_token) { + nav.reject(new Error('navigation aborted')); + return false; + } + + if (navigation_result.type === 'redirect') { + // whatwg fetch spec https://fetch.spec.whatwg.org/#http-redirect-fetch says to error after 20 redirects + if (redirect_count >= 20) { + navigation_result = await load_root_error_page({ + status: 500, + error: await handle_error(new Error('Redirect loop'), { + url, + params: {}, + route: { id: null } + }), + url, + route: { id: null } + }); + } else { + _goto(new URL(navigation_result.location, url).href, {}, redirect_count + 1, nav_token); + return false; + } + } else if (/** @type {number} */ (navigation_result.props.page.status) >= 400) { + const updated = await stores.updated.check(); + if (updated) { + await native_navigation(url); + } + } + + // reset invalidation only after a finished navigation. If there are redirects or + // additional invalidations, they should get the same invalidation treatment + reset_invalidation(); + + updating = true; + + update_scroll_positions(previous_history_index); + capture_snapshot(previous_navigation_index); + + // ensure the url pathname matches the page's trailing slash option + if (navigation_result.props.page.url.pathname !== url.pathname) { + url.pathname = navigation_result.props.page.url.pathname; + } + + state = popped ? popped.state : state; + + if (!popped) { + // this is a new navigation, rather than a popstate + const change = replace_state ? 0 : 1; + + const entry = { + [HISTORY_INDEX]: (current_history_index += change), + [NAVIGATION_INDEX]: (current_navigation_index += change), + [STATES_KEY]: state + }; + + const fn = replace_state ? history.replaceState : history.pushState; + fn.call(history, entry, '', url); + + if (!replace_state) { + clear_onward_history(current_history_index, current_navigation_index); + } + } + + // reset preload synchronously after the history state has been set to avoid race conditions + load_cache = null; + + navigation_result.props.page.state = state; + + if (started) { + current = navigation_result.state; + + // reset url before updating page store + if (navigation_result.props.page) { + navigation_result.props.page.url = url; + } + + const after_navigate = ( + await Promise.all( + on_navigate_callbacks.map((fn) => + fn(/** @type {import('@sveltejs/kit').OnNavigate} */ (nav.navigation)) + ) + ) + ).filter(/** @returns {value is () => void} */ (value) => typeof value === 'function'); + + if (after_navigate.length > 0) { + function cleanup() { + after_navigate_callbacks = after_navigate_callbacks.filter( + // @ts-ignore + (fn) => !after_navigate.includes(fn) + ); + } + + after_navigate.push(cleanup); + after_navigate_callbacks.push(...after_navigate); + } + + root.$set(navigation_result.props); + has_navigated = true; + } else { + initialize(navigation_result, target, false); + } + + const { activeElement } = document; + + // need to render the DOM before we can scroll to the rendered elements and do focus management + await tick(); + + // we reset scroll before dealing with focus, to avoid a flash of unscrolled content + const scroll = popped ? popped.scroll : noscroll ? scroll_state() : null; + + if (autoscroll) { + const deep_linked = url.hash && document.getElementById(decodeURIComponent(url.hash.slice(1))); + if (scroll) { + scrollTo(scroll.x, scroll.y); + } else if (deep_linked) { + // Here we use `scrollIntoView` on the element instead of `scrollTo` + // because it natively supports the `scroll-margin` and `scroll-behavior` + // CSS properties. + deep_linked.scrollIntoView(); + } else { + scrollTo(0, 0); + } + } + + const changed_focus = + // reset focus only if any manual focus management didn't override it + document.activeElement !== activeElement && + // also refocus when activeElement is body already because the + // focus event might not have been fired on it yet + document.activeElement !== document.body; + + if (!keepfocus && !changed_focus) { + reset_focus(); + } + + autoscroll = true; + + if (navigation_result.props.page) { + page = navigation_result.props.page; + } + + navigating = false; + + if (type === 'popstate') { + restore_snapshot(current_navigation_index); + } + + nav.fulfil(undefined); + + after_navigate_callbacks.forEach((fn) => + fn(/** @type {import('@sveltejs/kit').AfterNavigate} */ (nav.navigation)) + ); + + stores.navigating.set(null); + + updating = false; +} + +/** + * Does a full page reload if it wouldn't result in an endless loop in the SPA case + * @param {URL} url + * @param {{ id: string | null }} route + * @param {App.Error} error + * @param {number} status + * @returns {Promise} + */ +async function server_fallback(url, route, error, status) { + if (url.origin === origin && url.pathname === location.pathname && !hydrated) { + // We would reload the same page we're currently on, which isn't hydrated, + // which means no SSR, which means we would end up in an endless loop + return await load_root_error_page({ + status, + error, + url, + route + }); + } + + if (DEV && status !== 404) { + console.error( + 'An error occurred while loading the page. This will cause a full page reload. (This message will only appear during development.)' + ); + + debugger; // eslint-disable-line + } + + return await native_navigation(url); +} + +if (import.meta.hot) { + import.meta.hot.on('vite:beforeUpdate', () => { + if (current.error) location.reload(); + }); +} + +function setup_preload() { + /** @type {NodeJS.Timeout} */ + let mousemove_timeout; + + container.addEventListener('mousemove', (event) => { + const target = /** @type {Element} */ (event.target); + + clearTimeout(mousemove_timeout); + mousemove_timeout = setTimeout(() => { + preload(target, 2); + }, 20); + }); + + /** @param {Event} event */ + function tap(event) { + preload(/** @type {Element} */ (event.composedPath()[0]), 1); + } + + container.addEventListener('mousedown', tap); + container.addEventListener('touchstart', tap, { passive: true }); + + const observer = new IntersectionObserver( + (entries) => { + for (const entry of entries) { + if (entry.isIntersecting) { + _preload_code(/** @type {HTMLAnchorElement} */ (entry.target).href); + observer.unobserve(entry.target); + } + } + }, + { threshold: 0 } + ); + + /** + * @param {Element} element + * @param {number} priority + */ + function preload(element, priority) { + const a = find_anchor(element, container); + if (!a) return; + + const { url, external, download } = get_link_info(a, base); + if (external || download) return; + + const options = get_router_options(a); + + if (!options.reload) { + if (priority <= options.preload_data) { + const intent = get_navigation_intent(url, false); + if (intent) { + if (DEV) { + _preload_data(intent).then((result) => { + if (result.type === 'loaded' && result.state.error) { + console.warn( + `Preloading data for ${intent.url.pathname} failed with the following error: ${result.state.error.message}\n` + + 'If this error is transient, you can ignore it. Otherwise, consider disabling preloading for this route. ' + + 'This route was preloaded due to a data-sveltekit-preload-data attribute. ' + + 'See https://kit.svelte.dev/docs/link-options for more info' + ); + } + }); + } else { + _preload_data(intent); + } + } + } else if (priority <= options.preload_code) { + _preload_code(/** @type {URL} */ (url).pathname); + } + } + } + + function after_navigate() { + observer.disconnect(); + + for (const a of container.querySelectorAll('a')) { + const { url, external, download } = get_link_info(a, base); + if (external || download) continue; + + const options = get_router_options(a); + if (options.reload) continue; + + if (options.preload_code === PRELOAD_PRIORITIES.viewport) { + observer.observe(a); + } + + if (options.preload_code === PRELOAD_PRIORITIES.eager) { + _preload_code(/** @type {URL} */ (url).pathname); + } + } + } + + after_navigate_callbacks.push(after_navigate); + after_navigate(); +} + +/** + * @param {unknown} error + * @param {import('@sveltejs/kit').NavigationEvent} event + * @returns {import('types').MaybePromise} + */ +function handle_error(error, event) { + if (error instanceof HttpError) { + return error.body; + } + + if (DEV) { + errored = true; + console.warn('The next HMR update will cause the page to reload'); + } + + const status = get_status(error); + const message = get_message(error); + + return ( + app.hooks.handleError({ error, event, status, message }) ?? /** @type {any} */ ({ message }) + ); +} + +/** + * @template {Function} T + * @param {T[]} callbacks + * @param {T} callback + */ +function add_navigation_callback(callbacks, callback) { + onMount(() => { + callbacks.push(callback); + + return () => { + const i = callbacks.indexOf(callback); + callbacks.splice(i, 1); + }; + }); +} + +/** + * A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. + * + * `afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * @param {(navigation: import('@sveltejs/kit').AfterNavigate) => void} callback + * @returns {void} + */ +export function afterNavigate(callback) { + add_navigation_callback(after_navigate_callbacks, callback); +} + +/** + * A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. + * + * Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response. + * + * When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`. + * + * If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`. + * + * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * @param {(navigation: import('@sveltejs/kit').BeforeNavigate) => void} callback + * @returns {void} + */ +export function beforeNavigate(callback) { + add_navigation_callback(before_navigate_callbacks, callback); +} + +/** + * A lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations. + * + * If you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user. + * + * If a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated. + * + * `onNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * @param {(navigation: import('@sveltejs/kit').OnNavigate) => import('types').MaybePromise<(() => void) | void>} callback + * @returns {void} + */ +export function onNavigate(callback) { + add_navigation_callback(on_navigate_callbacks, callback); +} + +/** + * If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. + * This is generally discouraged, since it breaks user expectations. + * @returns {void} + */ +export function disableScrollHandling() { + if (!BROWSER) { + throw new Error('Cannot call disableScrollHandling() on the server'); + } + + if (DEV && started && !updating) { + throw new Error('Can only disable scroll handling during navigation'); + } + + if (updating || !started) { + autoscroll = false; + } +} + +/** + * Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`. + * For external URLs, use `window.location = url` instead of calling `goto(url)`. + * + * @param {string | URL} url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. + * @param {Object} [opts] Options related to the navigation + * @param {boolean} [opts.replaceState] If `true`, will replace the current `history` entry rather than creating a new one with `pushState` + * @param {boolean} [opts.noScroll] If `true`, the browser will maintain its scroll position rather than scrolling to the top of the page after navigation + * @param {boolean} [opts.keepFocus] If `true`, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body + * @param {boolean} [opts.invalidateAll] If `true`, all `load` functions of the page will be rerun. See https://kit.svelte.dev/docs/load#rerunning-load-functions for more info on invalidation. + * @param {App.PageState} [opts.state] An optional object that will be available on the `$page.state` store + * @returns {Promise} + */ +export function goto(url, opts = {}) { + if (!BROWSER) { + throw new Error('Cannot call goto(...) on the server'); + } + + url = resolve_url(url); + + if (url.origin !== origin) { + return Promise.reject( + new Error( + DEV + ? `Cannot use \`goto\` with an external URL. Use \`window.location = "${url}"\` instead` + : 'goto: invalid URL' + ) + ); + } + + return _goto(url, opts, 0); +} + +/** + * Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. + * + * If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). + * To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. + * + * The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. + * This can be useful if you want to invalidate based on a pattern instead of a exact match. + * + * ```ts + * // Example: Match '/path' regardless of the query parameters + * import { invalidate } from '$app/navigation'; + * + * invalidate((url) => url.pathname === '/path'); + * ``` + * @param {string | URL | ((url: URL) => boolean)} resource The invalidated URL + * @returns {Promise} + */ +export function invalidate(resource) { + if (!BROWSER) { + throw new Error('Cannot call invalidate(...) on the server'); + } + + if (typeof resource === 'function') { + invalidated.push(resource); + } else { + const { href } = new URL(resource, location.href); + invalidated.push((url) => url.href === href); + } + + return _invalidate(); +} + +/** + * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. + * @returns {Promise} + */ +export function invalidateAll() { + if (!BROWSER) { + throw new Error('Cannot call invalidateAll() on the server'); + } + + force_invalidation = true; + return _invalidate(); +} + +/** + * Programmatically preloads the given page, which means + * 1. ensuring that the code for the page is loaded, and + * 2. calling the page's load function with the appropriate options. + * + * This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. + * If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. + * Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete. + * + * @param {string} href Page to preload + * @returns {Promise<{ type: 'loaded'; status: number; data: Record } | { type: 'redirect'; location: string }>} + */ +export async function preloadData(href) { + if (!BROWSER) { + throw new Error('Cannot call preloadData(...) on the server'); + } + + const url = resolve_url(href); + const intent = get_navigation_intent(url, false); + + if (!intent) { + throw new Error(`Attempted to preload a URL that does not belong to this app: ${url}`); + } + + const result = await _preload_data(intent); + if (result.type === 'redirect') { + return { + type: result.type, + location: result.location + }; + } + + const { status, data } = result.props.page ?? page; + return { type: result.type, status, data }; +} + +/** + * Programmatically imports the code for routes that haven't yet been fetched. + * Typically, you might call this to speed up subsequent navigation. + * + * You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`). + * + * Unlike `preloadData`, this won't call `load` functions. + * Returns a Promise that resolves when the modules have been imported. + * + * @param {string} pathname + * @returns {Promise} + */ +export function preloadCode(pathname) { + if (!BROWSER) { + throw new Error('Cannot call preloadCode(...) on the server'); + } + + if (DEV) { + if (!pathname.startsWith(base)) { + throw new Error( + `pathnames passed to preloadCode must start with \`paths.base\` (i.e. "${base}${pathname}" rather than "${pathname}")` + ); + } + + if (!routes.find((route) => route.exec(get_url_path(pathname)))) { + throw new Error(`'${pathname}' did not match any routes`); + } + } + + return _preload_code(pathname); +} + +/** + * Programmatically create a new history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing). + * + * @param {string | URL} url + * @param {App.PageState} state + * @returns {void} + */ +export function pushState(url, state) { + if (!BROWSER) { + throw new Error('Cannot call pushState(...) on the server'); + } + + if (DEV) { + if (!started) { + throw new Error('Cannot call pushState(...) before router is initialized'); + } + + try { + // use `devalue.stringify` as a convenient way to ensure we exclude values that can't be properly rehydrated, such as custom class instances + devalue.stringify(state); + } catch (error) { + // @ts-expect-error + throw new Error(`Could not serialize state${error.path}`); + } + } + + update_scroll_positions(current_history_index); + + const opts = { + [HISTORY_INDEX]: (current_history_index += 1), + [NAVIGATION_INDEX]: current_navigation_index, + [PAGE_URL_KEY]: page.url.href, + [STATES_KEY]: state + }; + + history.pushState(opts, '', resolve_url(url)); + has_navigated = true; + + page = { ...page, state }; + root.$set({ page }); + + clear_onward_history(current_history_index, current_navigation_index); +} + +/** + * Programmatically replace the current history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing). + * + * @param {string | URL} url + * @param {App.PageState} state + * @returns {void} + */ +export function replaceState(url, state) { + if (!BROWSER) { + throw new Error('Cannot call replaceState(...) on the server'); + } + + if (DEV) { + if (!started) { + throw new Error('Cannot call replaceState(...) before router is initialized'); + } + + try { + // use `devalue.stringify` as a convenient way to ensure we exclude values that can't be properly rehydrated, such as custom class instances + devalue.stringify(state); + } catch (error) { + // @ts-expect-error + throw new Error(`Could not serialize state${error.path}`); + } + } + + const opts = { + [HISTORY_INDEX]: current_history_index, + [NAVIGATION_INDEX]: current_navigation_index, + [PAGE_URL_KEY]: page.url.href, + [STATES_KEY]: state + }; + + history.replaceState(opts, '', resolve_url(url)); + + page = { ...page, state }; + root.$set({ page }); +} + +/** + * This action updates the `form` property of the current page with the given data and updates `$page.status`. + * In case of an error, it redirects to the nearest error page. + * @template {Record | undefined} Success + * @template {Record | undefined} Failure + * @param {import('@sveltejs/kit').ActionResult} result + * @returns {Promise} + */ +export async function applyAction(result) { + if (!BROWSER) { + throw new Error('Cannot call applyAction(...) on the server'); + } + + if (result.type === 'error') { + const url = new URL(location.href); + + const { branch, route } = current; + if (!route) return; + + const error_load = await load_nearest_error_page(current.branch.length, branch, route.errors); + if (error_load) { + const navigation_result = get_navigation_result_from_branch({ + url, + params: current.params, + branch: branch.slice(0, error_load.idx).concat(error_load.node), + status: result.status ?? 500, + error: result.error, + route + }); + + current = navigation_result.state; + + root.$set(navigation_result.props); + + tick().then(reset_focus); + } + } else if (result.type === 'redirect') { + _goto(result.location, { invalidateAll: true }, 0); + } else { + /** @type {Record} */ + root.$set({ + // this brings Svelte's view of the world in line with SvelteKit's + // after use:enhance reset the form.... + form: null, + page: { ...page, form: result.data, status: result.status } + }); + + // ...so that setting the `form` prop takes effect and isn't ignored + await tick(); + root.$set({ form: result.data }); + + if (result.type === 'success') { + reset_focus(); + } + } +} + +function _start_router() { + history.scrollRestoration = 'manual'; + + // Adopted from Nuxt.js + // Reset scrollRestoration to auto when leaving page, allowing page reload + // and back-navigation from other pages to use the browser to restore the + // scrolling position. + addEventListener('beforeunload', (e) => { + let should_block = false; + + persist_state(); + + if (!navigating) { + const nav = create_navigation(current, undefined, null, 'leave'); + + // If we're navigating, beforeNavigate was already called. If we end up in here during navigation, + // it's due to an external or full-page-reload link, for which we don't want to call the hook again. + /** @type {import('@sveltejs/kit').BeforeNavigate} */ + const navigation = { + ...nav.navigation, + cancel: () => { + should_block = true; + nav.reject(new Error('navigation cancelled')); + } + }; + + before_navigate_callbacks.forEach((fn) => fn(navigation)); + } + + if (should_block) { + e.preventDefault(); + e.returnValue = ''; + } else { + history.scrollRestoration = 'auto'; + } + }); + + addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + persist_state(); + } + }); + + // @ts-expect-error this isn't supported everywhere yet + if (!navigator.connection?.saveData) { + setup_preload(); + } + + /** @param {MouseEvent} event */ + container.addEventListener('click', async (event) => { + // Adapted from https://github.com/visionmedia/page.js + // MIT license https://github.com/visionmedia/page.js#license + if (event.button || event.which !== 1) return; + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + if (event.defaultPrevented) return; + + const a = find_anchor(/** @type {Element} */ (event.composedPath()[0]), container); + if (!a) return; + + const { url, external, target, download } = get_link_info(a, base); + if (!url) return; + + // bail out before `beforeNavigate` if link opens in a different tab + if (target === '_parent' || target === '_top') { + if (window.parent !== window) return; + } else if (target && target !== '_self') { + return; + } + + const options = get_router_options(a); + const is_svg_a_element = a instanceof SVGAElement; + + // Ignore URL protocols that differ to the current one and are not http(s) (e.g. `mailto:`, `tel:`, `myapp:`, etc.) + // This may be wrong when the protocol is x: and the link goes to y:.. which should be treated as an external + // navigation, but it's not clear how to handle that case and it's not likely to come up in practice. + // MEMO: Without this condition, firefox will open mailer twice. + // See: + // - https://github.com/sveltejs/kit/issues/4045 + // - https://github.com/sveltejs/kit/issues/5725 + // - https://github.com/sveltejs/kit/issues/6496 + if ( + !is_svg_a_element && + url.protocol !== location.protocol && + !(url.protocol === 'https:' || url.protocol === 'http:') + ) + return; + + if (download) return; + + // Ignore the following but fire beforeNavigate + if (external || options.reload) { + if (_before_navigate({ url, type: 'link' })) { + // set `navigating` to `true` to prevent `beforeNavigate` callbacks + // being called when the page unloads + navigating = true; + } else { + event.preventDefault(); + } + + return; + } + + // Check if new url only differs by hash and use the browser default behavior in that case + // This will ensure the `hashchange` event is fired + // Removing the hash does a full page navigation in the browser, so make sure a hash is present + const [nonhash, hash] = url.href.split('#'); + if (hash !== undefined && nonhash === strip_hash(location)) { + // If we are trying to navigate to the same hash, we should only + // attempt to scroll to that element and avoid any history changes. + // Otherwise, this can cause Firefox to incorrectly assign a null + // history state value without any signal that we can detect. + const [, current_hash] = current.url.href.split('#'); + if (current_hash === hash) { + event.preventDefault(); + + // We're already on /# and click on a link that goes to /#, or we're on + // /#top and click on a link that goes to /#top. In those cases just go to + // the top of the page, and avoid a history change. + if (hash === '' || (hash === 'top' && a.ownerDocument.getElementById('top') === null)) { + window.scrollTo({ top: 0 }); + } else { + a.ownerDocument.getElementById(hash)?.scrollIntoView(); + } + + return; + } + // set this flag to distinguish between navigations triggered by + // clicking a hash link and those triggered by popstate + hash_navigating = true; + + update_scroll_positions(current_history_index); + + update_url(url); + + if (!options.replace_state) return; + + // hashchange event shouldn't occur if the router is replacing state. + hash_navigating = false; + } + + event.preventDefault(); + + // allow the browser to repaint before navigating — + // this prevents INP scores being penalised + await new Promise((fulfil) => { + requestAnimationFrame(() => { + setTimeout(fulfil, 0); + }); + + setTimeout(fulfil, 100); // fallback for edge case where rAF doesn't fire because e.g. tab was backgrounded + }); + + navigate({ + type: 'link', + url, + keepfocus: options.keepfocus, + noscroll: options.noscroll, + replace_state: options.replace_state ?? url.href === location.href + }); + }); + + container.addEventListener('submit', (event) => { + if (event.defaultPrevented) return; + + const form = /** @type {HTMLFormElement} */ ( + HTMLFormElement.prototype.cloneNode.call(event.target) + ); + + const submitter = /** @type {HTMLButtonElement | HTMLInputElement | null} */ (event.submitter); + + const target = submitter?.formTarget || form.target; + + if (target === '_blank') return; + + const method = submitter?.formMethod || form.method; + + if (method !== 'get') return; + + const url = new URL( + (submitter?.hasAttribute('formaction') && submitter?.formAction) || form.action + ); + + if (is_external_url(url, base)) return; + + const event_form = /** @type {HTMLFormElement} */ (event.target); + + const options = get_router_options(event_form); + if (options.reload) return; + + event.preventDefault(); + event.stopPropagation(); + + const data = new FormData(event_form); + + const submitter_name = submitter?.getAttribute('name'); + if (submitter_name) { + data.append(submitter_name, submitter?.getAttribute('value') ?? ''); + } + + // @ts-expect-error `URLSearchParams(fd)` is kosher, but typescript doesn't know that + url.search = new URLSearchParams(data).toString(); + + navigate({ + type: 'form', + url, + keepfocus: options.keepfocus, + noscroll: options.noscroll, + replace_state: options.replace_state ?? url.href === location.href + }); + }); + + addEventListener('popstate', async (event) => { + if (event.state?.[HISTORY_INDEX]) { + const history_index = event.state[HISTORY_INDEX]; + token = {}; + + // if a popstate-driven navigation is cancelled, we need to counteract it + // with history.go, which means we end up back here, hence this check + if (history_index === current_history_index) return; + + const scroll = scroll_positions[history_index]; + const state = event.state[STATES_KEY] ?? {}; + const url = new URL(event.state[PAGE_URL_KEY] ?? location.href); + const navigation_index = event.state[NAVIGATION_INDEX]; + const is_hash_change = strip_hash(location) === strip_hash(current.url); + const shallow = + navigation_index === current_navigation_index && (has_navigated || is_hash_change); + + if (shallow) { + // We don't need to navigate, we just need to update scroll and/or state. + // This happens with hash links and `pushState`/`replaceState`. The + // exception is if we haven't navigated yet, since we could have + // got here after a modal navigation then a reload + update_url(url); + + scroll_positions[current_history_index] = scroll_state(); + if (scroll) scrollTo(scroll.x, scroll.y); + + if (state !== page.state) { + page = { ...page, state }; + root.$set({ page }); + } + + current_history_index = history_index; + return; + } + + const delta = history_index - current_history_index; + + await navigate({ + type: 'popstate', + url, + popped: { + state, + scroll, + delta + }, + accept: () => { + current_history_index = history_index; + current_navigation_index = navigation_index; + }, + block: () => { + history.go(-delta); + }, + nav_token: token + }); + } else { + // since popstate event is also emitted when an anchor referencing the same + // document is clicked, we have to check that the router isn't already handling + // the navigation. otherwise we would be updating the page store twice. + if (!hash_navigating) { + const url = new URL(location.href); + update_url(url); + } + } + }); + + addEventListener('hashchange', () => { + // if the hashchange happened as a result of clicking on a link, + // we need to update history, otherwise we have to leave it alone + if (hash_navigating) { + hash_navigating = false; + history.replaceState( + { + ...history.state, + [HISTORY_INDEX]: ++current_history_index, + [NAVIGATION_INDEX]: current_navigation_index + }, + '', + location.href + ); + } + }); + + // fix link[rel=icon], because browsers will occasionally try to load relative + // URLs after a pushState/replaceState, resulting in a 404 — see + // https://github.com/sveltejs/kit/issues/3748#issuecomment-1125980897 + for (const link of document.querySelectorAll('link')) { + if (link.rel === 'icon') link.href = link.href; // eslint-disable-line + } + + addEventListener('pageshow', (event) => { + // If the user navigates to another site and then uses the back button and + // bfcache hits, we need to set navigating to null, the site doesn't know + // the navigation away from it was successful. + // Info about bfcache here: https://web.dev/bfcache + if (event.persisted) { + stores.navigating.set(null); + } + }); + + /** + * @param {URL} url + */ + function update_url(url) { + current.url = url; + stores.page.set({ ...page, url }); + stores.page.notify(); + } +} + +/** + * @param {HTMLElement} target + * @param {{ + * status: number; + * error: App.Error | null; + * node_ids: number[]; + * params: Record; + * route: { id: string | null }; + * data: Array; + * form: Record | null; + * }} opts + */ +async function _hydrate( + target, + { status = 200, error, node_ids, params, route, data: server_data_nodes, form } +) { + hydrated = true; + + const url = new URL(location.href); + + if (!__SVELTEKIT_EMBEDDED__) { + // See https://github.com/sveltejs/kit/pull/4935#issuecomment-1328093358 for one motivation + // of determining the params on the client side. + ({ params = {}, route = { id: null } } = get_navigation_intent(url, false) || {}); + } + + /** @type {import('./types.js').NavigationFinished | undefined} */ + let result; + + try { + const branch_promises = node_ids.map(async (n, i) => { + const server_data_node = server_data_nodes[i]; + // Type isn't completely accurate, we still need to deserialize uses + if (server_data_node?.uses) { + server_data_node.uses = deserialize_uses(server_data_node.uses); + } + + return load_node({ + loader: app.nodes[n], + url, + params, + route, + parent: async () => { + const data = {}; + for (let j = 0; j < i; j += 1) { + Object.assign(data, (await branch_promises[j]).data); + } + return data; + }, + server_data_node: create_data_node(server_data_node) + }); + }); + + /** @type {Array} */ + const branch = await Promise.all(branch_promises); + + const parsed_route = routes.find(({ id }) => id === route.id); + + // server-side will have compacted the branch, reinstate empty slots + // so that error boundaries can be lined up correctly + if (parsed_route) { + const layouts = parsed_route.layouts; + for (let i = 0; i < layouts.length; i++) { + if (!layouts[i]) { + branch.splice(i, 0, undefined); + } + } + } + + result = get_navigation_result_from_branch({ + url, + params, + branch, + status, + error, + form, + route: parsed_route ?? null + }); + } catch (error) { + if (error instanceof Redirect) { + // this is a real edge case — `load` would need to return + // a redirect but only in the browser + await native_navigation(new URL(error.location, location.href)); + return; + } + + result = await load_root_error_page({ + status: get_status(error), + error: await handle_error(error, { url, params, route }), + url, + route + }); + } + + if (result.props.page) { + result.props.page.state = {}; + } + + initialize(result, target, true); +} + +/** + * @param {URL} url + * @param {boolean[]} invalid + * @returns {Promise} + */ +async function load_data(url, invalid) { + const data_url = new URL(url); + data_url.pathname = add_data_suffix(url.pathname); + if (url.pathname.endsWith('/')) { + data_url.searchParams.append(TRAILING_SLASH_PARAM, '1'); + } + if (DEV && url.searchParams.has(INVALIDATED_PARAM)) { + throw new Error(`Cannot used reserved query parameter "${INVALIDATED_PARAM}"`); + } + data_url.searchParams.append(INVALIDATED_PARAM, invalid.map((i) => (i ? '1' : '0')).join('')); + + const res = await native_fetch(data_url.href); + + if (!res.ok) { + // error message is a JSON-stringified string which devalue can't handle at the top level + // turn it into a HttpError to not call handleError on the client again (was already handled on the server) + // if `__data.json` doesn't exist or the server has an internal error, + // avoid parsing the HTML error page as a JSON + /** @type {string | undefined} */ + let message; + if (res.headers.get('content-type')?.includes('application/json')) { + message = await res.json(); + } else if (res.status === 404) { + message = 'Not Found'; + } else if (res.status === 500) { + message = 'Internal Error'; + } + throw new HttpError(res.status, message); + } + + // TODO: fix eslint error / figure out if it actually applies to our situation + // eslint-disable-next-line + return new Promise(async (resolve) => { + /** + * Map of deferred promises that will be resolved by a subsequent chunk of data + * @type {Map} + */ + const deferreds = new Map(); + const reader = /** @type {ReadableStream} */ (res.body).getReader(); + const decoder = new TextDecoder(); + + /** + * @param {any} data + */ + function deserialize(data) { + return devalue.unflatten(data, { + Promise: (id) => { + return new Promise((fulfil, reject) => { + deferreds.set(id, { fulfil, reject }); + }); + } + }); + } + + let text = ''; + + while (true) { + // Format follows ndjson (each line is a JSON object) or regular JSON spec + const { done, value } = await reader.read(); + if (done && !text) break; + + text += !value && text ? '\n' : decoder.decode(value, { stream: true }); // no value -> final chunk -> add a new line to trigger the last parse + + while (true) { + const split = text.indexOf('\n'); + if (split === -1) { + break; + } + + const node = JSON.parse(text.slice(0, split)); + text = text.slice(split + 1); + + if (node.type === 'redirect') { + return resolve(node); + } + + if (node.type === 'data') { + // This is the first (and possibly only, if no pending promises) chunk + node.nodes?.forEach((/** @type {any} */ node) => { + if (node?.type === 'data') { + node.uses = deserialize_uses(node.uses); + node.data = deserialize(node.data); + } + }); + + resolve(node); + } else if (node.type === 'chunk') { + // This is a subsequent chunk containing deferred data + const { id, data, error } = node; + const deferred = /** @type {import('types').Deferred} */ (deferreds.get(id)); + deferreds.delete(id); + + if (error) { + deferred.reject(deserialize(error)); + } else { + deferred.fulfil(deserialize(data)); + } + } + } + } + }); + + // TODO edge case handling necessary? stream() read fails? +} + +/** + * @param {any} uses + * @return {import('types').Uses} + */ +function deserialize_uses(uses) { + return { + dependencies: new Set(uses?.dependencies ?? []), + params: new Set(uses?.params ?? []), + parent: !!uses?.parent, + route: !!uses?.route, + url: !!uses?.url, + search_params: new Set(uses?.search_params ?? []) + }; +} + +function reset_focus() { + const autofocus = document.querySelector('[autofocus]'); + if (autofocus) { + // @ts-ignore + autofocus.focus(); + } else { + // Reset page selection and focus + // We try to mimic browsers' behaviour as closely as possible by targeting the + // first scrollable region, but unfortunately it's not a perfect match — e.g. + // shift-tabbing won't immediately cycle up from the end of the page on Chromium + // See https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area + const root = document.body; + const tabindex = root.getAttribute('tabindex'); + + root.tabIndex = -1; + // @ts-expect-error + root.focus({ preventScroll: true, focusVisible: false }); + + // restore `tabindex` as to prevent `root` from stealing input from elements + if (tabindex !== null) { + root.setAttribute('tabindex', tabindex); + } else { + root.removeAttribute('tabindex'); + } + + // capture current selection, so we can compare the state after + // snapshot restoration and afterNavigate callbacks have run + const selection = getSelection(); + + if (selection && selection.type !== 'None') { + /** @type {Range[]} */ + const ranges = []; + + for (let i = 0; i < selection.rangeCount; i += 1) { + ranges.push(selection.getRangeAt(i)); + } + + setTimeout(() => { + if (selection.rangeCount !== ranges.length) return; + + for (let i = 0; i < selection.rangeCount; i += 1) { + const a = ranges[i]; + const b = selection.getRangeAt(i); + + // we need to do a deep comparison rather than just `a !== b` because + // Safari behaves differently to other browsers + if ( + a.commonAncestorContainer !== b.commonAncestorContainer || + a.startContainer !== b.startContainer || + a.endContainer !== b.endContainer || + a.startOffset !== b.startOffset || + a.endOffset !== b.endOffset + ) { + return; + } + } + + // if the selection hasn't changed (as a result of an element being (auto)focused, + // or a programmatic selection, we reset everything as part of the navigation) + // fixes https://github.com/sveltejs/kit/issues/8439 + selection.removeAllRanges(); + }); + } + } +} + +/** + * @param {import('./types.js').NavigationState} current + * @param {import('./types.js').NavigationIntent | undefined} intent + * @param {URL | null} url + * @param {Exclude} type + */ +function create_navigation(current, intent, url, type) { + /** @type {(value: any) => void} */ + let fulfil; + + /** @type {(error: any) => void} */ + let reject; + + const complete = new Promise((f, r) => { + fulfil = f; + reject = r; + }); + + // Handle any errors off-chain so that it doesn't show up as an unhandled rejection + complete.catch(() => {}); + + /** @type {import('@sveltejs/kit').Navigation} */ + const navigation = { + from: { + params: current.params, + route: { id: current.route?.id ?? null }, + url: current.url + }, + to: url && { + params: intent?.params ?? null, + route: { id: intent?.route?.id ?? null }, + url + }, + willUnload: !intent, + type, + complete + }; + + return { + navigation, + // @ts-expect-error + fulfil, + // @ts-expect-error + reject + }; +} + +if (DEV) { + // Nasty hack to silence harmless warnings the user can do nothing about + const console_warn = console.warn; + console.warn = function warn(...args) { + if ( + args.length === 1 && + /<(Layout|Page|Error)(_[\w$]+)?> was created (with unknown|without expected) prop '(data|form)'/.test( + args[0] + ) + ) { + return; + } + console_warn(...args); + }; + + if (import.meta.hot) { + import.meta.hot.on('vite:beforeUpdate', () => { + if (errored) { + location.reload(); + } + }); + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/constants.js b/node_modules/@sveltejs/kit/src/runtime/client/constants.js new file mode 100644 index 00000000..982c25d7 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/constants.js @@ -0,0 +1,16 @@ +export const SNAPSHOT_KEY = 'sveltekit:snapshot'; +export const SCROLL_KEY = 'sveltekit:scroll'; +export const STATES_KEY = 'sveltekit:states'; +export const PAGE_URL_KEY = 'sveltekit:pageurl'; + +export const HISTORY_INDEX = 'sveltekit:history'; +export const NAVIGATION_INDEX = 'sveltekit:navigation'; + +export const PRELOAD_PRIORITIES = /** @type {const} */ ({ + tap: 1, + hover: 2, + viewport: 3, + eager: 4, + off: -1, + false: -1 +}); diff --git a/node_modules/@sveltejs/kit/src/runtime/client/entry.js b/node_modules/@sveltejs/kit/src/runtime/client/entry.js new file mode 100644 index 00000000..4caac5e9 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/entry.js @@ -0,0 +1,3 @@ +// we expose this as a separate entry point (rather than treating client.js as the entry point) +// so that everything other than `start` can be treeshaken +export { start } from './client.js'; diff --git a/node_modules/@sveltejs/kit/src/runtime/client/fetcher.js b/node_modules/@sveltejs/kit/src/runtime/client/fetcher.js new file mode 100644 index 00000000..1d43a5bc --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/fetcher.js @@ -0,0 +1,177 @@ +import { BROWSER, DEV } from 'esm-env'; +import { hash } from '../hash.js'; +import { b64_decode } from '../utils.js'; + +let loading = 0; + +/** @type {typeof fetch} */ +export const native_fetch = BROWSER ? window.fetch : /** @type {any} */ (() => {}); + +export function lock_fetch() { + loading += 1; +} + +export function unlock_fetch() { + loading -= 1; +} + +if (DEV && BROWSER) { + let can_inspect_stack_trace = false; + + // detect whether async stack traces work + // eslint-disable-next-line @typescript-eslint/require-await + const check_stack_trace = async () => { + const stack = /** @type {string} */ (new Error().stack); + can_inspect_stack_trace = stack.includes('check_stack_trace'); + }; + + check_stack_trace(); + + /** + * @param {RequestInfo | URL} input + * @param {RequestInit & Record | undefined} init + */ + window.fetch = (input, init) => { + // Check if fetch was called via load_node. the lock method only checks if it was called at the + // same time, but not necessarily if it was called from `load`. + // We use just the filename as the method name sometimes does not appear on the CI. + const url = input instanceof Request ? input.url : input.toString(); + const stack_array = /** @type {string} */ (new Error().stack).split('\n'); + // We need to do a cutoff because Safari and Firefox maintain the stack + // across events and for example traces a `fetch` call triggered from a button + // back to the creation of the event listener and the element creation itself, + // where at some point client.js will show up, leading to false positives. + const cutoff = stack_array.findIndex((a) => a.includes('load@') || a.includes('at load')); + const stack = stack_array.slice(0, cutoff + 2).join('\n'); + + const in_load_heuristic = can_inspect_stack_trace + ? stack.includes('src/runtime/client/client.js') + : loading; + + // This flag is set in initial_fetch and subsequent_fetch + const used_kit_fetch = init?.__sveltekit_fetch__; + + if (in_load_heuristic && !used_kit_fetch) { + console.warn( + `Loading ${url} using \`window.fetch\`. For best results, use the \`fetch\` that is passed to your \`load\` function: https://kit.svelte.dev/docs/load#making-fetch-requests` + ); + } + + const method = input instanceof Request ? input.method : init?.method || 'GET'; + + if (method !== 'GET') { + cache.delete(build_selector(input)); + } + + return native_fetch(input, init); + }; +} else if (BROWSER) { + window.fetch = (input, init) => { + const method = input instanceof Request ? input.method : init?.method || 'GET'; + + if (method !== 'GET') { + cache.delete(build_selector(input)); + } + + return native_fetch(input, init); + }; +} + +const cache = new Map(); + +/** + * Should be called on the initial run of load functions that hydrate the page. + * Saves any requests with cache-control max-age to the cache. + * @param {URL | string} resource + * @param {RequestInit} [opts] + */ +export function initial_fetch(resource, opts) { + const selector = build_selector(resource, opts); + + const script = document.querySelector(selector); + if (script?.textContent) { + let { body, ...init } = JSON.parse(script.textContent); + + const ttl = script.getAttribute('data-ttl'); + if (ttl) cache.set(selector, { body, init, ttl: 1000 * Number(ttl) }); + const b64 = script.getAttribute('data-b64'); + if (b64 !== null) { + // Can't use native_fetch('data:...;base64,${body}') + // csp can block the request + body = b64_decode(body); + } + + return Promise.resolve(new Response(body, init)); + } + + return DEV ? dev_fetch(resource, opts) : window.fetch(resource, opts); +} + +/** + * Tries to get the response from the cache, if max-age allows it, else does a fetch. + * @param {URL | string} resource + * @param {string} resolved + * @param {RequestInit} [opts] + */ +export function subsequent_fetch(resource, resolved, opts) { + if (cache.size > 0) { + const selector = build_selector(resource, opts); + const cached = cache.get(selector); + if (cached) { + // https://developer.mozilla.org/en-US/docs/Web/API/Request/cache#value + if ( + performance.now() < cached.ttl && + ['default', 'force-cache', 'only-if-cached', undefined].includes(opts?.cache) + ) { + return new Response(cached.body, cached.init); + } + + cache.delete(selector); + } + } + + return DEV ? dev_fetch(resolved, opts) : window.fetch(resolved, opts); +} + +/** + * @param {RequestInfo | URL} resource + * @param {RequestInit & Record | undefined} opts + */ +function dev_fetch(resource, opts) { + const patched_opts = { ...opts }; + // This assigns the __sveltekit_fetch__ flag and makes it non-enumerable + Object.defineProperty(patched_opts, '__sveltekit_fetch__', { + value: true, + writable: true, + configurable: true + }); + return window.fetch(resource, patched_opts); +} + +/** + * Build the cache key for a given request + * @param {URL | RequestInfo} resource + * @param {RequestInit} [opts] + */ +function build_selector(resource, opts) { + const url = JSON.stringify(resource instanceof Request ? resource.url : resource); + + let selector = `script[data-sveltekit-fetched][data-url=${url}]`; + + if (opts?.headers || opts?.body) { + /** @type {import('types').StrictBody[]} */ + const values = []; + + if (opts.headers) { + values.push([...new Headers(opts.headers)].join(',')); + } + + if (opts.body && (typeof opts.body === 'string' || ArrayBuffer.isView(opts.body))) { + values.push(opts.body); + } + + selector += `[data-hash="${hash(...values)}"]`; + } + + return selector; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/parse.js b/node_modules/@sveltejs/kit/src/runtime/client/parse.js new file mode 100644 index 00000000..5abf1a7e --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/parse.js @@ -0,0 +1,57 @@ +import { exec, parse_route_id } from '../../utils/routing.js'; + +/** + * @param {import('./types.js').SvelteKitApp} app + * @returns {import('types').CSRRoute[]} + */ +export function parse({ nodes, server_loads, dictionary, matchers }) { + const layouts_with_server_load = new Set(server_loads); + + return Object.entries(dictionary).map(([id, [leaf, layouts, errors]]) => { + const { pattern, params } = parse_route_id(id); + + const route = { + id, + /** @param {string} path */ + exec: (path) => { + const match = pattern.exec(path); + if (match) return exec(match, params, matchers); + }, + errors: [1, ...(errors || [])].map((n) => nodes[n]), + layouts: [0, ...(layouts || [])].map(create_layout_loader), + leaf: create_leaf_loader(leaf) + }; + + // bit of a hack, but ensures that layout/error node lists are the same + // length, without which the wrong data will be applied if the route + // manifest looks like `[[a, b], [c,], d]` + route.errors.length = route.layouts.length = Math.max( + route.errors.length, + route.layouts.length + ); + + return route; + }); + + /** + * @param {number} id + * @returns {[boolean, import('types').CSRPageNodeLoader]} + */ + function create_leaf_loader(id) { + // whether or not the route uses the server data is + // encoded using the ones' complement, to save space + const uses_server_data = id < 0; + if (uses_server_data) id = ~id; + return [uses_server_data, nodes[id]]; + } + + /** + * @param {number | undefined} id + * @returns {[boolean, import('types').CSRPageNodeLoader] | undefined} + */ + function create_layout_loader(id) { + // whether or not the layout uses the server data is + // encoded in the layouts array, to save space + return id === undefined ? id : [layouts_with_server_load.has(id), nodes[id]]; + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/session-storage.js b/node_modules/@sveltejs/kit/src/runtime/client/session-storage.js new file mode 100644 index 00000000..e49543bc --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/session-storage.js @@ -0,0 +1,27 @@ +/** + * Read a value from `sessionStorage` + * @param {string} key + * @param {(value: string) => any} parse + */ +export function get(key, parse = JSON.parse) { + try { + return parse(sessionStorage[key]); + } catch { + // do nothing + } +} + +/** + * Write a value to `sessionStorage` + * @param {string} key + * @param {any} value + * @param {(value: any) => string} stringify + */ +export function set(key, value, stringify = JSON.stringify) { + const data = stringify(value); + try { + sessionStorage[key] = data; + } catch { + // do nothing + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/types.d.ts b/node_modules/@sveltejs/kit/src/runtime/client/types.d.ts new file mode 100644 index 00000000..50a78a04 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/types.d.ts @@ -0,0 +1,86 @@ +import { SvelteComponent } from 'svelte'; +import { ClientHooks, CSRPageNode, CSRPageNodeLoader, CSRRoute, TrailingSlash, Uses } from 'types'; +import { Page, ParamMatcher } from '@sveltejs/kit'; + +export interface SvelteKitApp { + /** + * A list of all the error/layout/page nodes used in the app + */ + nodes: CSRPageNodeLoader[]; + + /** + * A list of all layout node ids that have a server load function. + * Pages are not present because it's shorter to encode it on the leaf itself. + */ + server_loads: number[]; + + /** + * A map of `[routeId: string]: [leaf, layouts, errors]` tuples, which + * is parsed into an array of routes on startup. The numbers refer to the indices in `nodes`. + * If the leaf number is negative, it means it does use a server load function and the complement is the node index. + * The route layout and error nodes are not referenced, they are always number 0 and 1 and always apply. + */ + dictionary: Record; + + matchers: Record; + + hooks: ClientHooks; + + root: typeof SvelteComponent; +} + +export type NavigationIntent = { + /** `url.pathname + url.search` */ + id: string; + /** Whether we are invalidating or navigating */ + invalidating: boolean; + /** The route parameters */ + params: Record; + /** The route that matches `path` */ + route: CSRRoute; + /** The destination URL */ + url: URL; +}; + +export type NavigationResult = NavigationRedirect | NavigationFinished; + +export type NavigationRedirect = { + type: 'redirect'; + location: string; +}; + +export type NavigationFinished = { + type: 'loaded'; + state: NavigationState; + props: { + constructors: Array; + components?: Array; + page: Page; + form?: Record | null; + [key: `data_${number}`]: Record; + }; +}; + +export type BranchNode = { + node: CSRPageNode; + loader: CSRPageNodeLoader; + server: DataNode | null; + universal: DataNode | null; + data: Record | null; + slash?: TrailingSlash; +}; + +export interface DataNode { + type: 'data'; + data: Record | null; + uses: Uses; + slash?: TrailingSlash; +} + +export interface NavigationState { + branch: Array; + error: App.Error | null; + params: Record; + route: CSRRoute | null; + url: URL; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/utils.js b/node_modules/@sveltejs/kit/src/runtime/client/utils.js new file mode 100644 index 00000000..16a1b342 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/utils.js @@ -0,0 +1,299 @@ +import { BROWSER, DEV } from 'esm-env'; +import { writable } from 'svelte/store'; +import { assets } from '__sveltekit/paths'; +import { version } from '__sveltekit/environment'; +import { PRELOAD_PRIORITIES } from './constants.js'; + +/* global __SVELTEKIT_APP_VERSION_FILE__, __SVELTEKIT_APP_VERSION_POLL_INTERVAL__ */ + +export const origin = BROWSER ? location.origin : ''; + +/** @param {string | URL} url */ +export function resolve_url(url) { + if (url instanceof URL) return url; + + let baseURI = document.baseURI; + + if (!baseURI) { + const baseTags = document.getElementsByTagName('base'); + baseURI = baseTags.length ? baseTags[0].href : document.URL; + } + + return new URL(url, baseURI); +} + +export function scroll_state() { + return { + x: pageXOffset, + y: pageYOffset + }; +} + +const warned = new WeakSet(); + +/** @typedef {keyof typeof valid_link_options} LinkOptionName */ + +const valid_link_options = /** @type {const} */ ({ + 'preload-code': ['', 'off', 'false', 'tap', 'hover', 'viewport', 'eager'], + 'preload-data': ['', 'off', 'false', 'tap', 'hover'], + keepfocus: ['', 'true', 'off', 'false'], + noscroll: ['', 'true', 'off', 'false'], + reload: ['', 'true', 'off', 'false'], + replacestate: ['', 'true', 'off', 'false'] +}); + +/** + * @template {LinkOptionName} T + * @typedef {typeof valid_link_options[T][number]} ValidLinkOptions + */ + +/** + * @template {LinkOptionName} T + * @param {Element} element + * @param {T} name + */ +function link_option(element, name) { + const value = /** @type {ValidLinkOptions | null} */ ( + element.getAttribute(`data-sveltekit-${name}`) + ); + + if (DEV) { + validate_link_option(element, name, value); + } + + return value; +} + +/** + * @template {LinkOptionName} T + * @template {ValidLinkOptions | null} U + * @param {Element} element + * @param {T} name + * @param {U} value + */ +function validate_link_option(element, name, value) { + if (value === null) return; + + // @ts-expect-error - includes is dumb + if (!warned.has(element) && !valid_link_options[name].includes(value)) { + console.error( + `Unexpected value for ${name} — should be one of ${valid_link_options[name] + .map((option) => JSON.stringify(option)) + .join(', ')}`, + element + ); + + warned.add(element); + } +} + +const levels = { + ...PRELOAD_PRIORITIES, + '': PRELOAD_PRIORITIES.hover +}; + +/** + * @param {Element} element + * @returns {Element | null} + */ +function parent_element(element) { + let parent = element.assignedSlot ?? element.parentNode; + + // @ts-expect-error handle shadow roots + if (parent?.nodeType === 11) parent = parent.host; + + return /** @type {Element} */ (parent); +} + +/** + * @param {Element} element + * @param {Element} target + */ +export function find_anchor(element, target) { + while (element && element !== target) { + if (element.nodeName.toUpperCase() === 'A' && element.hasAttribute('href')) { + return /** @type {HTMLAnchorElement | SVGAElement} */ (element); + } + + element = /** @type {Element} */ (parent_element(element)); + } +} + +/** + * @param {HTMLAnchorElement | SVGAElement} a + * @param {string} base + */ +export function get_link_info(a, base) { + /** @type {URL | undefined} */ + let url; + + try { + url = new URL(a instanceof SVGAElement ? a.href.baseVal : a.href, document.baseURI); + } catch {} + + const target = a instanceof SVGAElement ? a.target.baseVal : a.target; + + const external = + !url || + !!target || + is_external_url(url, base) || + (a.getAttribute('rel') || '').split(/\s+/).includes('external'); + + const download = url?.origin === origin && a.hasAttribute('download'); + + return { url, external, target, download }; +} + +/** + * @param {HTMLFormElement | HTMLAnchorElement | SVGAElement} element + */ +export function get_router_options(element) { + /** @type {ValidLinkOptions<'keepfocus'> | null} */ + let keepfocus = null; + + /** @type {ValidLinkOptions<'noscroll'> | null} */ + let noscroll = null; + + /** @type {ValidLinkOptions<'preload-code'> | null} */ + let preload_code = null; + + /** @type {ValidLinkOptions<'preload-data'> | null} */ + let preload_data = null; + + /** @type {ValidLinkOptions<'reload'> | null} */ + let reload = null; + + /** @type {ValidLinkOptions<'replacestate'> | null} */ + let replace_state = null; + + /** @type {Element} */ + let el = element; + + while (el && el !== document.documentElement) { + if (preload_code === null) preload_code = link_option(el, 'preload-code'); + if (preload_data === null) preload_data = link_option(el, 'preload-data'); + if (keepfocus === null) keepfocus = link_option(el, 'keepfocus'); + if (noscroll === null) noscroll = link_option(el, 'noscroll'); + if (reload === null) reload = link_option(el, 'reload'); + if (replace_state === null) replace_state = link_option(el, 'replacestate'); + + el = /** @type {Element} */ (parent_element(el)); + } + + /** @param {string | null} value */ + function get_option_state(value) { + switch (value) { + case '': + case 'true': + return true; + case 'off': + case 'false': + return false; + default: + return undefined; + } + } + + return { + preload_code: levels[preload_code ?? 'off'], + preload_data: levels[preload_data ?? 'off'], + keepfocus: get_option_state(keepfocus), + noscroll: get_option_state(noscroll), + reload: get_option_state(reload), + replace_state: get_option_state(replace_state) + }; +} + +/** @param {any} value */ +export function notifiable_store(value) { + const store = writable(value); + let ready = true; + + function notify() { + ready = true; + store.update((val) => val); + } + + /** @param {any} new_value */ + function set(new_value) { + ready = false; + store.set(new_value); + } + + /** @param {(value: any) => void} run */ + function subscribe(run) { + /** @type {any} */ + let old_value; + return store.subscribe((new_value) => { + if (old_value === undefined || (ready && new_value !== old_value)) { + run((old_value = new_value)); + } + }); + } + + return { notify, set, subscribe }; +} + +export function create_updated_store() { + const { set, subscribe } = writable(false); + + if (DEV || !BROWSER) { + return { + subscribe, + // eslint-disable-next-line @typescript-eslint/require-await + check: async () => false + }; + } + + const interval = __SVELTEKIT_APP_VERSION_POLL_INTERVAL__; + + /** @type {NodeJS.Timeout} */ + let timeout; + + /** @type {() => Promise} */ + async function check() { + clearTimeout(timeout); + + if (interval) timeout = setTimeout(check, interval); + + try { + const res = await fetch(`${assets}/${__SVELTEKIT_APP_VERSION_FILE__}`, { + headers: { + pragma: 'no-cache', + 'cache-control': 'no-cache' + } + }); + + if (!res.ok) { + return false; + } + + const data = await res.json(); + const updated = data.version !== version; + + if (updated) { + set(true); + clearTimeout(timeout); + } + + return updated; + } catch { + return false; + } + } + + if (interval) timeout = setTimeout(check, interval); + + return { + subscribe, + check + }; +} + +/** + * @param {URL} url + * @param {string} base + */ +export function is_external_url(url, base) { + return url.origin !== origin || !url.pathname.startsWith(base); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/components/svelte-4/error.svelte b/node_modules/@sveltejs/kit/src/runtime/components/svelte-4/error.svelte new file mode 100644 index 00000000..b82ddfae --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/components/svelte-4/error.svelte @@ -0,0 +1,6 @@ + + +

{$page.status}

+

{$page.error?.message}

diff --git a/node_modules/@sveltejs/kit/src/runtime/components/svelte-4/layout.svelte b/node_modules/@sveltejs/kit/src/runtime/components/svelte-4/layout.svelte new file mode 100644 index 00000000..4fa864ce --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/components/svelte-4/layout.svelte @@ -0,0 +1 @@ + diff --git a/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte b/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte new file mode 100644 index 00000000..b82ddfae --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte @@ -0,0 +1,6 @@ + + +

{$page.status}

+

{$page.error?.message}

diff --git a/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/layout.svelte b/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/layout.svelte new file mode 100644 index 00000000..4b7cb066 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/layout.svelte @@ -0,0 +1,5 @@ + + +{@render children()} diff --git a/node_modules/@sveltejs/kit/src/runtime/control.js b/node_modules/@sveltejs/kit/src/runtime/control.js new file mode 100644 index 00000000..64737a9c --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/control.js @@ -0,0 +1,87 @@ +export class HttpError { + /** + * @param {number} status + * @param {{message: string} extends App.Error ? (App.Error | string | undefined) : App.Error} body + */ + constructor(status, body) { + this.status = status; + if (typeof body === 'string') { + this.body = { message: body }; + } else if (body) { + this.body = body; + } else { + this.body = { message: `Error: ${status}` }; + } + } + + toString() { + return JSON.stringify(this.body); + } +} + +export class Redirect { + /** + * @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status + * @param {string} location + */ + constructor(status, location) { + this.status = status; + this.location = location; + } +} + +/** + * An error that was thrown from within the SvelteKit runtime that is not fatal and doesn't result in a 500, such as a 404. + * `SvelteKitError` goes through `handleError`. + * @extends Error + */ +export class SvelteKitError extends Error { + /** + * @param {number} status + * @param {string} text + * @param {string} message + */ + constructor(status, text, message) { + super(message); + this.status = status; + this.text = text; + } +} + +/** + * @template {Record | undefined} [T=undefined] + */ +export class ActionFailure { + /** + * @param {number} status + * @param {T} data + */ + constructor(status, data) { + this.status = status; + this.data = data; + } +} + +/** + * This is a grotesque hack that, in dev, allows us to replace the implementations + * of these classes that you'd get by importing them from `@sveltejs/kit` with the + * ones that are imported via Vite and loaded internally, so that instanceof + * checks work even though SvelteKit imports this module via Vite and consumers + * import it via Node + * @param {{ + * ActionFailure: typeof ActionFailure; + * HttpError: typeof HttpError; + * Redirect: typeof Redirect; + * SvelteKitError: typeof SvelteKitError; + * }} implementations + */ +export function replace_implementations(implementations) { + // @ts-expect-error + ActionFailure = implementations.ActionFailure; // eslint-disable-line no-class-assign + // @ts-expect-error + HttpError = implementations.HttpError; // eslint-disable-line no-class-assign + // @ts-expect-error + Redirect = implementations.Redirect; // eslint-disable-line no-class-assign + // @ts-expect-error + SvelteKitError = implementations.SvelteKitError; // eslint-disable-line no-class-assign +} diff --git a/node_modules/@sveltejs/kit/src/runtime/env/dynamic/private.js b/node_modules/@sveltejs/kit/src/runtime/env/dynamic/private.js new file mode 100644 index 00000000..1965ee8b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/env/dynamic/private.js @@ -0,0 +1 @@ +export { private_env as env } from '../../shared-server.js'; diff --git a/node_modules/@sveltejs/kit/src/runtime/env/dynamic/public.js b/node_modules/@sveltejs/kit/src/runtime/env/dynamic/public.js new file mode 100644 index 00000000..919d034b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/env/dynamic/public.js @@ -0,0 +1 @@ +export { public_env as env } from '../../shared-server.js'; diff --git a/node_modules/@sveltejs/kit/src/runtime/hash.js b/node_modules/@sveltejs/kit/src/runtime/hash.js new file mode 100644 index 00000000..cfebacb3 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/hash.js @@ -0,0 +1,22 @@ +/** + * Hash using djb2 + * @param {import('types').StrictBody[]} values + */ +export function hash(...values) { + let hash = 5381; + + for (const value of values) { + if (typeof value === 'string') { + let i = value.length; + while (i) hash = (hash * 33) ^ value.charCodeAt(--i); + } else if (ArrayBuffer.isView(value)) { + const buffer = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + let i = buffer.length; + while (i) hash = (hash * 33) ^ buffer[--i]; + } else { + throw new TypeError('value must be a string or TypedArray'); + } + } + + return (hash >>> 0).toString(36); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/ambient.d.ts b/node_modules/@sveltejs/kit/src/runtime/server/ambient.d.ts new file mode 100644 index 00000000..2f382611 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/ambient.d.ts @@ -0,0 +1,4 @@ +declare module '__SERVER__/internal.js' { + export const options: import('types').SSROptions; + export const get_hooks: () => Promise>; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/cookie.js b/node_modules/@sveltejs/kit/src/runtime/server/cookie.js new file mode 100644 index 00000000..7acd2441 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/cookie.js @@ -0,0 +1,265 @@ +import { parse, serialize } from 'cookie'; +import { add_data_suffix, normalize_path, resolve } from '../../utils/url.js'; + +/** + * Tracks all cookies set during dev mode so we can emit warnings + * when we detect that there's likely cookie misusage due to wrong paths + * + * @type {Record>} */ +const cookie_paths = {}; + +/** + * Cookies that are larger than this size (including the name and other + * attributes) are discarded by browsers + */ +const MAX_COOKIE_SIZE = 4129; + +// TODO 3.0 remove this check +/** @param {import('./page/types.js').Cookie['options']} options */ +function validate_options(options) { + if (options?.path === undefined) { + throw new Error('You must specify a `path` when setting, deleting or serializing cookies'); + } +} + +/** + * @param {Request} request + * @param {URL} url + * @param {import('types').TrailingSlash} trailing_slash + */ +export function get_cookies(request, url, trailing_slash) { + const header = request.headers.get('cookie') ?? ''; + const initial_cookies = parse(header, { decode: (value) => value }); + + const normalized_url = normalize_path(url.pathname, trailing_slash); + + /** @type {Record} */ + const new_cookies = {}; + + /** @type {import('cookie').CookieSerializeOptions} */ + const defaults = { + httpOnly: true, + sameSite: 'lax', + secure: url.hostname === 'localhost' && url.protocol === 'http:' ? false : true + }; + + /** @type {import('@sveltejs/kit').Cookies} */ + const cookies = { + // The JSDoc param annotations appearing below for get, set and delete + // are necessary to expose the `cookie` library types to + // typescript users. `@type {import('@sveltejs/kit').Cookies}` above is not + // sufficient to do so. + + /** + * @param {string} name + * @param {import('cookie').CookieParseOptions} opts + */ + get(name, opts) { + const c = new_cookies[name]; + if ( + c && + domain_matches(url.hostname, c.options.domain) && + path_matches(url.pathname, c.options.path) + ) { + return c.value; + } + + const decoder = opts?.decode || decodeURIComponent; + const req_cookies = parse(header, { decode: decoder }); + const cookie = req_cookies[name]; // the decoded string or undefined + + // in development, if the cookie was set during this session with `cookies.set`, + // but at a different path, warn the user. (ignore cookies from request headers, + // since we don't know which path they were set at) + if (__SVELTEKIT_DEV__ && !cookie) { + const paths = Array.from(cookie_paths[name] ?? []).filter((path) => { + // we only care about paths that are _more_ specific than the current path + return path_matches(path, url.pathname) && path !== url.pathname; + }); + + if (paths.length > 0) { + console.warn( + // prettier-ignore + `'${name}' cookie does not exist for ${url.pathname}, but was previously set at ${conjoin([...paths])}. Did you mean to set its 'path' to '/' instead?` + ); + } + } + + return cookie; + }, + + /** + * @param {import('cookie').CookieParseOptions} opts + */ + getAll(opts) { + const decoder = opts?.decode || decodeURIComponent; + const cookies = parse(header, { decode: decoder }); + + for (const c of Object.values(new_cookies)) { + if ( + domain_matches(url.hostname, c.options.domain) && + path_matches(url.pathname, c.options.path) + ) { + cookies[c.name] = c.value; + } + } + + return Object.entries(cookies).map(([name, value]) => ({ name, value })); + }, + + /** + * @param {string} name + * @param {string} value + * @param {import('./page/types.js').Cookie['options']} options + */ + set(name, value, options) { + validate_options(options); + set_internal(name, value, { ...defaults, ...options }); + }, + + /** + * @param {string} name + * @param {import('./page/types.js').Cookie['options']} options + */ + delete(name, options) { + validate_options(options); + cookies.set(name, '', { ...options, maxAge: 0 }); + }, + + /** + * @param {string} name + * @param {string} value + * @param {import('./page/types.js').Cookie['options']} options + */ + serialize(name, value, options) { + validate_options(options); + + let path = options.path; + + if (!options.domain || options.domain === url.hostname) { + path = resolve(normalized_url, path); + } + + return serialize(name, value, { ...defaults, ...options, path }); + } + }; + + /** + * @param {URL} destination + * @param {string | null} header + */ + function get_cookie_header(destination, header) { + /** @type {Record} */ + const combined_cookies = { + // cookies sent by the user agent have lowest precedence + ...initial_cookies + }; + + // cookies previous set during this event with cookies.set have higher precedence + for (const key in new_cookies) { + const cookie = new_cookies[key]; + if (!domain_matches(destination.hostname, cookie.options.domain)) continue; + if (!path_matches(destination.pathname, cookie.options.path)) continue; + + const encoder = cookie.options.encode || encodeURIComponent; + combined_cookies[cookie.name] = encoder(cookie.value); + } + + // explicit header has highest precedence + if (header) { + const parsed = parse(header, { decode: (value) => value }); + for (const name in parsed) { + combined_cookies[name] = parsed[name]; + } + } + + return Object.entries(combined_cookies) + .map(([name, value]) => `${name}=${value}`) + .join('; '); + } + + /** + * @param {string} name + * @param {string} value + * @param {import('./page/types.js').Cookie['options']} options + */ + function set_internal(name, value, options) { + let path = options.path; + + if (!options.domain || options.domain === url.hostname) { + path = resolve(normalized_url, path); + } + + new_cookies[name] = { name, value, options: { ...options, path } }; + + if (__SVELTEKIT_DEV__) { + const serialized = serialize(name, value, new_cookies[name].options); + if (new TextEncoder().encode(serialized).byteLength > MAX_COOKIE_SIZE) { + throw new Error(`Cookie "${name}" is too large, and will be discarded by the browser`); + } + + cookie_paths[name] ??= new Set(); + + if (!value) { + cookie_paths[name].delete(path); + } else { + cookie_paths[name].add(path); + } + } + } + + return { cookies, new_cookies, get_cookie_header, set_internal }; +} + +/** + * @param {string} hostname + * @param {string} [constraint] + */ +export function domain_matches(hostname, constraint) { + if (!constraint) return true; + + const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint; + + if (hostname === normalized) return true; + return hostname.endsWith('.' + normalized); +} + +/** + * @param {string} path + * @param {string} [constraint] + */ +export function path_matches(path, constraint) { + if (!constraint) return true; + + const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint; + + if (path === normalized) return true; + return path.startsWith(normalized + '/'); +} + +/** + * @param {Headers} headers + * @param {import('./page/types.js').Cookie[]} cookies + */ +export function add_cookies_to_headers(headers, cookies) { + for (const new_cookie of cookies) { + const { name, value, options } = new_cookie; + headers.append('set-cookie', serialize(name, value, options)); + + // special case — for routes ending with .html, the route data lives in a sibling + // `.html__data.json` file rather than a child `/__data.json` file, which means + // we need to duplicate the cookie + if (options.path.endsWith('.html')) { + const path = add_data_suffix(options.path); + headers.append('set-cookie', serialize(name, value, { ...options, path })); + } + } +} + +/** + * @param {string[]} array + */ +function conjoin(array) { + if (array.length <= 2) return array.join(' and '); + return `${array.slice(0, -1).join(', ')} and ${array.at(-1)}`; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/data/index.js b/node_modules/@sveltejs/kit/src/runtime/server/data/index.js new file mode 100644 index 00000000..b278ee31 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/data/index.js @@ -0,0 +1,265 @@ +import { HttpError, SvelteKitError, Redirect } from '../../control.js'; +import { normalize_error } from '../../../utils/error.js'; +import { once } from '../../../utils/functions.js'; +import { load_server_data } from '../page/load_data.js'; +import { clarify_devalue_error, handle_error_and_jsonify, stringify_uses } from '../utils.js'; +import { normalize_path } from '../../../utils/url.js'; +import { text } from '../../../exports/index.js'; +import * as devalue from 'devalue'; +import { create_async_iterator } from '../../../utils/streaming.js'; + +const encoder = new TextEncoder(); + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSRRoute} route + * @param {import('types').SSROptions} options + * @param {import('@sveltejs/kit').SSRManifest} manifest + * @param {import('types').SSRState} state + * @param {boolean[] | undefined} invalidated_data_nodes + * @param {import('types').TrailingSlash} trailing_slash + * @returns {Promise} + */ +export async function render_data( + event, + route, + options, + manifest, + state, + invalidated_data_nodes, + trailing_slash +) { + if (!route.page) { + // requesting /__data.json should fail for a +server.js + return new Response(undefined, { + status: 404 + }); + } + + try { + const node_ids = [...route.page.layouts, route.page.leaf]; + const invalidated = invalidated_data_nodes ?? node_ids.map(() => true); + + let aborted = false; + + const url = new URL(event.url); + url.pathname = normalize_path(url.pathname, trailing_slash); + + const new_event = { ...event, url }; + + const functions = node_ids.map((n, i) => { + return once(async () => { + try { + if (aborted) { + return /** @type {import('types').ServerDataSkippedNode} */ ({ + type: 'skip' + }); + } + + // == because it could be undefined (in dev) or null (in build, because of JSON.stringify) + const node = n == undefined ? n : await manifest._.nodes[n](); + // load this. for the child, return as is. for the final result, stream things + return load_server_data({ + event: new_event, + state, + node, + parent: async () => { + /** @type {Record} */ + const data = {}; + for (let j = 0; j < i; j += 1) { + const parent = /** @type {import('types').ServerDataNode | null} */ ( + await functions[j]() + ); + + if (parent) { + Object.assign(data, parent.data); + } + } + return data; + } + }); + } catch (e) { + aborted = true; + throw e; + } + }); + }); + + const promises = functions.map(async (fn, i) => { + if (!invalidated[i]) { + return /** @type {import('types').ServerDataSkippedNode} */ ({ + type: 'skip' + }); + } + + return fn(); + }); + + let length = promises.length; + const nodes = await Promise.all( + promises.map((p, i) => + p.catch(async (error) => { + if (error instanceof Redirect) { + throw error; + } + + // Math.min because array isn't guaranteed to resolve in order + length = Math.min(length, i + 1); + + return /** @type {import('types').ServerErrorNode} */ ({ + type: 'error', + error: await handle_error_and_jsonify(event, options, error), + status: + error instanceof HttpError || error instanceof SvelteKitError + ? error.status + : undefined + }); + }) + ) + ); + + const { data, chunks } = get_data_json(event, options, nodes); + + if (!chunks) { + // use a normal JSON response where possible, so we get `content-length` + // and can use browser JSON devtools for easier inspecting + return json_response(data); + } + + return new Response( + new ReadableStream({ + async start(controller) { + controller.enqueue(encoder.encode(data)); + for await (const chunk of chunks) { + controller.enqueue(encoder.encode(chunk)); + } + controller.close(); + }, + + type: 'bytes' + }), + { + headers: { + // we use a proprietary content type to prevent buffering. + // the `text` prefix makes it inspectable + 'content-type': 'text/sveltekit-data', + 'cache-control': 'private, no-store' + } + } + ); + } catch (e) { + const error = normalize_error(e); + + if (error instanceof Redirect) { + return redirect_json_response(error); + } else { + return json_response(await handle_error_and_jsonify(event, options, error), 500); + } + } +} + +/** + * @param {Record | string} json + * @param {number} [status] + */ +function json_response(json, status = 200) { + return text(typeof json === 'string' ? json : JSON.stringify(json), { + status, + headers: { + 'content-type': 'application/json', + 'cache-control': 'private, no-store' + } + }); +} + +/** + * @param {Redirect} redirect + */ +export function redirect_json_response(redirect) { + return json_response({ + type: 'redirect', + location: redirect.location + }); +} + +/** + * If the serialized data contains promises, `chunks` will be an + * async iterable containing their resolutions + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSROptions} options + * @param {Array} nodes + * @returns {{ data: string, chunks: AsyncIterable | null }} + */ +export function get_data_json(event, options, nodes) { + let promise_id = 1; + let count = 0; + + const { iterator, push, done } = create_async_iterator(); + + const reducers = { + /** @param {any} thing */ + Promise: (thing) => { + if (typeof thing?.then === 'function') { + const id = promise_id++; + count += 1; + + /** @type {'data' | 'error'} */ + let key = 'data'; + + thing + .catch( + /** @param {any} e */ async (e) => { + key = 'error'; + return handle_error_and_jsonify(event, options, /** @type {any} */ (e)); + } + ) + .then( + /** @param {any} value */ + async (value) => { + let str; + try { + str = devalue.stringify(value, reducers); + } catch { + const error = await handle_error_and_jsonify( + event, + options, + new Error(`Failed to serialize promise while rendering ${event.route.id}`) + ); + + key = 'error'; + str = devalue.stringify(error, reducers); + } + + count -= 1; + + push(`{"type":"chunk","id":${id},"${key}":${str}}\n`); + if (count === 0) done(); + } + ); + + return id; + } + } + }; + + try { + const strings = nodes.map((node) => { + if (!node) return 'null'; + + if (node.type === 'error' || node.type === 'skip') { + return JSON.stringify(node); + } + + return `{"type":"data","data":${devalue.stringify(node.data, reducers)},${stringify_uses( + node + )}${node.slash ? `,"slash":${JSON.stringify(node.slash)}` : ''}}`; + }); + + return { + data: `{"type":"data","nodes":[${strings.join(',')}]}\n`, + chunks: count > 0 ? iterator : null + }; + } catch (e) { + throw new Error(clarify_devalue_error(event, /** @type {any} */ (e))); + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/endpoint.js b/node_modules/@sveltejs/kit/src/runtime/server/endpoint.js new file mode 100644 index 00000000..55bcd878 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/endpoint.js @@ -0,0 +1,94 @@ +import { ENDPOINT_METHODS, PAGE_METHODS } from '../../constants.js'; +import { negotiate } from '../../utils/http.js'; +import { Redirect } from '../control.js'; +import { method_not_allowed } from './utils.js'; + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSREndpoint} mod + * @param {import('types').SSRState} state + * @returns {Promise} + */ +export async function render_endpoint(event, mod, state) { + const method = /** @type {import('types').HttpMethod} */ (event.request.method); + + let handler = mod[method] || mod.fallback; + + if (method === 'HEAD' && mod.GET && !mod.HEAD) { + handler = mod.GET; + } + + if (!handler) { + return method_not_allowed(mod, method); + } + + const prerender = mod.prerender ?? state.prerender_default; + + if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) { + throw new Error('Cannot prerender endpoints that have mutative methods'); + } + + if (state.prerendering && !prerender) { + if (state.depth > 0) { + // if request came from a prerendered page, bail + throw new Error(`${event.route.id} is not prerenderable`); + } else { + // if request came direct from the crawler, signal that + // this route cannot be prerendered, but don't bail + return new Response(undefined, { status: 204 }); + } + } + + try { + let response = await handler( + /** @type {import('@sveltejs/kit').RequestEvent>} */ (event) + ); + + if (!(response instanceof Response)) { + throw new Error( + `Invalid response from route ${event.url.pathname}: handler should return a Response object` + ); + } + + if (state.prerendering) { + // the returned Response might have immutable Headers + // so we should clone them before trying to mutate them + response = new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers: new Headers(response.headers) + }); + response.headers.set('x-sveltekit-prerender', String(prerender)); + } + + return response; + } catch (e) { + if (e instanceof Redirect) { + return new Response(undefined, { + status: e.status, + headers: { location: e.location } + }); + } + + throw e; + } +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + */ +export function is_endpoint_request(event) { + const { method, headers } = event.request; + + // These methods exist exclusively for endpoints + if (ENDPOINT_METHODS.includes(method) && !PAGE_METHODS.includes(method)) { + return true; + } + + // use:enhance uses a custom header to disambiguate + if (method === 'POST' && headers.get('x-sveltekit-action') === 'true') return false; + + // GET/POST requests may be for endpoints or pages. We prefer endpoints if this isn't a text/html request + const accept = event.request.headers.get('accept') ?? '*/*'; + return negotiate(accept, ['*', 'text/html']) !== 'text/html'; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/env_module.js b/node_modules/@sveltejs/kit/src/runtime/server/env_module.js new file mode 100644 index 00000000..7d37ac6a --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/env_module.js @@ -0,0 +1,29 @@ +import { public_env } from '../shared-server.js'; + +/** @type {string} */ +let body; + +/** @type {string} */ +let etag; + +/** @type {Headers} */ +let headers; + +/** + * @param {Request} request + * @returns {Response} + */ +export function get_public_env(request) { + body ??= `export const env=${JSON.stringify(public_env)}`; + etag ??= `W/${Date.now()}`; + headers ??= new Headers({ + 'content-type': 'application/javascript; charset=utf-8', + etag + }); + + if (request.headers.get('if-none-match') === etag) { + return new Response(undefined, { status: 304, headers }); + } + + return new Response(body, { headers }); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/fetch.js b/node_modules/@sveltejs/kit/src/runtime/server/fetch.js new file mode 100644 index 00000000..ff4a1fa5 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/fetch.js @@ -0,0 +1,175 @@ +import * as set_cookie_parser from 'set-cookie-parser'; +import { respond } from './respond.js'; +import * as paths from '__sveltekit/paths'; + +/** + * @param {{ + * event: import('@sveltejs/kit').RequestEvent; + * options: import('types').SSROptions; + * manifest: import('@sveltejs/kit').SSRManifest; + * state: import('types').SSRState; + * get_cookie_header: (url: URL, header: string | null) => string; + * set_internal: (name: string, value: string, opts: import('./page/types.js').Cookie['options']) => void; + * }} opts + * @returns {typeof fetch} + */ +export function create_fetch({ event, options, manifest, state, get_cookie_header, set_internal }) { + /** + * @type {typeof fetch} + */ + const server_fetch = async (info, init) => { + const original_request = normalize_fetch_input(info, init, event.url); + + // some runtimes (e.g. Cloudflare) error if you access `request.mode`, + // annoyingly, so we need to read the value from the `init` object instead + let mode = (info instanceof Request ? info.mode : init?.mode) ?? 'cors'; + let credentials = + (info instanceof Request ? info.credentials : init?.credentials) ?? 'same-origin'; + + return options.hooks.handleFetch({ + event, + request: original_request, + fetch: async (info, init) => { + const request = normalize_fetch_input(info, init, event.url); + + const url = new URL(request.url); + + if (!request.headers.has('origin')) { + request.headers.set('origin', event.url.origin); + } + + if (info !== original_request) { + mode = (info instanceof Request ? info.mode : init?.mode) ?? 'cors'; + credentials = + (info instanceof Request ? info.credentials : init?.credentials) ?? 'same-origin'; + } + + // Remove Origin, according to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin#description + if ( + (request.method === 'GET' || request.method === 'HEAD') && + ((mode === 'no-cors' && url.origin !== event.url.origin) || + url.origin === event.url.origin) + ) { + request.headers.delete('origin'); + } + + if (url.origin !== event.url.origin) { + // Allow cookie passthrough for "credentials: same-origin" and "credentials: include" + // if SvelteKit is serving my.domain.com: + // - domain.com WILL NOT receive cookies + // - my.domain.com WILL receive cookies + // - api.domain.dom WILL NOT receive cookies + // - sub.my.domain.com WILL receive cookies + // ports do not affect the resolution + // leading dot prevents mydomain.com matching domain.com + // Do not forward other cookies for "credentials: include" because we don't know + // which cookie belongs to which domain (browser does not pass this info) + if (`.${url.hostname}`.endsWith(`.${event.url.hostname}`) && credentials !== 'omit') { + const cookie = get_cookie_header(url, request.headers.get('cookie')); + if (cookie) request.headers.set('cookie', cookie); + } + + return fetch(request); + } + + // handle fetch requests for static assets. e.g. prebaked data, etc. + // we need to support everything the browser's fetch supports + const prefix = paths.assets || paths.base; + const decoded = decodeURIComponent(url.pathname); + const filename = ( + decoded.startsWith(prefix) ? decoded.slice(prefix.length) : decoded + ).slice(1); + const filename_html = `${filename}/index.html`; // path may also match path/index.html + + const is_asset = manifest.assets.has(filename); + const is_asset_html = manifest.assets.has(filename_html); + + if (is_asset || is_asset_html) { + const file = is_asset ? filename : filename_html; + + if (state.read) { + const type = is_asset + ? manifest.mimeTypes[filename.slice(filename.lastIndexOf('.'))] + : 'text/html'; + + return new Response(state.read(file), { + headers: type ? { 'content-type': type } : {} + }); + } + + return await fetch(request); + } + + if (credentials !== 'omit') { + const cookie = get_cookie_header(url, request.headers.get('cookie')); + if (cookie) { + request.headers.set('cookie', cookie); + } + + const authorization = event.request.headers.get('authorization'); + if (authorization && !request.headers.has('authorization')) { + request.headers.set('authorization', authorization); + } + } + + if (!request.headers.has('accept')) { + request.headers.set('accept', '*/*'); + } + + if (!request.headers.has('accept-language')) { + request.headers.set( + 'accept-language', + /** @type {string} */ (event.request.headers.get('accept-language')) + ); + } + + const response = await respond(request, options, manifest, { + ...state, + depth: state.depth + 1 + }); + + const set_cookie = response.headers.get('set-cookie'); + if (set_cookie) { + for (const str of set_cookie_parser.splitCookiesString(set_cookie)) { + const { name, value, ...options } = set_cookie_parser.parseString(str, { + decodeValues: false + }); + + const path = options.path ?? (url.pathname.split('/').slice(0, -1).join('/') || '/'); + + // options.sameSite is string, something more specific is required - type cast is safe + set_internal(name, value, { + path, + encode: (value) => value, + .../** @type {import('cookie').CookieSerializeOptions} */ (options) + }); + } + } + + return response; + } + }); + }; + + // Don't make this function `async`! Otherwise, the user has to `catch` promises they use for streaming responses or else + // it will be an unhandled rejection. Instead, we add a `.catch(() => {})` ourselves below to prevent this from happening. + return (input, init) => { + // See docs in fetch.js for why we need to do this + const response = server_fetch(input, init); + response.catch(() => {}); + return response; + }; +} + +/** + * @param {RequestInfo | URL} info + * @param {RequestInit | undefined} init + * @param {URL} url + */ +function normalize_fetch_input(info, init, url) { + if (info instanceof Request) { + return info; + } + + return new Request(typeof info === 'string' ? new URL(info, url) : info, init); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/index.js b/node_modules/@sveltejs/kit/src/runtime/server/index.js new file mode 100644 index 00000000..36cbd04b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/index.js @@ -0,0 +1,104 @@ +import { respond } from './respond.js'; +import { set_private_env, set_public_env, set_safe_public_env } from '../shared-server.js'; +import { options, get_hooks } from '__SERVER__/internal.js'; +import { DEV } from 'esm-env'; +import { filter_private_env, filter_public_env } from '../../utils/env.js'; +import { prerendering } from '__sveltekit/environment'; +import { set_read_implementation, set_manifest } from '__sveltekit/server'; + +/** @type {ProxyHandler<{ type: 'public' | 'private' }>} */ +const prerender_env_handler = { + get({ type }, prop) { + throw new Error( + `Cannot read values from $env/dynamic/${type} while prerendering (attempted to read env.${prop.toString()}). Use $env/static/${type} instead` + ); + } +}; + +export class Server { + /** @type {import('types').SSROptions} */ + #options; + + /** @type {import('@sveltejs/kit').SSRManifest} */ + #manifest; + + /** @param {import('@sveltejs/kit').SSRManifest} manifest */ + constructor(manifest) { + /** @type {import('types').SSROptions} */ + this.#options = options; + this.#manifest = manifest; + + set_manifest(manifest); + } + + /** + * @param {{ + * env: Record; + * read?: (file: string) => ReadableStream; + * }} opts + */ + async init({ env, read }) { + // Take care: Some adapters may have to call `Server.init` per-request to set env vars, + // so anything that shouldn't be rerun should be wrapped in an `if` block to make sure it hasn't + // been done already. + + // set env, in case it's used in initialisation + const prefixes = { + public_prefix: this.#options.env_public_prefix, + private_prefix: this.#options.env_private_prefix + }; + + const private_env = filter_private_env(env, prefixes); + const public_env = filter_public_env(env, prefixes); + + set_private_env( + prerendering ? new Proxy({ type: 'private' }, prerender_env_handler) : private_env + ); + set_public_env( + prerendering ? new Proxy({ type: 'public' }, prerender_env_handler) : public_env + ); + set_safe_public_env(public_env); + + if (read) { + set_read_implementation(read); + } + + if (!this.#options.hooks) { + try { + const module = await get_hooks(); + + this.#options.hooks = { + handle: module.handle || (({ event, resolve }) => resolve(event)), + handleError: module.handleError || (({ error }) => console.error(error)), + handleFetch: module.handleFetch || (({ request, fetch }) => fetch(request)), + reroute: module.reroute || (() => {}) + }; + } catch (error) { + if (DEV) { + this.#options.hooks = { + handle: () => { + throw error; + }, + handleError: ({ error }) => console.error(error), + handleFetch: ({ request, fetch }) => fetch(request), + reroute: () => {} + }; + } else { + throw error; + } + } + } + } + + /** + * @param {Request} request + * @param {import('types').RequestOptions} options + */ + async respond(request, options) { + return respond(request, this.#options, this.#manifest, { + ...options, + error: false, + depth: 0 + }); + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js b/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js new file mode 100644 index 00000000..64db8105 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js @@ -0,0 +1,291 @@ +import * as devalue from 'devalue'; +import { json } from '../../../exports/index.js'; +import { get_status, normalize_error } from '../../../utils/error.js'; +import { is_form_content_type, negotiate } from '../../../utils/http.js'; +import { HttpError, Redirect, ActionFailure, SvelteKitError } from '../../control.js'; +import { handle_error_and_jsonify } from '../utils.js'; + +/** @param {import('@sveltejs/kit').RequestEvent} event */ +export function is_action_json_request(event) { + const accept = negotiate(event.request.headers.get('accept') ?? '*/*', [ + 'application/json', + 'text/html' + ]); + + return accept === 'application/json' && event.request.method === 'POST'; +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSROptions} options + * @param {import('types').SSRNode['server'] | undefined} server + */ +export async function handle_action_json_request(event, options, server) { + const actions = server?.actions; + + if (!actions) { + const no_actions_error = new SvelteKitError( + 405, + 'Method Not Allowed', + 'POST method not allowed. No actions exist for this page' + ); + return action_json( + { + type: 'error', + error: await handle_error_and_jsonify(event, options, no_actions_error) + }, + { + status: no_actions_error.status, + headers: { + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 + // "The server must generate an Allow header field in a 405 status code response" + allow: 'GET' + } + } + ); + } + + check_named_default_separate(actions); + + try { + const data = await call_action(event, actions); + + if (__SVELTEKIT_DEV__) { + validate_action_return(data); + } + + if (data instanceof ActionFailure) { + return action_json({ + type: 'failure', + status: data.status, + // @ts-expect-error we assign a string to what is supposed to be an object. That's ok + // because we don't use the object outside, and this way we have better code navigation + // through knowing where the related interface is used. + data: stringify_action_response(data.data, /** @type {string} */ (event.route.id)) + }); + } else { + return action_json({ + type: 'success', + status: data ? 200 : 204, + // @ts-expect-error see comment above + data: stringify_action_response(data, /** @type {string} */ (event.route.id)) + }); + } + } catch (e) { + const err = normalize_error(e); + + if (err instanceof Redirect) { + return action_json_redirect(err); + } + + return action_json( + { + type: 'error', + error: await handle_error_and_jsonify(event, options, check_incorrect_fail_use(err)) + }, + { + status: get_status(err) + } + ); + } +} + +/** + * @param {HttpError | Error} error + */ +function check_incorrect_fail_use(error) { + return error instanceof ActionFailure + ? new Error('Cannot "throw fail()". Use "return fail()"') + : error; +} + +/** + * @param {import('@sveltejs/kit').Redirect} redirect + */ +export function action_json_redirect(redirect) { + return action_json({ + type: 'redirect', + status: redirect.status, + location: redirect.location + }); +} + +/** + * @param {import('@sveltejs/kit').ActionResult} data + * @param {ResponseInit} [init] + */ +function action_json(data, init) { + return json(data, init); +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + */ +export function is_action_request(event) { + return event.request.method === 'POST'; +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSRNode['server'] | undefined} server + * @returns {Promise} + */ +export async function handle_action_request(event, server) { + const actions = server?.actions; + + if (!actions) { + // TODO should this be a different error altogether? + event.setHeaders({ + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 + // "The server must generate an Allow header field in a 405 status code response" + allow: 'GET' + }); + return { + type: 'error', + error: new SvelteKitError( + 405, + 'Method Not Allowed', + 'POST method not allowed. No actions exist for this page' + ) + }; + } + + check_named_default_separate(actions); + + try { + const data = await call_action(event, actions); + + if (__SVELTEKIT_DEV__) { + validate_action_return(data); + } + + if (data instanceof ActionFailure) { + return { + type: 'failure', + status: data.status, + data: data.data + }; + } else { + return { + type: 'success', + status: 200, + // @ts-expect-error this will be removed upon serialization, so `undefined` is the same as omission + data + }; + } + } catch (e) { + const err = normalize_error(e); + + if (err instanceof Redirect) { + return { + type: 'redirect', + status: err.status, + location: err.location + }; + } + + return { + type: 'error', + error: check_incorrect_fail_use(err) + }; + } +} + +/** + * @param {import('@sveltejs/kit').Actions} actions + */ +function check_named_default_separate(actions) { + if (actions.default && Object.keys(actions).length > 1) { + throw new Error( + 'When using named actions, the default action cannot be used. See the docs for more info: https://kit.svelte.dev/docs/form-actions#named-actions' + ); + } +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {NonNullable} actions + * @throws {Redirect | HttpError | SvelteKitError | Error} + */ +async function call_action(event, actions) { + const url = new URL(event.request.url); + + let name = 'default'; + for (const param of url.searchParams) { + if (param[0].startsWith('/')) { + name = param[0].slice(1); + if (name === 'default') { + throw new Error('Cannot use reserved action name "default"'); + } + break; + } + } + + const action = actions[name]; + if (!action) { + throw new SvelteKitError(404, 'Not Found', `No action with name '${name}' found`); + } + + if (!is_form_content_type(event.request)) { + throw new SvelteKitError( + 415, + 'Unsupported Media Type', + `Form actions expect form-encoded data — received ${event.request.headers.get( + 'content-type' + )}` + ); + } + + return action(event); +} + +/** @param {any} data */ +function validate_action_return(data) { + if (data instanceof Redirect) { + throw new Error('Cannot `return redirect(...)` — use `redirect(...)` instead'); + } + + if (data instanceof HttpError) { + throw new Error('Cannot `return error(...)` — use `error(...)` or `return fail(...)` instead'); + } +} + +/** + * Try to `devalue.uneval` the data object, and if it fails, return a proper Error with context + * @param {any} data + * @param {string} route_id + */ +export function uneval_action_response(data, route_id) { + return try_deserialize(data, devalue.uneval, route_id); +} + +/** + * Try to `devalue.stringify` the data object, and if it fails, return a proper Error with context + * @param {any} data + * @param {string} route_id + */ +function stringify_action_response(data, route_id) { + return try_deserialize(data, devalue.stringify, route_id); +} + +/** + * @param {any} data + * @param {(data: any) => string} fn + * @param {string} route_id + */ +function try_deserialize(data, fn, route_id) { + try { + return fn(data); + } catch (e) { + // If we're here, the data could not be serialized with devalue + const error = /** @type {any} */ (e); + + if ('path' in error) { + let message = `Data returned from action inside ${route_id} is not serializable: ${error.message}`; + if (error.path !== '') message += ` (data.${error.path})`; + throw new Error(message); + } + + throw error; + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/page/crypto.js b/node_modules/@sveltejs/kit/src/runtime/server/page/crypto.js new file mode 100644 index 00000000..9af02da5 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/page/crypto.js @@ -0,0 +1,239 @@ +const encoder = new TextEncoder(); + +/** + * SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl + * modified and redistributed under BSD license + * @param {string} data + */ +export function sha256(data) { + if (!key[0]) precompute(); + + const out = init.slice(0); + const array = encode(data); + + for (let i = 0; i < array.length; i += 16) { + const w = array.subarray(i, i + 16); + + let tmp; + let a; + let b; + + let out0 = out[0]; + let out1 = out[1]; + let out2 = out[2]; + let out3 = out[3]; + let out4 = out[4]; + let out5 = out[5]; + let out6 = out[6]; + let out7 = out[7]; + + /* Rationale for placement of |0 : + * If a value can overflow is original 32 bits by a factor of more than a few + * million (2^23 ish), there is a possibility that it might overflow the + * 53-bit mantissa and lose precision. + * + * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that + * propagates around the loop, and on the hash state out[]. I don't believe + * that the clamps on out4 and on out0 are strictly necessary, but it's close + * (for out4 anyway), and better safe than sorry. + * + * The clamps on out[] are necessary for the output to be correct even in the + * common case and for short inputs. + */ + + for (let i = 0; i < 64; i++) { + // load up the input word for this round + + if (i < 16) { + tmp = w[i]; + } else { + a = w[(i + 1) & 15]; + + b = w[(i + 14) & 15]; + + tmp = w[i & 15] = + (((a >>> 7) ^ (a >>> 18) ^ (a >>> 3) ^ (a << 25) ^ (a << 14)) + + ((b >>> 17) ^ (b >>> 19) ^ (b >>> 10) ^ (b << 15) ^ (b << 13)) + + w[i & 15] + + w[(i + 9) & 15]) | + 0; + } + + tmp = + tmp + + out7 + + ((out4 >>> 6) ^ (out4 >>> 11) ^ (out4 >>> 25) ^ (out4 << 26) ^ (out4 << 21) ^ (out4 << 7)) + + (out6 ^ (out4 & (out5 ^ out6))) + + key[i]; // | 0; + + // shift register + out7 = out6; + out6 = out5; + out5 = out4; + + out4 = (out3 + tmp) | 0; + + out3 = out2; + out2 = out1; + out1 = out0; + + out0 = + (tmp + + ((out1 & out2) ^ (out3 & (out1 ^ out2))) + + ((out1 >>> 2) ^ + (out1 >>> 13) ^ + (out1 >>> 22) ^ + (out1 << 30) ^ + (out1 << 19) ^ + (out1 << 10))) | + 0; + } + + out[0] = (out[0] + out0) | 0; + out[1] = (out[1] + out1) | 0; + out[2] = (out[2] + out2) | 0; + out[3] = (out[3] + out3) | 0; + out[4] = (out[4] + out4) | 0; + out[5] = (out[5] + out5) | 0; + out[6] = (out[6] + out6) | 0; + out[7] = (out[7] + out7) | 0; + } + + const bytes = new Uint8Array(out.buffer); + reverse_endianness(bytes); + + return base64(bytes); +} + +/** The SHA-256 initialization vector */ +const init = new Uint32Array(8); + +/** The SHA-256 hash key */ +const key = new Uint32Array(64); + +/** Function to precompute init and key. */ +function precompute() { + /** @param {number} x */ + function frac(x) { + return (x - Math.floor(x)) * 0x100000000; + } + + let prime = 2; + + for (let i = 0; i < 64; prime++) { + let is_prime = true; + + for (let factor = 2; factor * factor <= prime; factor++) { + if (prime % factor === 0) { + is_prime = false; + + break; + } + } + + if (is_prime) { + if (i < 8) { + init[i] = frac(prime ** (1 / 2)); + } + + key[i] = frac(prime ** (1 / 3)); + + i++; + } + } +} + +/** @param {Uint8Array} bytes */ +function reverse_endianness(bytes) { + for (let i = 0; i < bytes.length; i += 4) { + const a = bytes[i + 0]; + const b = bytes[i + 1]; + const c = bytes[i + 2]; + const d = bytes[i + 3]; + + bytes[i + 0] = d; + bytes[i + 1] = c; + bytes[i + 2] = b; + bytes[i + 3] = a; + } +} + +/** @param {string} str */ +function encode(str) { + const encoded = encoder.encode(str); + const length = encoded.length * 8; + + // result should be a multiple of 512 bits in length, + // with room for a 1 (after the data) and two 32-bit + // words containing the original input bit length + const size = 512 * Math.ceil((length + 65) / 512); + const bytes = new Uint8Array(size / 8); + bytes.set(encoded); + + // append a 1 + bytes[encoded.length] = 0b10000000; + + reverse_endianness(bytes); + + // add the input bit length + const words = new Uint32Array(bytes.buffer); + words[words.length - 2] = Math.floor(length / 0x100000000); // this will always be zero for us + words[words.length - 1] = length; + + return words; +} + +/* + Based on https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727 + + MIT License + Copyright (c) 2020 Egor Nepomnyaschih + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** @param {Uint8Array} bytes */ +export function base64(bytes) { + const l = bytes.length; + + let result = ''; + let i; + + for (i = 2; i < l; i += 3) { + result += chars[bytes[i - 2] >> 2]; + result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += chars[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)]; + result += chars[bytes[i] & 0x3f]; + } + + if (i === l + 1) { + // 1 octet yet to write + result += chars[bytes[i - 2] >> 2]; + result += chars[(bytes[i - 2] & 0x03) << 4]; + result += '=='; + } + + if (i === l) { + // 2 octets yet to write + result += chars[bytes[i - 2] >> 2]; + result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += chars[(bytes[i - 1] & 0x0f) << 2]; + result += '='; + } + + return result; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/page/csp.js b/node_modules/@sveltejs/kit/src/runtime/server/page/csp.js new file mode 100644 index 00000000..547c43cd --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/page/csp.js @@ -0,0 +1,366 @@ +import { escape_html_attr } from '../../../utils/escape.js'; +import { base64, sha256 } from './crypto.js'; + +const array = new Uint8Array(16); + +function generate_nonce() { + crypto.getRandomValues(array); + return base64(array); +} + +const quoted = new Set([ + 'self', + 'unsafe-eval', + 'unsafe-hashes', + 'unsafe-inline', + 'none', + 'strict-dynamic', + 'report-sample', + 'wasm-unsafe-eval', + 'script' +]); + +const crypto_pattern = /^(nonce|sha\d\d\d)-/; + +// CSP and CSP Report Only are extremely similar with a few caveats +// the easiest/DRYest way to express this is with some private encapsulation +class BaseProvider { + /** @type {boolean} */ + #use_hashes; + + /** @type {boolean} */ + #script_needs_csp; + + /** @type {boolean} */ + #style_needs_csp; + + /** @type {import('types').CspDirectives} */ + #directives; + + /** @type {import('types').Csp.Source[]} */ + #script_src; + + /** @type {import('types').Csp.Source[]} */ + #script_src_elem; + + /** @type {import('types').Csp.Source[]} */ + #style_src; + + /** @type {import('types').Csp.Source[]} */ + #style_src_attr; + + /** @type {import('types').Csp.Source[]} */ + #style_src_elem; + + /** @type {string} */ + #nonce; + + /** + * @param {boolean} use_hashes + * @param {import('types').CspDirectives} directives + * @param {string} nonce + */ + constructor(use_hashes, directives, nonce) { + this.#use_hashes = use_hashes; + this.#directives = __SVELTEKIT_DEV__ ? { ...directives } : directives; // clone in dev so we can safely mutate + + const d = this.#directives; + + this.#script_src = []; + this.#script_src_elem = []; + this.#style_src = []; + this.#style_src_attr = []; + this.#style_src_elem = []; + + const effective_script_src = d['script-src'] || d['default-src']; + const script_src_elem = d['script-src-elem']; + const effective_style_src = d['style-src'] || d['default-src']; + const style_src_attr = d['style-src-attr']; + const style_src_elem = d['style-src-elem']; + + if (__SVELTEKIT_DEV__) { + // remove strict-dynamic in dev... + // TODO reinstate this if we can figure out how to make strict-dynamic work + // if (d['default-src']) { + // d['default-src'] = d['default-src'].filter((name) => name !== 'strict-dynamic'); + // if (d['default-src'].length === 0) delete d['default-src']; + // } + + // if (d['script-src']) { + // d['script-src'] = d['script-src'].filter((name) => name !== 'strict-dynamic'); + // if (d['script-src'].length === 0) delete d['script-src']; + // } + + // ...and add unsafe-inline so we can inject `; + } + + for (const dep of stylesheets) { + const path = prefixed(dep); + + const attributes = ['rel="stylesheet"']; + + if (inline_styles.has(dep)) { + // don't load stylesheets that are already inlined + // include them in disabled state so that Vite can detect them and doesn't try to add them + attributes.push('disabled', 'media="(max-width: 0)"'); + } else { + if (resolve_opts.preload({ type: 'css', path })) { + const preload_atts = ['rel="preload"', 'as="style"']; + link_header_preloads.add(`<${encodeURI(path)}>; ${preload_atts.join(';')}; nopush`); + } + } + + head += `\n\t\t`; + } + + for (const dep of fonts) { + const path = prefixed(dep); + + if (resolve_opts.preload({ type: 'font', path })) { + const ext = dep.slice(dep.lastIndexOf('.') + 1); + const attributes = [ + 'rel="preload"', + 'as="font"', + `type="font/${ext}"`, + `href="${path}"`, + 'crossorigin' + ]; + + head += `\n\t\t`; + } + } + + const global = __SVELTEKIT_DEV__ ? '__sveltekit_dev' : `__sveltekit_${options.version_hash}`; + + const { data, chunks } = get_data( + event, + options, + branch.map((b) => b.server_data), + global + ); + + if (page_config.ssr && page_config.csr) { + body += `\n\t\t\t${fetched + .map((item) => + serialize_data(item, resolve_opts.filterSerializedResponseHeaders, !!state.prerendering) + ) + .join('\n\t\t\t')}`; + } + + if (page_config.csr) { + if (client.uses_env_dynamic_public && state.prerendering) { + modulepreloads.add(`${options.app_dir}/env.js`); + } + + const included_modulepreloads = Array.from(modulepreloads, (dep) => prefixed(dep)).filter( + (path) => resolve_opts.preload({ type: 'js', path }) + ); + + for (const path of included_modulepreloads) { + // see the kit.output.preloadStrategy option for details on why we have multiple options here + link_header_preloads.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`); + if (options.preload_strategy !== 'modulepreload') { + head += `\n\t\t`; + } else if (state.prerendering) { + head += `\n\t\t`; + } + } + + const blocks = []; + + // when serving a prerendered page in an app that uses $env/dynamic/public, we must + // import the env.js module so that it evaluates before any user code can evaluate. + // TODO revert to using top-level await once https://bugs.webkit.org/show_bug.cgi?id=242740 is fixed + // https://github.com/sveltejs/kit/pull/11601 + const load_env_eagerly = client.uses_env_dynamic_public && state.prerendering; + + const properties = [`base: ${base_expression}`]; + + if (paths.assets) { + properties.push(`assets: ${s(paths.assets)}`); + } + + if (client.uses_env_dynamic_public) { + properties.push(`env: ${load_env_eagerly ? 'null' : s(public_env)}`); + } + + if (chunks) { + blocks.push('const deferred = new Map();'); + + properties.push(`defer: (id) => new Promise((fulfil, reject) => { + deferred.set(id, { fulfil, reject }); + })`); + + properties.push(`resolve: ({ id, data, error }) => { + const { fulfil, reject } = deferred.get(id); + deferred.delete(id); + + if (error) reject(error); + else fulfil(data); + }`); + } + + // create this before declaring `data`, which may contain references to `${global}` + blocks.push(`${global} = { + ${properties.join(',\n\t\t\t\t\t\t')} + };`); + + const args = ['app', 'element']; + + blocks.push('const element = document.currentScript.parentElement;'); + + if (page_config.ssr) { + const serialized = { form: 'null', error: 'null' }; + + blocks.push(`const data = ${data};`); + + if (form_value) { + serialized.form = uneval_action_response( + form_value, + /** @type {string} */ (event.route.id) + ); + } + + if (error) { + serialized.error = devalue.uneval(error); + } + + const hydrate = [ + `node_ids: [${branch.map(({ node }) => node.index).join(', ')}]`, + 'data', + `form: ${serialized.form}`, + `error: ${serialized.error}` + ]; + + if (status !== 200) { + hydrate.push(`status: ${status}`); + } + + if (options.embedded) { + hydrate.push(`params: ${devalue.uneval(event.params)}`, `route: ${s(event.route)}`); + } + + const indent = '\t'.repeat(load_env_eagerly ? 7 : 6); + args.push(`{\n${indent}\t${hydrate.join(`,\n${indent}\t`)}\n${indent}}`); + } + + if (load_env_eagerly) { + blocks.push(`import(${s(`${base}/${options.app_dir}/env.js`)}).then(({ env }) => { + ${global}.env = env; + + Promise.all([ + import(${s(prefixed(client.start))}), + import(${s(prefixed(client.app))}) + ]).then(([kit, app]) => { + kit.start(${args.join(', ')}); + }); + });`); + } else { + blocks.push(`Promise.all([ + import(${s(prefixed(client.start))}), + import(${s(prefixed(client.app))}) + ]).then(([kit, app]) => { + kit.start(${args.join(', ')}); + });`); + } + + if (options.service_worker) { + const opts = __SVELTEKIT_DEV__ ? ", { type: 'module' }" : ''; + + // we use an anonymous function instead of an arrow function to support + // older browsers (https://github.com/sveltejs/kit/pull/5417) + blocks.push(`if ('serviceWorker' in navigator) { + addEventListener('load', function () { + navigator.serviceWorker.register('${prefixed('service-worker.js')}'${opts}); + }); + }`); + } + + const init_app = ` + { + ${blocks.join('\n\n\t\t\t\t\t')} + } + `; + csp.add_script(init_app); + + body += `\n\t\t\t${init_app}\n\t\t`; + } + + const headers = new Headers({ + 'x-sveltekit-page': 'true', + 'content-type': 'text/html' + }); + + if (state.prerendering) { + // TODO read headers set with setHeaders and convert into http-equiv where possible + const http_equiv = []; + + const csp_headers = csp.csp_provider.get_meta(); + if (csp_headers) { + http_equiv.push(csp_headers); + } + + if (state.prerendering.cache) { + http_equiv.push(``); + } + + if (http_equiv.length > 0) { + head = http_equiv.join('\n') + head; + } + } else { + const csp_header = csp.csp_provider.get_header(); + if (csp_header) { + headers.set('content-security-policy', csp_header); + } + const report_only_header = csp.report_only_provider.get_header(); + if (report_only_header) { + headers.set('content-security-policy-report-only', report_only_header); + } + + if (link_header_preloads.size) { + headers.set('link', Array.from(link_header_preloads).join(', ')); + } + } + + // add the content after the script/css links so the link elements are parsed first + head += rendered.head; + + const html = options.templates.app({ + head, + body, + assets, + nonce: /** @type {string} */ (csp.nonce), + env: safe_public_env + }); + + // TODO flush chunks as early as we can + const transformed = + (await resolve_opts.transformPageChunk({ + html, + done: true + })) || ''; + + if (!chunks) { + headers.set('etag', `"${hash(transformed)}"`); + } + + if (DEV) { + if (page_config.csr) { + if (transformed.split('`, so the script element might be unexpectedly + * kept open until until an unrelated HTML comment in the page. + * + * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018 + * browsers. + * + * @see tests for unsafe parsing examples. + * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements + * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions + * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state + * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state + * @see https://github.com/tc39/proposal-json-superset + * @type {Record} + */ +const replacements = { + '<': '\\u003C', + '\u2028': '\\u2028', + '\u2029': '\\u2029' +}; + +const pattern = new RegExp(`[${Object.keys(replacements).join('')}]`, 'g'); + +/** + * Generates a raw HTML string containing a safe script element carrying data and associated attributes. + * + * It escapes all the special characters needed to guarantee the element is unbroken, but care must + * be taken to ensure it is inserted in the document at an acceptable position for a script element, + * and that the resulting string isn't further modified. + * + * @param {import('./types.js').Fetched} fetched + * @param {(name: string, value: string) => boolean} filter + * @param {boolean} [prerendering] + * @returns {string} The raw HTML of a script element carrying the JSON payload. + * @example const html = serialize_data('/data.json', null, { foo: 'bar' }); + */ +export function serialize_data(fetched, filter, prerendering = false) { + /** @type {Record} */ + const headers = {}; + + let cache_control = null; + let age = null; + let varyAny = false; + + for (const [key, value] of fetched.response.headers) { + if (filter(key, value)) { + headers[key] = value; + } + + if (key === 'cache-control') cache_control = value; + else if (key === 'age') age = value; + else if (key === 'vary' && value.trim() === '*') varyAny = true; + } + + const payload = { + status: fetched.response.status, + statusText: fetched.response.statusText, + headers, + body: fetched.response_body + }; + + const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]); + + const attrs = [ + 'type="application/json"', + 'data-sveltekit-fetched', + `data-url=${escape_html_attr(fetched.url)}` + ]; + + if (fetched.is_b64) { + attrs.push('data-b64'); + } + + if (fetched.request_headers || fetched.request_body) { + /** @type {import('types').StrictBody[]} */ + const values = []; + + if (fetched.request_headers) { + values.push([...new Headers(fetched.request_headers)].join(',')); + } + + if (fetched.request_body) { + values.push(fetched.request_body); + } + + attrs.push(`data-hash="${hash(...values)}"`); + } + + // Compute the time the response should be cached, taking into account max-age and age. + // Do not cache at all if a `Vary: *` header is present, as this indicates that the + // cache is likely to get busted. + if (!prerendering && fetched.method === 'GET' && cache_control && !varyAny) { + const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control); + if (match) { + const ttl = +match[1] - +(age ?? '0'); + attrs.push(`data-ttl="${ttl}"`); + } + } + + return ``; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/page/types.d.ts b/node_modules/@sveltejs/kit/src/runtime/server/page/types.d.ts new file mode 100644 index 00000000..7e501b1a --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/page/types.d.ts @@ -0,0 +1,36 @@ +import { CookieSerializeOptions } from 'cookie'; +import { SSRNode, CspDirectives, ServerDataNode } from 'types'; + +export interface Fetched { + url: string; + method: string; + request_body?: string | ArrayBufferView | null; + request_headers?: HeadersInit | undefined; + response_body: string; + response: Response; + is_b64?: boolean; +} + +export type Loaded = { + node: SSRNode; + data: Record | null; + server_data: ServerDataNode | null; +}; + +type CspMode = 'hash' | 'nonce' | 'auto'; + +export interface CspConfig { + mode: CspMode; + directives: CspDirectives; + reportOnly: CspDirectives; +} + +export interface CspOpts { + prerender: boolean; +} + +export interface Cookie { + name: string; + value: string; + options: CookieSerializeOptions & { path: string }; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/respond.js b/node_modules/@sveltejs/kit/src/runtime/server/respond.js new file mode 100644 index 00000000..f81f52ef --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/respond.js @@ -0,0 +1,558 @@ +import { DEV } from 'esm-env'; +import { base } from '__sveltekit/paths'; +import { is_endpoint_request, render_endpoint } from './endpoint.js'; +import { render_page } from './page/index.js'; +import { render_response } from './page/render.js'; +import { respond_with_error } from './page/respond_with_error.js'; +import { is_form_content_type } from '../../utils/http.js'; +import { handle_fatal_error, method_not_allowed, redirect_response } from './utils.js'; +import { + decode_pathname, + decode_params, + disable_search, + has_data_suffix, + normalize_path, + strip_data_suffix +} from '../../utils/url.js'; +import { exec } from '../../utils/routing.js'; +import { redirect_json_response, render_data } from './data/index.js'; +import { add_cookies_to_headers, get_cookies } from './cookie.js'; +import { create_fetch } from './fetch.js'; +import { HttpError, Redirect, SvelteKitError } from '../control.js'; +import { + validate_layout_exports, + validate_layout_server_exports, + validate_page_exports, + validate_page_server_exports, + validate_server_exports +} from '../../utils/exports.js'; +import { get_option } from '../../utils/options.js'; +import { json, text } from '../../exports/index.js'; +import { action_json_redirect, is_action_json_request } from './page/actions.js'; +import { INVALIDATED_PARAM, TRAILING_SLASH_PARAM } from '../shared.js'; +import { get_public_env } from './env_module.js'; +import { load_page_nodes } from './page/load_page_nodes.js'; +import { get_page_config } from '../../utils/route_config.js'; + +/* global __SVELTEKIT_ADAPTER_NAME__ */ + +/** @type {import('types').RequiredResolveOptions['transformPageChunk']} */ +const default_transform = ({ html }) => html; + +/** @type {import('types').RequiredResolveOptions['filterSerializedResponseHeaders']} */ +const default_filter = () => false; + +/** @type {import('types').RequiredResolveOptions['preload']} */ +const default_preload = ({ type }) => type === 'js' || type === 'css'; + +const page_methods = new Set(['GET', 'HEAD', 'POST']); + +const allowed_page_methods = new Set(['GET', 'HEAD', 'OPTIONS']); + +/** + * @param {Request} request + * @param {import('types').SSROptions} options + * @param {import('@sveltejs/kit').SSRManifest} manifest + * @param {import('types').SSRState} state + * @returns {Promise} + */ +export async function respond(request, options, manifest, state) { + /** URL but stripped from the potential `/__data.json` suffix and its search param */ + const url = new URL(request.url); + + if (options.csrf_check_origin) { + const forbidden = + is_form_content_type(request) && + (request.method === 'POST' || + request.method === 'PUT' || + request.method === 'PATCH' || + request.method === 'DELETE') && + request.headers.get('origin') !== url.origin; + + if (forbidden) { + const csrf_error = new HttpError( + 403, + `Cross-site ${request.method} form submissions are forbidden` + ); + if (request.headers.get('accept') === 'application/json') { + return json(csrf_error.body, { status: csrf_error.status }); + } + return text(csrf_error.body.message, { status: csrf_error.status }); + } + } + + // reroute could alter the given URL, so we pass a copy + let rerouted_path; + try { + rerouted_path = options.hooks.reroute({ url: new URL(url) }) ?? url.pathname; + } catch { + return text('Internal Server Error', { + status: 500 + }); + } + + let decoded; + try { + decoded = decode_pathname(rerouted_path); + } catch { + return text('Malformed URI', { status: 400 }); + } + + /** @type {import('types').SSRRoute | null} */ + let route = null; + + /** @type {Record} */ + let params = {}; + + if (base && !state.prerendering?.fallback) { + if (!decoded.startsWith(base)) { + return text('Not found', { status: 404 }); + } + decoded = decoded.slice(base.length) || '/'; + } + + if (decoded === `/${options.app_dir}/env.js`) { + return get_public_env(request); + } + + if (decoded.startsWith(`/${options.app_dir}`)) { + // Ensure that 404'd static assets are not cached - some adapters might apply caching by default + const headers = new Headers(); + headers.set('cache-control', 'public, max-age=0, must-revalidate'); + return text('Not found', { status: 404, headers }); + } + + const is_data_request = has_data_suffix(decoded); + /** @type {boolean[] | undefined} */ + let invalidated_data_nodes; + if (is_data_request) { + decoded = strip_data_suffix(decoded) || '/'; + url.pathname = + strip_data_suffix(url.pathname) + + (url.searchParams.get(TRAILING_SLASH_PARAM) === '1' ? '/' : '') || '/'; + url.searchParams.delete(TRAILING_SLASH_PARAM); + invalidated_data_nodes = url.searchParams + .get(INVALIDATED_PARAM) + ?.split('') + .map((node) => node === '1'); + url.searchParams.delete(INVALIDATED_PARAM); + } + + if (!state.prerendering?.fallback) { + // TODO this could theoretically break — should probably be inside a try-catch + const matchers = await manifest._.matchers(); + + for (const candidate of manifest._.routes) { + const match = candidate.pattern.exec(decoded); + if (!match) continue; + + const matched = exec(match, candidate.params, matchers); + if (matched) { + route = candidate; + params = decode_params(matched); + break; + } + } + } + + /** @type {import('types').TrailingSlash | void} */ + let trailing_slash = undefined; + + /** @type {Record} */ + const headers = {}; + + /** @type {Record} */ + let cookies_to_add = {}; + + /** @type {import('@sveltejs/kit').RequestEvent} */ + const event = { + // @ts-expect-error `cookies` and `fetch` need to be created after the `event` itself + cookies: null, + // @ts-expect-error + fetch: null, + getClientAddress: + state.getClientAddress || + (() => { + throw new Error( + `${__SVELTEKIT_ADAPTER_NAME__} does not specify getClientAddress. Please raise an issue` + ); + }), + locals: {}, + params, + platform: state.platform, + request, + route: { id: route?.id ?? null }, + setHeaders: (new_headers) => { + for (const key in new_headers) { + const lower = key.toLowerCase(); + const value = new_headers[key]; + + if (lower === 'set-cookie') { + throw new Error( + 'Use `event.cookies.set(name, value, options)` instead of `event.setHeaders` to set cookies' + ); + } else if (lower in headers) { + throw new Error(`"${key}" header is already set`); + } else { + headers[lower] = value; + + if (state.prerendering && lower === 'cache-control') { + state.prerendering.cache = /** @type {string} */ (value); + } + } + } + }, + url, + isDataRequest: is_data_request, + isSubRequest: state.depth > 0 + }; + + /** @type {import('types').RequiredResolveOptions} */ + let resolve_opts = { + transformPageChunk: default_transform, + filterSerializedResponseHeaders: default_filter, + preload: default_preload + }; + + try { + // determine whether we need to redirect to add/remove a trailing slash + if (route) { + // if `paths.base === '/a/b/c`, then the root route is `/a/b/c/`, + // regardless of the `trailingSlash` route option + if (url.pathname === base || url.pathname === base + '/') { + trailing_slash = 'always'; + } else if (route.page) { + const nodes = await load_page_nodes(route.page, manifest); + + if (DEV) { + const layouts = nodes.slice(0, -1); + const page = nodes.at(-1); + + for (const layout of layouts) { + if (layout) { + validate_layout_server_exports( + layout.server, + /** @type {string} */ (layout.server_id) + ); + validate_layout_exports( + layout.universal, + /** @type {string} */ (layout.universal_id) + ); + } + } + + if (page) { + validate_page_server_exports(page.server, /** @type {string} */ (page.server_id)); + validate_page_exports(page.universal, /** @type {string} */ (page.universal_id)); + } + } + + trailing_slash = get_option(nodes, 'trailingSlash'); + } else if (route.endpoint) { + const node = await route.endpoint(); + trailing_slash = node.trailingSlash; + + if (DEV) { + validate_server_exports(node, /** @type {string} */ (route.endpoint_id)); + } + } + + if (!is_data_request) { + const normalized = normalize_path(url.pathname, trailing_slash ?? 'never'); + + if (normalized !== url.pathname && !state.prerendering?.fallback) { + return new Response(undefined, { + status: 308, + headers: { + 'x-sveltekit-normalize': '1', + location: + // ensure paths starting with '//' are not treated as protocol-relative + (normalized.startsWith('//') ? url.origin + normalized : normalized) + + (url.search === '?' ? '' : url.search) + } + }); + } + } + + if (state.before_handle || state.emulator?.platform) { + let config = {}; + + /** @type {import('types').PrerenderOption} */ + let prerender = false; + + if (route.endpoint) { + const node = await route.endpoint(); + config = node.config ?? config; + prerender = node.prerender ?? prerender; + } else if (route.page) { + const nodes = await load_page_nodes(route.page, manifest); + config = get_page_config(nodes) ?? config; + prerender = get_option(nodes, 'prerender') ?? false; + } + + if (state.before_handle) { + state.before_handle(event, config, prerender); + } + + if (state.emulator?.platform) { + event.platform = await state.emulator.platform({ config, prerender }); + } + } + } else if (state.emulator?.platform) { + event.platform = await state.emulator.platform({ + config: {}, + prerender: !!state.prerendering?.fallback + }); + } + + const { cookies, new_cookies, get_cookie_header, set_internal } = get_cookies( + request, + url, + trailing_slash ?? 'never' + ); + + cookies_to_add = new_cookies; + event.cookies = cookies; + event.fetch = create_fetch({ + event, + options, + manifest, + state, + get_cookie_header, + set_internal + }); + + if (state.prerendering && !state.prerendering.fallback) disable_search(url); + + const response = await options.hooks.handle({ + event, + resolve: (event, opts) => + resolve(event, opts).then((response) => { + // add headers/cookies here, rather than inside `resolve`, so that we + // can do it once for all responses instead of once per `return` + for (const key in headers) { + const value = headers[key]; + response.headers.set(key, /** @type {string} */ (value)); + } + + add_cookies_to_headers(response.headers, Object.values(cookies_to_add)); + + if (state.prerendering && event.route.id !== null) { + response.headers.set('x-sveltekit-routeid', encodeURI(event.route.id)); + } + + return response; + }) + }); + + // respond with 304 if etag matches + if (response.status === 200 && response.headers.has('etag')) { + let if_none_match_value = request.headers.get('if-none-match'); + + // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives + if (if_none_match_value?.startsWith('W/"')) { + if_none_match_value = if_none_match_value.substring(2); + } + + const etag = /** @type {string} */ (response.headers.get('etag')); + + if (if_none_match_value === etag) { + const headers = new Headers({ etag }); + + // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1 + set-cookie + for (const key of [ + 'cache-control', + 'content-location', + 'date', + 'expires', + 'vary', + 'set-cookie' + ]) { + const value = response.headers.get(key); + if (value) headers.set(key, value); + } + + return new Response(undefined, { + status: 304, + headers + }); + } + } + + // Edge case: If user does `return Response(30x)` in handle hook while processing a data request, + // we need to transform the redirect response to a corresponding JSON response. + if (is_data_request && response.status >= 300 && response.status <= 308) { + const location = response.headers.get('location'); + if (location) { + return redirect_json_response(new Redirect(/** @type {any} */ (response.status), location)); + } + } + + return response; + } catch (e) { + if (e instanceof Redirect) { + const response = is_data_request + ? redirect_json_response(e) + : route?.page && is_action_json_request(event) + ? action_json_redirect(e) + : redirect_response(e.status, e.location); + add_cookies_to_headers(response.headers, Object.values(cookies_to_add)); + return response; + } + return await handle_fatal_error(event, options, e); + } + + /** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('@sveltejs/kit').ResolveOptions} [opts] + */ + async function resolve(event, opts) { + try { + if (opts) { + resolve_opts = { + transformPageChunk: opts.transformPageChunk || default_transform, + filterSerializedResponseHeaders: opts.filterSerializedResponseHeaders || default_filter, + preload: opts.preload || default_preload + }; + } + + if (state.prerendering?.fallback) { + return await render_response({ + event, + options, + manifest, + state, + page_config: { ssr: false, csr: true }, + status: 200, + error: null, + branch: [], + fetched: [], + resolve_opts + }); + } + + if (route) { + const method = /** @type {import('types').HttpMethod} */ (event.request.method); + + /** @type {Response} */ + let response; + + if (is_data_request) { + response = await render_data( + event, + route, + options, + manifest, + state, + invalidated_data_nodes, + trailing_slash ?? 'never' + ); + } else if (route.endpoint && (!route.page || is_endpoint_request(event))) { + response = await render_endpoint(event, await route.endpoint(), state); + } else if (route.page) { + if (page_methods.has(method)) { + response = await render_page(event, route.page, options, manifest, state, resolve_opts); + } else { + const allowed_methods = new Set(allowed_page_methods); + const node = await manifest._.nodes[route.page.leaf](); + if (node?.server?.actions) { + allowed_methods.add('POST'); + } + + if (method === 'OPTIONS') { + // This will deny CORS preflight requests implicitly because we don't + // add the required CORS headers to the response. + response = new Response(null, { + status: 204, + headers: { + allow: Array.from(allowed_methods.values()).join(', ') + } + }); + } else { + const mod = [...allowed_methods].reduce((acc, curr) => { + acc[curr] = true; + return acc; + }, /** @type {Record} */ ({})); + response = method_not_allowed(mod, method); + } + } + } else { + // a route will always have a page or an endpoint, but TypeScript + // doesn't know that + throw new Error('This should never happen'); + } + + // If the route contains a page and an endpoint, we need to add a + // `Vary: Accept` header to the response because of browser caching + if (request.method === 'GET' && route.page && route.endpoint) { + const vary = response.headers + .get('vary') + ?.split(',') + ?.map((v) => v.trim().toLowerCase()); + if (!(vary?.includes('accept') || vary?.includes('*'))) { + // the returned response might have immutable headers, + // so we have to clone them before trying to mutate them + response = new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers: new Headers(response.headers) + }); + response.headers.append('Vary', 'Accept'); + } + } + + return response; + } + + if (state.error && event.isSubRequest) { + return await fetch(request, { + headers: { + 'x-sveltekit-error': 'true' + } + }); + } + + if (state.error) { + return text('Internal Server Error', { + status: 500 + }); + } + + // if this request came direct from the user, rather than + // via our own `fetch`, render a 404 page + if (state.depth === 0) { + return await respond_with_error({ + event, + options, + manifest, + state, + status: 404, + error: new SvelteKitError(404, 'Not Found', `Not found: ${event.url.pathname}`), + resolve_opts + }); + } + + if (state.prerendering) { + return text('not found', { status: 404 }); + } + + // we can't load the endpoint from our own manifest, + // so we need to make an actual HTTP request + return await fetch(request); + } catch (e) { + // TODO if `e` is instead named `error`, some fucked up Vite transformation happens + // and I don't even know how to describe it. need to investigate at some point + + // HttpError from endpoint can end up here - TODO should it be handled there instead? + return await handle_fatal_error(event, options, e); + } finally { + event.cookies.set = () => { + throw new Error('Cannot use `cookies.set(...)` after the response has been generated'); + }; + + event.setHeaders = () => { + throw new Error('Cannot use `setHeaders(...)` after the response has been generated'); + }; + } + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/utils.js b/node_modules/@sveltejs/kit/src/runtime/server/utils.js new file mode 100644 index 00000000..12cb4928 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/utils.js @@ -0,0 +1,178 @@ +import { DEV } from 'esm-env'; +import { json, text } from '../../exports/index.js'; +import { coalesce_to_error, get_message, get_status } from '../../utils/error.js'; +import { negotiate } from '../../utils/http.js'; +import { HttpError } from '../control.js'; +import { fix_stack_trace } from '../shared-server.js'; +import { ENDPOINT_METHODS } from '../../constants.js'; + +/** @param {any} body */ +export function is_pojo(body) { + if (typeof body !== 'object') return false; + + if (body) { + if (body instanceof Uint8Array) return false; + if (body instanceof ReadableStream) return false; + } + + return true; +} + +/** + * @param {Partial>} mod + * @param {import('types').HttpMethod} method + */ +export function method_not_allowed(mod, method) { + return text(`${method} method not allowed`, { + status: 405, + headers: { + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 + // "The server must generate an Allow header field in a 405 status code response" + allow: allowed_methods(mod).join(', ') + } + }); +} + +/** @param {Partial>} mod */ +export function allowed_methods(mod) { + const allowed = ENDPOINT_METHODS.filter((method) => method in mod); + + if ('GET' in mod || 'HEAD' in mod) allowed.push('HEAD'); + + return allowed; +} + +/** + * Return as a response that renders the error.html + * + * @param {import('types').SSROptions} options + * @param {number} status + * @param {string} message + */ +export function static_error_page(options, status, message) { + let page = options.templates.error({ status, message }); + + if (DEV) { + // inject Vite HMR client, for easier debugging + page = page.replace('', ''); + } + + return text(page, { + headers: { 'content-type': 'text/html; charset=utf-8' }, + status + }); +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSROptions} options + * @param {unknown} error + */ +export async function handle_fatal_error(event, options, error) { + error = error instanceof HttpError ? error : coalesce_to_error(error); + const status = get_status(error); + const body = await handle_error_and_jsonify(event, options, error); + + // ideally we'd use sec-fetch-dest instead, but Safari — quelle surprise — doesn't support it + const type = negotiate(event.request.headers.get('accept') || 'text/html', [ + 'application/json', + 'text/html' + ]); + + if (event.isDataRequest || type === 'application/json') { + return json(body, { + status + }); + } + + return static_error_page(options, status, body.message); +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSROptions} options + * @param {any} error + * @returns {Promise} + */ +export async function handle_error_and_jsonify(event, options, error) { + if (error instanceof HttpError) { + return error.body; + } + + if (__SVELTEKIT_DEV__ && typeof error == 'object') { + fix_stack_trace(error); + } + + const status = get_status(error); + const message = get_message(error); + + return (await options.hooks.handleError({ error, event, status, message })) ?? { message }; +} + +/** + * @param {number} status + * @param {string} location + */ +export function redirect_response(status, location) { + const response = new Response(undefined, { + status, + headers: { location } + }); + return response; +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {Error & { path: string }} error + */ +export function clarify_devalue_error(event, error) { + if (error.path) { + return `Data returned from \`load\` while rendering ${event.route.id} is not serializable: ${error.message} (data${error.path})`; + } + + if (error.path === '') { + return `Data returned from \`load\` while rendering ${event.route.id} is not a plain object`; + } + + // belt and braces — this should never happen + return error.message; +} + +/** + * @param {import('types').ServerDataNode} node + */ +export function stringify_uses(node) { + const uses = []; + + if (node.uses && node.uses.dependencies.size > 0) { + uses.push(`"dependencies":${JSON.stringify(Array.from(node.uses.dependencies))}`); + } + + if (node.uses && node.uses.search_params.size > 0) { + uses.push(`"search_params":${JSON.stringify(Array.from(node.uses.search_params))}`); + } + + if (node.uses && node.uses.params.size > 0) { + uses.push(`"params":${JSON.stringify(Array.from(node.uses.params))}`); + } + + if (node.uses?.parent) uses.push('"parent":1'); + if (node.uses?.route) uses.push('"route":1'); + if (node.uses?.url) uses.push('"url":1'); + + return `"uses":{${uses.join(',')}}`; +} + +/** + * @param {string} message + * @param {number} offset + */ +export function warn_with_callsite(message, offset = 0) { + if (DEV) { + const stack = fix_stack_trace(new Error()).split('\n'); + const line = stack.at(3 + offset); + message += `\n${line}`; + } + + console.warn(message); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/shared-server.js b/node_modules/@sveltejs/kit/src/runtime/shared-server.js new file mode 100644 index 00000000..7bd6bde4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/shared-server.js @@ -0,0 +1,40 @@ +/** + * `$env/dynamic/private` + * @type {Record} + */ +export let private_env = {}; + +/** + * `$env/dynamic/public`. When prerendering, this will be a proxy that forbids reads + * @type {Record} + */ +export let public_env = {}; + +/** + * The same as `public_env`, but without the proxy. Use for `%sveltekit.env.PUBLIC_FOO%` + * @type {Record} + */ +export let safe_public_env = {}; + +/** @param {any} error */ +export let fix_stack_trace = (error) => error?.stack; + +/** @type {(environment: Record) => void} */ +export function set_private_env(environment) { + private_env = environment; +} + +/** @type {(environment: Record) => void} */ +export function set_public_env(environment) { + public_env = environment; +} + +/** @type {(environment: Record) => void} */ +export function set_safe_public_env(environment) { + safe_public_env = environment; +} + +/** @param {(error: Error) => string} value */ +export function set_fix_stack_trace(value) { + fix_stack_trace = value; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/shared.js b/node_modules/@sveltejs/kit/src/runtime/shared.js new file mode 100644 index 00000000..b5c559b4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/shared.js @@ -0,0 +1,16 @@ +/** + * @param {string} route_id + * @param {string} dep + */ +export function validate_depends(route_id, dep) { + const match = /^(moz-icon|view-source|jar):/.exec(dep); + if (match) { + console.warn( + `${route_id}: Calling \`depends('${dep}')\` will throw an error in Firefox because \`${match[1]}\` is a special URI scheme` + ); + } +} + +export const INVALIDATED_PARAM = 'x-sveltekit-invalidated'; + +export const TRAILING_SLASH_PARAM = 'x-sveltekit-trailing-slash'; diff --git a/node_modules/@sveltejs/kit/src/runtime/utils.js b/node_modules/@sveltejs/kit/src/runtime/utils.js new file mode 100644 index 00000000..f73f5372 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/utils.js @@ -0,0 +1,34 @@ +/** + * @param {string} text + * @returns {ArrayBufferLike} + */ +export function b64_decode(text) { + const d = atob(text); + + const u8 = new Uint8Array(d.length); + + for (let i = 0; i < d.length; i++) { + u8[i] = d.charCodeAt(i); + } + + return u8.buffer; +} + +/** + * @param {ArrayBuffer} buffer + * @returns {string} + */ +export function b64_encode(buffer) { + if (globalThis.Buffer) { + return Buffer.from(buffer).toString('base64'); + } + + const little_endian = new Uint8Array(new Uint16Array([1]).buffer)[0] > 0; + + // The Uint16Array(Uint8Array(...)) ensures the code points are padded with 0's + return btoa( + new TextDecoder(little_endian ? 'utf-16le' : 'utf-16be').decode( + new Uint16Array(new Uint8Array(buffer)) + ) + ); +} diff --git a/node_modules/@sveltejs/kit/src/types/ambient-private.d.ts b/node_modules/@sveltejs/kit/src/types/ambient-private.d.ts new file mode 100644 index 00000000..4f149147 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/ambient-private.d.ts @@ -0,0 +1,28 @@ +/** Internal version of $app/environment */ +declare module '__sveltekit/environment' { + export const building: boolean; + export const prerendering: boolean; + export const version: string; + export function set_building(): void; + export function set_prerendering(): void; +} + +/** Internal version of $app/paths */ +declare module '__sveltekit/paths' { + export let base: '' | `/${string}`; + export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; + export let relative: boolean; + export function reset(): void; + export function override(paths: { base: string; assets: string }): void; + export function set_assets(path: string): void; +} + +/** Internal version of $app/server */ +declare module '__sveltekit/server' { + import { SSRManifest } from '@sveltejs/kit'; + + export let manifest: SSRManifest; + export function read_implementation(path: string): ReadableStream; + export function set_manifest(manifest: SSRManifest): void; + export function set_read_implementation(fn: (path: string) => ReadableStream): void; +} diff --git a/node_modules/@sveltejs/kit/src/types/ambient.d.ts b/node_modules/@sveltejs/kit/src/types/ambient.d.ts new file mode 100644 index 00000000..00730946 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/ambient.d.ts @@ -0,0 +1,81 @@ +/** + * It's possible to tell SvelteKit how to type objects inside your app by declaring the `App` namespace. By default, a new project will have a file called `src/app.d.ts` containing the following: + * + * ```ts + * declare global { + * namespace App { + * // interface Error {} + * // interface Locals {} + * // interface PageData {} + * // interface PageState {} + * // interface Platform {} + * } + * } + * + * export {}; + * ``` + * + * The `export {}` line exists because without it, the file would be treated as an _ambient module_ which prevents you from adding `import` declarations. + * If you need to add ambient `declare module` declarations, do so in a separate file like `src/ambient.d.ts`. + * + * By populating these interfaces, you will gain type safety when using `event.locals`, `event.platform`, and `data` from `load` functions. + */ +declare namespace App { + /** + * Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape. + */ + export interface Error { + message: string; + } + + /** + * The interface that defines `event.locals`, which can be accessed in [hooks](https://kit.svelte.dev/docs/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. + */ + export interface Locals {} + + /** + * Defines the common shape of the [$page.data store](https://kit.svelte.dev/docs/modules#$app-stores-page) - that is, the data that is shared between all pages. + * The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly. + * Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`). + */ + export interface PageData {} + + /** + * The shape of the `$page.state` object, which can be manipulated using the [`pushState`](https://kit.svelte.dev/docs/modules#$app-navigation-pushstate) and [`replaceState`](https://kit.svelte.dev/docs/modules#$app-navigation-replacestate) functions from `$app/navigation`. + */ + export interface PageState {} + + /** + * If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. + */ + export interface Platform {} +} + +/** + * This module is only available to [service workers](https://kit.svelte.dev/docs/service-workers). + */ +declare module '$service-worker' { + /** + * The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory. + * Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified. + */ + export const base: string; + /** + * An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. + * During development, this is an empty array. + */ + export const build: string[]; + /** + * An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](https://kit.svelte.dev/docs/configuration) + */ + export const files: string[]; + /** + * An array of pathnames corresponding to prerendered pages and endpoints. + * During development, this is an empty array. + */ + export const prerendered: string[]; + /** + * See [`config.kit.version`](https://kit.svelte.dev/docs/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches. + */ + export const version: string; +} diff --git a/node_modules/@sveltejs/kit/src/types/global-private.d.ts b/node_modules/@sveltejs/kit/src/types/global-private.d.ts new file mode 100644 index 00000000..66e1d41e --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/global-private.d.ts @@ -0,0 +1,26 @@ +declare global { + const __SVELTEKIT_ADAPTER_NAME__: string; + const __SVELTEKIT_APP_VERSION_FILE__: string; + const __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: number; + const __SVELTEKIT_DEV__: boolean; + const __SVELTEKIT_EMBEDDED__: boolean; + /** + * This makes the use of specific features visible at both dev and build time, in such a + * way that we can error when they are not supported by the target platform. + * + * During dev, `globalThis.__SVELTEKIT_TRACK__` is a function that grabs the current `event` + * and route `config` (from an AsyncLocalStorage instance) and calls the relevant `supports` + * function on the adapter (e.g. `adapter.supports.read(...)`). + * + * At build time, if the function containing the `__SVELTEKIT_TRACK__` call is untreeshaken, + * we locate it in the `renderChunk` build hook and a) make a note of the chunk that contains + * it and b) replace it with a comment. Later, we can use this information to establish + * which routes use which feature, and use the same `adapter.supports.read(...)` function + * to throw an error if the feature would fail in production. + */ + var __SVELTEKIT_TRACK__: (label: string) => void; + var Bun: object; + var Deno: object; +} + +export {}; diff --git a/node_modules/@sveltejs/kit/src/types/internal.d.ts b/node_modules/@sveltejs/kit/src/types/internal.d.ts new file mode 100644 index 00000000..c9dbb51c --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/internal.d.ts @@ -0,0 +1,449 @@ +import { SvelteComponent } from 'svelte'; +import { + Config, + ServerLoad, + Handle, + HandleServerError, + KitConfig, + Load, + RequestHandler, + ResolveOptions, + Server, + ServerInitOptions, + HandleFetch, + Actions, + HandleClientError, + Reroute, + RequestEvent, + SSRManifest, + Emulator, + Adapter +} from '@sveltejs/kit'; +import { + HttpMethod, + MaybePromise, + PrerenderOption, + RequestOptions, + TrailingSlash +} from './private.js'; + +export interface ServerModule { + Server: typeof InternalServer; +} + +export interface ServerInternalModule { + set_assets(path: string): void; + set_building(): void; + set_manifest(manifest: SSRManifest): void; + set_prerendering(): void; + set_private_env(environment: Record): void; + set_public_env(environment: Record): void; + set_read_implementation(implementation: (path: string) => ReadableStream): void; + set_safe_public_env(environment: Record): void; + set_version(version: string): void; + set_fix_stack_trace(fix_stack_trace: (error: unknown) => string): void; +} + +export interface Asset { + file: string; + size: number; + type: string | null; +} + +export interface AssetDependencies { + assets: string[]; + file: string; + imports: string[]; + stylesheets: string[]; + fonts: string[]; +} + +export interface BuildData { + app_dir: string; + app_path: string; + manifest_data: ManifestData; + out_dir: string; + service_worker: string | null; + client: { + start: string; + app: string; + imports: string[]; + stylesheets: string[]; + fonts: string[]; + uses_env_dynamic_public: boolean; + } | null; + server_manifest: import('vite').Manifest; +} + +export interface CSRPageNode { + component: typeof SvelteComponent; + universal: { + load?: Load; + trailingSlash?: TrailingSlash; + }; +} + +export type CSRPageNodeLoader = () => Promise; + +/** + * Definition of a client side route. + * The boolean in the tuples indicates whether the route has a server load. + */ +export type CSRRoute = { + id: string; + exec(path: string): undefined | Record; + errors: Array; + layouts: Array<[has_server_load: boolean, node_loader: CSRPageNodeLoader] | undefined>; + leaf: [has_server_load: boolean, node_loader: CSRPageNodeLoader]; +}; + +export interface Deferred { + fulfil: (value: any) => void; + reject: (error: Error) => void; +} + +export type GetParams = (match: RegExpExecArray) => Record; + +export interface ServerHooks { + handleFetch: HandleFetch; + handle: Handle; + handleError: HandleServerError; + reroute: Reroute; +} + +export interface ClientHooks { + handleError: HandleClientError; + reroute: Reroute; +} + +export interface Env { + private: Record; + public: Record; +} + +export class InternalServer extends Server { + init(options: ServerInitOptions): Promise; + respond( + request: Request, + options: RequestOptions & { + prerendering?: PrerenderOptions; + read: (file: string) => Buffer; + /** A hook called before `handle` during dev, so that `AsyncLocalStorage` can be populated */ + before_handle?: (event: RequestEvent, config: any, prerender: PrerenderOption) => void; + emulator?: Emulator; + } + ): Promise; +} + +export interface ManifestData { + assets: Asset[]; + hooks: { + client: string | null; + server: string | null; + universal: string | null; + }; + nodes: PageNode[]; + routes: RouteData[]; + matchers: Record; +} + +export interface PageNode { + depth: number; + /** The +page.svelte */ + component?: string; // TODO supply default component if it's missing (bit of an edge case) + /** The +page.js/.ts */ + universal?: string; + /** The +page.server.js/ts */ + server?: string; + parent_id?: string; + parent?: PageNode; + /** Filled with the pages that reference this layout (if this is a layout) */ + child_pages?: PageNode[]; +} + +export interface PrerenderDependency { + response: Response; + body: null | string | Uint8Array; +} + +export interface PrerenderOptions { + cache?: string; // including this here is a bit of a hack, but it makes it easy to add + fallback?: boolean; + dependencies: Map; +} + +export type RecursiveRequired = { + // Recursive implementation of TypeScript's Required utility type. + // Will recursively continue until it reaches a primitive or Function + [K in keyof T]-?: Extract extends never // If it does not have a Function type + ? RecursiveRequired // recursively continue through. + : T[K]; // Use the exact type for everything else +}; + +export type RequiredResolveOptions = Required; + +export interface RouteParam { + name: string; + matcher: string; + optional: boolean; + rest: boolean; + chained: boolean; +} + +/** + * Represents a route segment in the app. It can either be an intermediate node + * with only layout/error pages, or a leaf, at which point either `page` and `leaf` + * or `endpoint` is set. + */ +export interface RouteData { + id: string; + parent: RouteData | null; + + segment: string; + pattern: RegExp; + params: RouteParam[]; + + layout: PageNode | null; + error: PageNode | null; + leaf: PageNode | null; + + page: { + layouts: Array; + errors: Array; + leaf: number; + } | null; + + endpoint: { + file: string; + } | null; +} + +export type ServerRedirectNode = { + type: 'redirect'; + location: string; +}; + +export type ServerNodesResponse = { + type: 'data'; + /** + * If `null`, then there was no load function <- TODO is this outdated now with the recent changes? + */ + nodes: Array; +}; + +export type ServerDataResponse = ServerRedirectNode | ServerNodesResponse; + +/** + * Signals a successful response of the server `load` function. + * The `uses` property tells the client when it's possible to reuse this data + * in a subsequent request. + */ +export interface ServerDataNode { + type: 'data'; + /** + * The serialized version of this contains a serialized representation of any deferred promises, + * which will be resolved later through chunk nodes. + */ + data: Record | null; + uses: Uses; + slash?: TrailingSlash; +} + +/** + * Resolved data/error of a deferred promise. + */ +export interface ServerDataChunkNode { + type: 'chunk'; + id: number; + data?: Record; + error?: any; +} + +/** + * Signals that the server `load` function was not run, and the + * client should use what it has in memory + */ +export interface ServerDataSkippedNode { + type: 'skip'; +} + +/** + * Signals that the server `load` function failed + */ +export interface ServerErrorNode { + type: 'error'; + error: App.Error; + /** + * Only set for HttpErrors + */ + status?: number; +} + +export interface ServerMetadataRoute { + config: any; + api: { + methods: Array; + }; + page: { + methods: Array<'GET' | 'POST'>; + }; + methods: Array; + prerender: PrerenderOption | undefined; + entries: string[] | undefined; +} + +export interface ServerMetadata { + nodes: Array<{ has_server_load: boolean }>; + routes: Map; +} + +export interface SSRComponent { + default: { + render(props: Record): { + html: string; + head: string; + css: { + code: string; + map: any; // TODO + }; + }; + }; +} + +export type SSRComponentLoader = () => Promise; + +export interface SSRNode { + component: SSRComponentLoader; + /** index into the `components` array in client/manifest.js */ + index: number; + /** external JS files */ + imports: string[]; + /** external CSS files */ + stylesheets: string[]; + /** external font files */ + fonts: string[]; + /** inlined styles */ + inline_styles?(): MaybePromise>; + + universal: { + load?: Load; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + server: { + load?: ServerLoad; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + actions?: Actions; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + universal_id: string; + server_id: string; +} + +export type SSRNodeLoader = () => Promise; + +export interface SSROptions { + app_dir: string; + app_template_contains_nonce: boolean; + csp: ValidatedConfig['kit']['csp']; + csrf_check_origin: boolean; + embedded: boolean; + env_public_prefix: string; + env_private_prefix: string; + hooks: ServerHooks; + preload_strategy: ValidatedConfig['kit']['output']['preloadStrategy']; + root: SSRComponent['default']; + service_worker: boolean; + templates: { + app(values: { + head: string; + body: string; + assets: string; + nonce: string; + env: Record; + }): string; + error(values: { message: string; status: number }): string; + }; + version_hash: string; +} + +export interface PageNodeIndexes { + errors: Array; + layouts: Array; + leaf: number; +} + +export type PrerenderEntryGenerator = () => MaybePromise>>; + +export type SSREndpoint = Partial> & { + prerender?: PrerenderOption; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; + fallback?: RequestHandler; +}; + +export interface SSRRoute { + id: string; + pattern: RegExp; + params: RouteParam[]; + page: PageNodeIndexes | null; + endpoint: (() => Promise) | null; + endpoint_id?: string; +} + +export interface SSRState { + fallback?: string; + getClientAddress(): string; + /** + * True if we're currently attempting to render an error page + */ + error: boolean; + /** + * Allows us to prevent `event.fetch` from making infinitely looping internal requests + */ + depth: number; + platform?: any; + prerendering?: PrerenderOptions; + /** + * When fetching data from a +server.js endpoint in `load`, the page's + * prerender option is inherited by the endpoint, unless overridden + */ + prerender_default?: PrerenderOption; + read?: (file: string) => Buffer; + before_handle?: (event: RequestEvent, config: any, prerender: PrerenderOption) => void; + emulator?: Emulator; +} + +export type StrictBody = string | ArrayBufferView; + +export interface Uses { + dependencies: Set; + params: Set; + parent: boolean; + route: boolean; + url: boolean; + search_params: Set; +} + +export type ValidatedConfig = Config & { + kit: ValidatedKitConfig; + extensions: string[]; +}; + +export type ValidatedKitConfig = Omit, 'adapter'> & { + adapter?: Adapter; +}; + +export * from '../exports/index.js'; +export * from './private.js'; diff --git a/node_modules/@sveltejs/kit/src/types/private.d.ts b/node_modules/@sveltejs/kit/src/types/private.d.ts new file mode 100644 index 00000000..0207a8f5 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/private.d.ts @@ -0,0 +1,234 @@ +// This module contains types that are visible in the documentation, +// but which cannot be imported from `@sveltejs/kit`. Care should +// be taken to avoid breaking changes when editing this file + +import { RouteDefinition } from '@sveltejs/kit'; + +export interface AdapterEntry { + /** + * A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication. + * For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both + * be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID + */ + id: string; + + /** + * A function that compares the candidate route with the current route to determine + * if it should be grouped with the current route. + * + * Use cases: + * - Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes + * - Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function + */ + filter(route: RouteDefinition): boolean; + + /** + * A function that is invoked once the entry has been created. This is where you + * should write the function to the filesystem and generate redirect manifests. + */ + complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise; +} + +// Based on https://github.com/josh-hemphill/csp-typed-directives/blob/latest/src/csp.types.ts +// +// MIT License +// +// Copyright (c) 2021-present, Joshua Hemphill +// Copyright (c) 2021, Tecnico Corporation +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +export namespace Csp { + type ActionSource = 'strict-dynamic' | 'report-sample'; + type BaseSource = + | 'self' + | 'unsafe-eval' + | 'unsafe-hashes' + | 'unsafe-inline' + | 'wasm-unsafe-eval' + | 'none'; + type CryptoSource = `${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`; + type FrameSource = HostSource | SchemeSource | 'self' | 'none'; + type HostNameScheme = `${string}.${string}` | 'localhost'; + type HostSource = `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`; + type HostProtocolSchemes = `${string}://` | ''; + type HttpDelineator = '/' | '?' | '#' | '\\'; + type PortScheme = `:${number}` | '' | ':*'; + type SchemeSource = 'http:' | 'https:' | 'data:' | 'mediastream:' | 'blob:' | 'filesystem:'; + type Source = HostSource | SchemeSource | CryptoSource | BaseSource; + type Sources = Source[]; +} + +export interface CspDirectives { + 'child-src'?: Csp.Sources; + 'default-src'?: Array; + 'frame-src'?: Csp.Sources; + 'worker-src'?: Csp.Sources; + 'connect-src'?: Csp.Sources; + 'font-src'?: Csp.Sources; + 'img-src'?: Csp.Sources; + 'manifest-src'?: Csp.Sources; + 'media-src'?: Csp.Sources; + 'object-src'?: Csp.Sources; + 'prefetch-src'?: Csp.Sources; + 'script-src'?: Array; + 'script-src-elem'?: Csp.Sources; + 'script-src-attr'?: Csp.Sources; + 'style-src'?: Array; + 'style-src-elem'?: Csp.Sources; + 'style-src-attr'?: Csp.Sources; + 'base-uri'?: Array; + sandbox?: Array< + | 'allow-downloads-without-user-activation' + | 'allow-forms' + | 'allow-modals' + | 'allow-orientation-lock' + | 'allow-pointer-lock' + | 'allow-popups' + | 'allow-popups-to-escape-sandbox' + | 'allow-presentation' + | 'allow-same-origin' + | 'allow-scripts' + | 'allow-storage-access-by-user-activation' + | 'allow-top-navigation' + | 'allow-top-navigation-by-user-activation' + >; + 'form-action'?: Array; + 'frame-ancestors'?: Array; + 'navigate-to'?: Array; + 'report-uri'?: string[]; + 'report-to'?: string[]; + + 'require-trusted-types-for'?: Array<'script'>; + 'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>; + 'upgrade-insecure-requests'?: boolean; + + /** @deprecated */ + 'require-sri-for'?: Array<'script' | 'style' | 'script style'>; + + /** @deprecated */ + 'block-all-mixed-content'?: boolean; + + /** @deprecated */ + 'plugin-types'?: Array<`${string}/${string}` | 'none'>; + + /** @deprecated */ + referrer?: Array< + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url' + | 'none' + >; +} + +export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; + +export interface Logger { + (msg: string): void; + success(msg: string): void; + error(msg: string): void; + warn(msg: string): void; + minor(msg: string): void; + info(msg: string): void; +} + +export type MaybePromise = T | Promise; + +export interface Prerendered { + /** + * A map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo.html` and a path like `/bar/` corresponds to `bar/index.html`. + */ + pages: Map< + string, + { + /** The location of the .html file relative to the output directory */ + file: string; + } + >; + /** + * A map of `path` to `{ type }` objects. + */ + assets: Map< + string, + { + /** The MIME type of the asset */ + type: string; + } + >; + /** + * A map of redirects encountered during prerendering. + */ + redirects: Map< + string, + { + status: number; + location: string; + } + >; + /** An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config) */ + paths: string[]; +} + +export interface PrerenderHttpErrorHandler { + (details: { + status: number; + path: string; + referrer: string | null; + referenceType: 'linked' | 'fetched'; + message: string; + }): void; +} + +export interface PrerenderMissingIdHandler { + (details: { path: string; id: string; referrers: string[]; message: string }): void; +} + +export interface PrerenderEntryGeneratorMismatchHandler { + (details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void; +} + +export type PrerenderHttpErrorHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler; +export type PrerenderMissingIdHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler; +export type PrerenderEntryGeneratorMismatchHandlerValue = + | 'fail' + | 'warn' + | 'ignore' + | PrerenderEntryGeneratorMismatchHandler; + +export type PrerenderOption = boolean | 'auto'; + +export type PrerenderMap = Map; + +export interface RequestOptions { + getClientAddress(): string; + platform?: App.Platform; +} + +export interface RouteSegment { + content: string; + dynamic: boolean; + rest: boolean; +} + +export type TrailingSlash = 'never' | 'always' | 'ignore'; diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+private.md b/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+private.md new file mode 100644 index 00000000..d5cd7239 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+private.md @@ -0,0 +1,12 @@ +This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://kit.svelte.dev/docs/cli)), this is equivalent to `process.env`. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://kit.svelte.dev/docs/configuration#env) (if configured). + +This module cannot be imported into client-side code. + +Dynamic environment variables cannot be used during prerendering. + +```ts +import { env } from '$env/dynamic/private'; +console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE); +``` + +> In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter. diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+public.md b/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+public.md new file mode 100644 index 00000000..ad1cf54d --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+public.md @@ -0,0 +1,10 @@ +Similar to [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. + +Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests — when possible, use `$env/static/public` instead. + +Dynamic environment variables cannot be used during prerendering. + +```ts +import { env } from '$env/dynamic/public'; +console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE); +``` diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+private.md b/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+private.md new file mode 100644 index 00000000..40704d23 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+private.md @@ -0,0 +1,19 @@ +Environment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private), this module cannot be imported into client-side code. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://kit.svelte.dev/docs/configuration#env) (if configured). + +_Unlike_ [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination. + +```ts +import { API_KEY } from '$env/static/private'; +``` + +Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: + +``` +MY_FEATURE_FLAG="" +``` + +You can override `.env` values from the command line like so: + +```bash +MY_FEATURE_FLAG="enabled" npm run dev +``` diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+public.md b/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+public.md new file mode 100644 index 00000000..2b55250f --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+public.md @@ -0,0 +1,7 @@ +Similar to [`$env/static/private`](https://kit.svelte.dev/docs/modules#$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. + +Values are replaced statically at build time. + +```ts +import { PUBLIC_BASE_URL } from '$env/static/public'; +``` diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$lib.md b/node_modules/@sveltejs/kit/src/types/synthetic/$lib.md new file mode 100644 index 00000000..9b760013 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$lib.md @@ -0,0 +1,5 @@ +This is a simple alias to `src/lib`, or whatever directory is specified as [`config.kit.files.lib`](https://kit.svelte.dev/docs/configuration#files). It allows you to access common components and utility modules without `../../../../` nonsense. + +### `$lib/server` + +A subdirectory of `$lib`. SvelteKit will prevent you from importing any modules in `$lib/server` into client-side code. See [server-only modules](/docs/server-only-modules). diff --git a/node_modules/@sveltejs/kit/src/utils/array.js b/node_modules/@sveltejs/kit/src/utils/array.js new file mode 100644 index 00000000..08f93845 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/array.js @@ -0,0 +1,9 @@ +/** + * Removes nullish values from an array. + * + * @template T + * @param {Array} arr + */ +export function compact(arr) { + return arr.filter(/** @returns {val is NonNullable} */ (val) => val != null); +} diff --git a/node_modules/@sveltejs/kit/src/utils/env.js b/node_modules/@sveltejs/kit/src/utils/env.js new file mode 100644 index 00000000..e2106f34 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/env.js @@ -0,0 +1,33 @@ +/** + * @param {Record} env + * @param {{ + * public_prefix: string; + * private_prefix: string; + * }} prefixes + * @returns {Record} + */ +export function filter_private_env(env, { public_prefix, private_prefix }) { + return Object.fromEntries( + Object.entries(env).filter( + ([k]) => + k.startsWith(private_prefix) && (public_prefix === '' || !k.startsWith(public_prefix)) + ) + ); +} + +/** + * @param {Record} env + * @param {{ + * public_prefix: string; + * private_prefix: string; + * }} prefixes + * @returns {Record} + */ +export function filter_public_env(env, { public_prefix, private_prefix }) { + return Object.fromEntries( + Object.entries(env).filter( + ([k]) => + k.startsWith(public_prefix) && (private_prefix === '' || !k.startsWith(private_prefix)) + ) + ); +} diff --git a/node_modules/@sveltejs/kit/src/utils/error.js b/node_modules/@sveltejs/kit/src/utils/error.js new file mode 100644 index 00000000..1247b940 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/error.js @@ -0,0 +1,38 @@ +import { HttpError, SvelteKitError } from '../runtime/control.js'; + +/** + * @param {unknown} err + * @return {Error} + */ +export function coalesce_to_error(err) { + return err instanceof Error || + (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message) + ? /** @type {Error} */ (err) + : new Error(JSON.stringify(err)); +} + +/** + * This is an identity function that exists to make TypeScript less + * paranoid about people throwing things that aren't errors, which + * frankly is not something we should care about + * @param {unknown} error + */ +export function normalize_error(error) { + return /** @type {import('../runtime/control.js').Redirect | HttpError | SvelteKitError | Error} */ ( + error + ); +} + +/** + * @param {unknown} error + */ +export function get_status(error) { + return error instanceof HttpError || error instanceof SvelteKitError ? error.status : 500; +} + +/** + * @param {unknown} error + */ +export function get_message(error) { + return error instanceof SvelteKitError ? error.text : 'Internal Error'; +} diff --git a/node_modules/@sveltejs/kit/src/utils/escape.js b/node_modules/@sveltejs/kit/src/utils/escape.js new file mode 100644 index 00000000..543e1a13 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/escape.js @@ -0,0 +1,46 @@ +/** + * When inside a double-quoted attribute value, only `&` and `"` hold special meaning. + * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state + * @type {Record} + */ +const escape_html_attr_dict = { + '&': '&', + '"': '"' +}; + +const escape_html_attr_regex = new RegExp( + // special characters + `[${Object.keys(escape_html_attr_dict).join('')}]|` + + // high surrogate without paired low surrogate + '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' + + // a valid surrogate pair, the only match with 2 code units + // we match it so that we can match unpaired low surrogates in the same pass + // TODO: use lookbehind assertions once they are widely supported: (?...`; + */ +export function escape_html_attr(str) { + const escaped_str = str.replace(escape_html_attr_regex, (match) => { + if (match.length === 2) { + // valid surrogate pair + return match; + } + + return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`; + }); + + return `"${escaped_str}"`; +} diff --git a/node_modules/@sveltejs/kit/src/utils/exports.js b/node_modules/@sveltejs/kit/src/utils/exports.js new file mode 100644 index 00000000..ed685edb --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/exports.js @@ -0,0 +1,93 @@ +/** + * @param {Set} expected + */ +function validator(expected) { + /** + * @param {any} module + * @param {string} [file] + */ + function validate(module, file) { + if (!module) return; + + for (const key in module) { + if (key[0] === '_' || expected.has(key)) continue; // key is valid in this module + + const values = [...expected.values()]; + + const hint = + hint_for_supported_files(key, file?.slice(file.lastIndexOf('.'))) ?? + `valid exports are ${values.join(', ')}, or anything with a '_' prefix`; + + throw new Error(`Invalid export '${key}'${file ? ` in ${file}` : ''} (${hint})`); + } + } + + return validate; +} + +/** + * @param {string} key + * @param {string} ext + * @returns {string | void} + */ +function hint_for_supported_files(key, ext = '.js') { + const supported_files = []; + + if (valid_layout_exports.has(key)) { + supported_files.push(`+layout${ext}`); + } + + if (valid_page_exports.has(key)) { + supported_files.push(`+page${ext}`); + } + + if (valid_layout_server_exports.has(key)) { + supported_files.push(`+layout.server${ext}`); + } + + if (valid_page_server_exports.has(key)) { + supported_files.push(`+page.server${ext}`); + } + + if (valid_server_exports.has(key)) { + supported_files.push(`+server${ext}`); + } + + if (supported_files.length > 0) { + return `'${key}' is a valid export in ${supported_files.slice(0, -1).join(', ')}${ + supported_files.length > 1 ? ' or ' : '' + }${supported_files.at(-1)}`; + } +} + +const valid_layout_exports = new Set([ + 'load', + 'prerender', + 'csr', + 'ssr', + 'trailingSlash', + 'config' +]); +const valid_page_exports = new Set([...valid_layout_exports, 'entries']); +const valid_layout_server_exports = new Set([...valid_layout_exports]); +const valid_page_server_exports = new Set([...valid_layout_server_exports, 'actions', 'entries']); +const valid_server_exports = new Set([ + 'GET', + 'POST', + 'PATCH', + 'PUT', + 'DELETE', + 'OPTIONS', + 'HEAD', + 'fallback', + 'prerender', + 'trailingSlash', + 'config', + 'entries' +]); + +export const validate_layout_exports = validator(valid_layout_exports); +export const validate_page_exports = validator(valid_page_exports); +export const validate_layout_server_exports = validator(valid_layout_server_exports); +export const validate_page_server_exports = validator(valid_page_server_exports); +export const validate_server_exports = validator(valid_server_exports); diff --git a/node_modules/@sveltejs/kit/src/utils/features.js b/node_modules/@sveltejs/kit/src/utils/features.js new file mode 100644 index 00000000..4a8530d2 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/features.js @@ -0,0 +1,24 @@ +/** + * @param {string} route_id + * @param {any} config + * @param {string} feature + * @param {import('@sveltejs/kit').Adapter | undefined} adapter + */ +export function check_feature(route_id, config, feature, adapter) { + if (!adapter) return; + + switch (feature) { + case '$app/server:read': { + const supported = adapter.supports?.read?.({ + route: { id: route_id }, + config + }); + + if (!supported) { + throw new Error( + `Cannot use \`read\` from \`$app/server\` in ${route_id} when using ${adapter.name}. Please ensure that your adapter is up to date and supports this feature.` + ); + } + } + } +} diff --git a/node_modules/@sveltejs/kit/src/utils/filesystem.js b/node_modules/@sveltejs/kit/src/utils/filesystem.js new file mode 100644 index 00000000..ff83568e --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/filesystem.js @@ -0,0 +1,196 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +/** @param {string} dir */ +export function mkdirp(dir) { + try { + fs.mkdirSync(dir, { recursive: true }); + } catch (/** @type {any} */ e) { + if (e.code === 'EEXIST') { + if (!fs.statSync(dir).isDirectory()) { + throw new Error(`Cannot create directory ${dir}, a file already exists at this position`); + } + return; + } + throw e; + } +} + +/** @param {string} path */ +export function rimraf(path) { + fs.rmSync(path, { force: true, recursive: true }); +} + +/** + * @param {string} source + * @param {string} target + * @param {{ + * filter?: (basename: string) => boolean; + * replace?: Record; + * }} opts + */ +export function copy(source, target, opts = {}) { + if (!fs.existsSync(source)) return []; + + /** @type {string[]} */ + const files = []; + + const prefix = posixify(target) + '/'; + + const regex = opts.replace + ? new RegExp(`\\b(${Object.keys(opts.replace).join('|')})\\b`, 'g') + : null; + + /** + * @param {string} from + * @param {string} to + */ + function go(from, to) { + if (opts.filter && !opts.filter(path.basename(from))) return; + + const stats = fs.statSync(from); + + if (stats.isDirectory()) { + fs.readdirSync(from).forEach((file) => { + go(path.join(from, file), path.join(to, file)); + }); + } else { + mkdirp(path.dirname(to)); + + if (opts.replace) { + const data = fs.readFileSync(from, 'utf-8'); + fs.writeFileSync( + to, + data.replace( + /** @type {RegExp} */ (regex), + (_match, key) => /** @type {Record} */ (opts.replace)[key] + ) + ); + } else { + fs.copyFileSync(from, to); + } + + files.push(to === target ? posixify(path.basename(to)) : posixify(to).replace(prefix, '')); + } + } + + go(source, target); + + return files; +} + +/** + * Get a list of all files in a directory + * @param {string} cwd - the directory to walk + * @param {boolean} [dirs] - whether to include directories in the result + * @returns {string[]} a list of all found files (and possibly directories) relative to `cwd` + */ +export function walk(cwd, dirs = false) { + /** @type {string[]} */ + const all_files = []; + + /** @param {string} dir */ + function walk_dir(dir) { + const files = fs.readdirSync(path.join(cwd, dir)); + + for (const file of files) { + const joined = path.join(dir, file); + const stats = fs.statSync(path.join(cwd, joined)); + if (stats.isDirectory()) { + if (dirs) all_files.push(joined); + walk_dir(joined); + } else { + all_files.push(joined); + } + } + } + + return walk_dir(''), all_files; +} + +/** @param {string} str */ +export function posixify(str) { + return str.replace(/\\/g, '/'); +} + +/** + * Like `path.join`, but posixified and with a leading `./` if necessary + * @param {string[]} str + */ +export function join_relative(...str) { + let result = posixify(path.join(...str)); + if (!result.startsWith('.')) { + result = `./${result}`; + } + return result; +} + +/** + * Like `path.relative`, but always posixified and with a leading `./` if necessary. + * Useful for JS imports so the path can safely reside inside of `node_modules`. + * Otherwise paths could be falsely interpreted as package paths. + * @param {string} from + * @param {string} to + */ +export function relative_path(from, to) { + return join_relative(path.relative(from, to)); +} + +/** + * Prepend given path with `/@fs` prefix + * @param {string} str + */ +export function to_fs(str) { + str = posixify(str); + return `/@fs${ + // Windows/Linux separation - Windows starts with a drive letter, we need a / in front there + str.startsWith('/') ? '' : '/' + }${str}`; +} + +/** + * Removes `/@fs` prefix from given path and posixifies it + * @param {string} str + */ +export function from_fs(str) { + str = posixify(str); + if (!str.startsWith('/@fs')) return str; + + str = str.slice(4); + // Windows/Linux separation - Windows starts with a drive letter, we need to strip the additional / here + return str[2] === ':' && /[A-Z]/.test(str[1]) ? str.slice(1) : str; +} + +/** + * Given an entry point like [cwd]/src/hooks, returns a filename like [cwd]/src/hooks.js or [cwd]/src/hooks/index.js + * @param {string} entry + * @returns {string|null} + */ +export function resolve_entry(entry) { + if (fs.existsSync(entry)) { + const stats = fs.statSync(entry); + if (stats.isDirectory()) { + return resolve_entry(path.join(entry, 'index')); + } + + return entry; + } else { + const dir = path.dirname(entry); + + if (fs.existsSync(dir)) { + const base = path.basename(entry); + const files = fs.readdirSync(dir); + + const found = files.find((file) => file.replace(/\.(js|ts)$/, '') === base); + + if (found) return path.join(dir, found); + } + } + + return null; +} + +/** @param {string} file */ +export function read(file) { + return fs.readFileSync(file, 'utf-8'); +} diff --git a/node_modules/@sveltejs/kit/src/utils/fork.js b/node_modules/@sveltejs/kit/src/utils/fork.js new file mode 100644 index 00000000..918eded4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/fork.js @@ -0,0 +1,70 @@ +import { fileURLToPath } from 'node:url'; +import { Worker, parentPort } from 'node:worker_threads'; +import process from 'node:process'; + +/** + * Runs a task in a subprocess so any dangling stuff gets killed upon completion. + * The subprocess needs to be the file `forked` is called in, and `forked` needs to be called eagerly at the top level. + * @template T + * @template U + * @param {string} module `import.meta.url` of the file + * @param {(opts: T) => Promise} callback The function that is invoked in the subprocess + * @returns {(opts: T) => Promise} A function that when called starts the subprocess + */ +export function forked(module, callback) { + if (process.env.SVELTEKIT_FORK && parentPort) { + parentPort.on( + 'message', + /** @param {any} data */ async (data) => { + if (data?.type === 'args' && data.module === module) { + parentPort?.postMessage({ + type: 'result', + module, + payload: await callback(data.payload) + }); + } + } + ); + + parentPort.postMessage({ type: 'ready', module }); + } + + /** + * @param {T} opts + * @returns {Promise} + */ + return function (opts) { + return new Promise((fulfil, reject) => { + const worker = new Worker(fileURLToPath(module), { + env: { + ...process.env, + SVELTEKIT_FORK: 'true' + } + }); + + worker.on( + 'message', + /** @param {any} data */ (data) => { + if (data?.type === 'ready' && data.module === module) { + worker.postMessage({ + type: 'args', + module, + payload: opts + }); + } + + if (data?.type === 'result' && data.module === module) { + worker.unref(); + fulfil(data.payload); + } + } + ); + + worker.on('exit', (code) => { + if (code) { + reject(new Error(`Failed with code ${code}`)); + } + }); + }); + }; +} diff --git a/node_modules/@sveltejs/kit/src/utils/functions.js b/node_modules/@sveltejs/kit/src/utils/functions.js new file mode 100644 index 00000000..06291078 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/functions.js @@ -0,0 +1,16 @@ +/** + * @template T + * @param {() => T} fn + */ +export function once(fn) { + let done = false; + + /** @type T */ + let result; + + return () => { + if (done) return result; + done = true; + return (result = fn()); + }; +} diff --git a/node_modules/@sveltejs/kit/src/utils/http.js b/node_modules/@sveltejs/kit/src/utils/http.js new file mode 100644 index 00000000..bfd948d4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/http.js @@ -0,0 +1,79 @@ +/** + * Given an Accept header and a list of possible content types, pick + * the most suitable one to respond with + * @param {string} accept + * @param {string[]} types + */ +export function negotiate(accept, types) { + /** @type {Array<{ type: string, subtype: string, q: number, i: number }>} */ + const parts = []; + + accept.split(',').forEach((str, i) => { + const match = /([^/ \t]+)\/([^; \t]+)[ \t]*(?:;[ \t]*q=([0-9.]+))?/.exec(str); + + // no match equals invalid header — ignore + if (match) { + const [, type, subtype, q = '1'] = match; + parts.push({ type, subtype, q: +q, i }); + } + }); + + parts.sort((a, b) => { + if (a.q !== b.q) { + return b.q - a.q; + } + + if ((a.subtype === '*') !== (b.subtype === '*')) { + return a.subtype === '*' ? 1 : -1; + } + + if ((a.type === '*') !== (b.type === '*')) { + return a.type === '*' ? 1 : -1; + } + + return a.i - b.i; + }); + + let accepted; + let min_priority = Infinity; + + for (const mimetype of types) { + const [type, subtype] = mimetype.split('/'); + const priority = parts.findIndex( + (part) => + (part.type === type || part.type === '*') && + (part.subtype === subtype || part.subtype === '*') + ); + + if (priority !== -1 && priority < min_priority) { + accepted = mimetype; + min_priority = priority; + } + } + + return accepted; +} + +/** + * Returns `true` if the request contains a `content-type` header with the given type + * @param {Request} request + * @param {...string} types + */ +function is_content_type(request, ...types) { + const type = request.headers.get('content-type')?.split(';', 1)[0].trim() ?? ''; + return types.includes(type.toLowerCase()); +} + +/** + * @param {Request} request + */ +export function is_form_content_type(request) { + // These content types must be protected against CSRF + // https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype + return is_content_type( + request, + 'application/x-www-form-urlencoded', + 'multipart/form-data', + 'text/plain' + ); +} diff --git a/node_modules/@sveltejs/kit/src/utils/import.js b/node_modules/@sveltejs/kit/src/utils/import.js new file mode 100644 index 00000000..78ed5482 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/import.js @@ -0,0 +1,20 @@ +import * as imr from 'import-meta-resolve'; +import process from 'node:process'; +import { pathToFileURL } from 'node:url'; + +/** + * Resolve a dependency relative to the current working directory, + * rather than relative to this package + * @param {string} dependency + */ +export function resolve_peer_dependency(dependency) { + try { + // @ts-expect-error the types are wrong + const resolved = imr.resolve(dependency, pathToFileURL(process.cwd() + '/dummy.js')); + return import(resolved); + } catch { + throw new Error( + `Could not resolve peer dependency "${dependency}" relative to your project — please install it and try again.` + ); + } +} diff --git a/node_modules/@sveltejs/kit/src/utils/misc.js b/node_modules/@sveltejs/kit/src/utils/misc.js new file mode 100644 index 00000000..cd64ed21 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/misc.js @@ -0,0 +1 @@ +export const s = JSON.stringify; diff --git a/node_modules/@sveltejs/kit/src/utils/options.js b/node_modules/@sveltejs/kit/src/utils/options.js new file mode 100644 index 00000000..46a32535 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/options.js @@ -0,0 +1,16 @@ +/** + * @template {'prerender' | 'ssr' | 'csr' | 'trailingSlash' | 'entries'} Option + * @template {(import('types').SSRNode['universal'] | import('types').SSRNode['server'])[Option]} Value + * + * @param {Array} nodes + * @param {Option} option + * + * @returns {Value | undefined} + */ +export function get_option(nodes, option) { + return nodes.reduce((value, node) => { + return /** @type {Value} TypeScript's too dumb to understand this */ ( + node?.universal?.[option] ?? node?.server?.[option] ?? value + ); + }, /** @type {Value | undefined} */ (undefined)); +} diff --git a/node_modules/@sveltejs/kit/src/utils/route_config.js b/node_modules/@sveltejs/kit/src/utils/route_config.js new file mode 100644 index 00000000..27b67f71 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/route_config.js @@ -0,0 +1,21 @@ +/** + * Do a shallow merge (first level) of the config object + * @param {Array} nodes + */ +export function get_page_config(nodes) { + /** @type {any} */ + let current = {}; + + for (const node of nodes) { + if (!node?.universal?.config && !node?.server?.config) continue; + + current = { + ...current, + ...node?.universal?.config, + ...node?.server?.config + }; + } + + // TODO 3.0 always return `current`? then we can get rid of `?? {}` in other places + return Object.keys(current).length ? current : undefined; +} diff --git a/node_modules/@sveltejs/kit/src/utils/routing.js b/node_modules/@sveltejs/kit/src/utils/routing.js new file mode 100644 index 00000000..7d988317 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/routing.js @@ -0,0 +1,267 @@ +import { BROWSER } from 'esm-env'; + +const param_pattern = /^(\[)?(\.\.\.)?(\w+)(?:=(\w+))?(\])?$/; + +/** + * Creates the regex pattern, extracts parameter names, and generates types for a route + * @param {string} id + */ +export function parse_route_id(id) { + /** @type {import('types').RouteParam[]} */ + const params = []; + + const pattern = + id === '/' + ? /^\/$/ + : new RegExp( + `^${get_route_segments(id) + .map((segment) => { + // special case — /[...rest]/ could contain zero segments + const rest_match = /^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(segment); + if (rest_match) { + params.push({ + name: rest_match[1], + matcher: rest_match[2], + optional: false, + rest: true, + chained: true + }); + return '(?:/(.*))?'; + } + // special case — /[[optional]]/ could contain zero segments + const optional_match = /^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(segment); + if (optional_match) { + params.push({ + name: optional_match[1], + matcher: optional_match[2], + optional: true, + rest: false, + chained: true + }); + return '(?:/([^/]+))?'; + } + + if (!segment) { + return; + } + + const parts = segment.split(/\[(.+?)\](?!\])/); + const result = parts + .map((content, i) => { + if (i % 2) { + if (content.startsWith('x+')) { + return escape(String.fromCharCode(parseInt(content.slice(2), 16))); + } + + if (content.startsWith('u+')) { + return escape( + String.fromCharCode( + ...content + .slice(2) + .split('-') + .map((code) => parseInt(code, 16)) + ) + ); + } + + // We know the match cannot be null in the browser because manifest generation + // would have invoked this during build and failed if we hit an invalid + // param/matcher name with non-alphanumeric character. + const match = /** @type {RegExpExecArray} */ (param_pattern.exec(content)); + if (!BROWSER && !match) { + throw new Error( + `Invalid param: ${content}. Params and matcher names can only have underscores and alphanumeric characters.` + ); + } + + const [, is_optional, is_rest, name, matcher] = match; + // It's assumed that the following invalid route id cases are already checked + // - unbalanced brackets + // - optional param following rest param + + params.push({ + name, + matcher, + optional: !!is_optional, + rest: !!is_rest, + chained: is_rest ? i === 1 && parts[0] === '' : false + }); + return is_rest ? '(.*?)' : is_optional ? '([^/]*)?' : '([^/]+?)'; + } + + return escape(content); + }) + .join(''); + + return '/' + result; + }) + .join('')}/?$` + ); + + return { pattern, params }; +} + +const optional_param_regex = /\/\[\[\w+?(?:=\w+)?\]\]/; + +/** + * Removes optional params from a route ID. + * @param {string} id + * @returns The route id with optional params removed + */ +export function remove_optional_params(id) { + return id.replace(optional_param_regex, ''); +} + +/** + * Returns `false` for `(group)` segments + * @param {string} segment + */ +function affects_path(segment) { + return !/^\([^)]+\)$/.test(segment); +} + +/** + * Splits a route id into its segments, removing segments that + * don't affect the path (i.e. groups). The root route is represented by `/` + * and will be returned as `['']`. + * @param {string} route + * @returns string[] + */ +export function get_route_segments(route) { + return route.slice(1).split('/').filter(affects_path); +} + +/** + * @param {RegExpMatchArray} match + * @param {import('types').RouteParam[]} params + * @param {Record} matchers + */ +export function exec(match, params, matchers) { + /** @type {Record} */ + const result = {}; + + const values = match.slice(1); + const values_needing_match = values.filter((value) => value !== undefined); + + let buffered = 0; + + for (let i = 0; i < params.length; i += 1) { + const param = params[i]; + let value = values[i - buffered]; + + // in the `[[a=b]]/.../[...rest]` case, if one or more optional parameters + // weren't matched, roll the skipped values into the rest + if (param.chained && param.rest && buffered) { + value = values + .slice(i - buffered, i + 1) + .filter((s) => s) + .join('/'); + + buffered = 0; + } + + // if `value` is undefined, it means this is an optional or rest parameter + if (value === undefined) { + if (param.rest) result[param.name] = ''; + continue; + } + + if (!param.matcher || matchers[param.matcher](value)) { + result[param.name] = value; + + // Now that the params match, reset the buffer if the next param isn't the [...rest] + // and the next value is defined, otherwise the buffer will cause us to skip values + const next_param = params[i + 1]; + const next_value = values[i + 1]; + if (next_param && !next_param.rest && next_param.optional && next_value && param.chained) { + buffered = 0; + } + + // There are no more params and no more values, but all non-empty values have been matched + if ( + !next_param && + !next_value && + Object.keys(result).length === values_needing_match.length + ) { + buffered = 0; + } + continue; + } + + // in the `/[[a=b]]/...` case, if the value didn't satisfy the matcher, + // keep track of the number of skipped optional parameters and continue + if (param.optional && param.chained) { + buffered++; + continue; + } + + // otherwise, if the matcher returns `false`, the route did not match + return; + } + + if (buffered) return; + return result; +} + +/** @param {string} str */ +function escape(str) { + return ( + str + .normalize() + // escape [ and ] before escaping other characters, since they are used in the replacements + .replace(/[[\]]/g, '\\$&') + // replace %, /, ? and # with their encoded versions because decode_pathname leaves them untouched + .replace(/%/g, '%25') + .replace(/\//g, '%2[Ff]') + .replace(/\?/g, '%3[Ff]') + .replace(/#/g, '%23') + // escape characters that have special meaning in regex + .replace(/[.*+?^${}()|\\]/g, '\\$&') + ); +} + +const basic_param_pattern = /\[(\[)?(\.\.\.)?(\w+?)(?:=(\w+))?\]\]?/g; + +/** + * Populate a route ID with params to resolve a pathname. + * @example + * ```js + * resolveRoute( + * `/blog/[slug]/[...somethingElse]`, + * { + * slug: 'hello-world', + * somethingElse: 'something/else' + * } + * ); // `/blog/hello-world/something/else` + * ``` + * @param {string} id + * @param {Record} params + * @returns {string} + */ +export function resolve_route(id, params) { + const segments = get_route_segments(id); + return ( + '/' + + segments + .map((segment) => + segment.replace(basic_param_pattern, (_, optional, rest, name) => { + const param_value = params[name]; + + // This is nested so TS correctly narrows the type + if (!param_value) { + if (optional) return ''; + if (rest && param_value !== undefined) return ''; + throw new Error(`Missing parameter '${name}' in route ${id}`); + } + + if (param_value.startsWith('/') || param_value.endsWith('/')) + throw new Error( + `Parameter '${name}' in route ${id} cannot start or end with a slash -- this would cause an invalid route like foo//bar` + ); + return param_value; + }) + ) + .filter(Boolean) + .join('/') + ); +} diff --git a/node_modules/@sveltejs/kit/src/utils/streaming.js b/node_modules/@sveltejs/kit/src/utils/streaming.js new file mode 100644 index 00000000..cfb0d6a0 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/streaming.js @@ -0,0 +1,51 @@ +/** + * @returns {import('types').Deferred & { promise: Promise }}} + */ +function defer() { + let fulfil; + let reject; + + const promise = new Promise((f, r) => { + fulfil = f; + reject = r; + }); + + // @ts-expect-error + return { promise, fulfil, reject }; +} + +/** + * Create an async iterator and a function to push values into it + * @returns {{ + * iterator: AsyncIterable; + * push: (value: any) => void; + * done: () => void; + * }} + */ +export function create_async_iterator() { + const deferred = [defer()]; + + return { + iterator: { + [Symbol.asyncIterator]() { + return { + next: async () => { + const next = await deferred[0].promise; + if (!next.done) deferred.shift(); + return next; + } + }; + } + }, + push: (value) => { + deferred[deferred.length - 1].fulfil({ + value, + done: false + }); + deferred.push(defer()); + }, + done: () => { + deferred[deferred.length - 1].fulfil({ done: true }); + } + }; +} diff --git a/node_modules/@sveltejs/kit/src/utils/url.js b/node_modules/@sveltejs/kit/src/utils/url.js new file mode 100644 index 00000000..53759b31 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/url.js @@ -0,0 +1,222 @@ +import { BROWSER, DEV } from 'esm-env'; + +/** + * Matches a URI scheme. See https://www.rfc-editor.org/rfc/rfc3986#section-3.1 + * @type {RegExp} + */ +export const SCHEME = /^[a-z][a-z\d+\-.]+:/i; + +const internal = new URL('sveltekit-internal://'); + +/** + * @param {string} base + * @param {string} path + */ +export function resolve(base, path) { + // special case + if (path[0] === '/' && path[1] === '/') return path; + + let url = new URL(base, internal); + url = new URL(path, url); + + return url.protocol === internal.protocol ? url.pathname + url.search + url.hash : url.href; +} + +/** @param {string} path */ +export function is_root_relative(path) { + return path[0] === '/' && path[1] !== '/'; +} + +/** + * @param {string} path + * @param {import('types').TrailingSlash} trailing_slash + */ +export function normalize_path(path, trailing_slash) { + if (path === '/' || trailing_slash === 'ignore') return path; + + if (trailing_slash === 'never') { + return path.endsWith('/') ? path.slice(0, -1) : path; + } else if (trailing_slash === 'always' && !path.endsWith('/')) { + return path + '/'; + } + + return path; +} + +/** + * Decode pathname excluding %25 to prevent further double decoding of params + * @param {string} pathname + */ +export function decode_pathname(pathname) { + return pathname.split('%25').map(decodeURI).join('%25'); +} + +/** @param {Record} params */ +export function decode_params(params) { + for (const key in params) { + // input has already been decoded by decodeURI + // now handle the rest + params[key] = decodeURIComponent(params[key]); + } + + return params; +} + +/** + * The error when a URL is malformed is not very helpful, so we augment it with the URI + * @param {string} uri + */ +export function decode_uri(uri) { + try { + return decodeURI(uri); + } catch (e) { + if (e instanceof Error) { + e.message = `Failed to decode URI: ${uri}\n` + e.message; + } + throw e; + } +} + +/** + * Returns everything up to the first `#` in a URL + * @param {{href: string}} url_like + */ +export function strip_hash({ href }) { + return href.split('#')[0]; +} + +/** + * URL properties that could change during the lifetime of the page, + * which excludes things like `origin` + */ +const tracked_url_properties = /** @type {const} */ ([ + 'href', + 'pathname', + 'search', + 'toString', + 'toJSON' +]); + +/** + * @param {URL} url + * @param {() => void} callback + * @param {(search_param: string) => void} search_params_callback + */ +export function make_trackable(url, callback, search_params_callback) { + const tracked = new URL(url); + + Object.defineProperty(tracked, 'searchParams', { + value: new Proxy(tracked.searchParams, { + get(obj, key) { + if (key === 'get' || key === 'getAll' || key === 'has') { + return (/**@type {string}*/ param) => { + search_params_callback(param); + return obj[key](param); + }; + } + + // if they try to access something different from what is in `tracked_search_params_properties` + // we track the whole url (entries, values, keys etc) + callback(); + + const value = Reflect.get(obj, key); + return typeof value === 'function' ? value.bind(obj) : value; + } + }), + enumerable: true, + configurable: true + }); + + for (const property of tracked_url_properties) { + Object.defineProperty(tracked, property, { + get() { + callback(); + return url[property]; + }, + + enumerable: true, + configurable: true + }); + } + + if (!BROWSER) { + // @ts-ignore + tracked[Symbol.for('nodejs.util.inspect.custom')] = (depth, opts, inspect) => { + return inspect(url, opts); + }; + } + + if (DEV || !BROWSER) { + disable_hash(tracked); + } + + return tracked; +} + +/** + * Disallow access to `url.hash` on the server and in `load` + * @param {URL} url + */ +function disable_hash(url) { + allow_nodejs_console_log(url); + + Object.defineProperty(url, 'hash', { + get() { + throw new Error( + 'Cannot access event.url.hash. Consider using `$page.url.hash` inside a component instead' + ); + } + }); +} + +/** + * Disallow access to `url.search` and `url.searchParams` during prerendering + * @param {URL} url + */ +export function disable_search(url) { + allow_nodejs_console_log(url); + + for (const property of ['search', 'searchParams']) { + Object.defineProperty(url, property, { + get() { + throw new Error(`Cannot access url.${property} on a page with prerendering enabled`); + } + }); + } +} + +/** + * Allow URL to be console logged, bypassing disabled properties. + * @param {URL} url + */ +function allow_nodejs_console_log(url) { + if (!BROWSER) { + // @ts-ignore + url[Symbol.for('nodejs.util.inspect.custom')] = (depth, opts, inspect) => { + return inspect(new URL(url), opts); + }; + } +} + +const DATA_SUFFIX = '/__data.json'; +const HTML_DATA_SUFFIX = '.html__data.json'; + +/** @param {string} pathname */ +export function has_data_suffix(pathname) { + return pathname.endsWith(DATA_SUFFIX) || pathname.endsWith(HTML_DATA_SUFFIX); +} + +/** @param {string} pathname */ +export function add_data_suffix(pathname) { + if (pathname.endsWith('.html')) return pathname.replace(/\.html$/, HTML_DATA_SUFFIX); + return pathname.replace(/\/$/, '') + DATA_SUFFIX; +} + +/** @param {string} pathname */ +export function strip_data_suffix(pathname) { + if (pathname.endsWith(HTML_DATA_SUFFIX)) { + return pathname.slice(0, -HTML_DATA_SUFFIX.length) + '.html'; + } + + return pathname.slice(0, -DATA_SUFFIX.length); +} diff --git a/node_modules/@sveltejs/kit/src/version.js b/node_modules/@sveltejs/kit/src/version.js new file mode 100644 index 00000000..389a1a53 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/version.js @@ -0,0 +1,4 @@ +// generated during release, do not modify + +/** @type {string} */ +export const VERSION = '2.6.1'; diff --git a/node_modules/@sveltejs/kit/svelte-kit.js b/node_modules/@sveltejs/kit/svelte-kit.js new file mode 100644 index 00000000..b48389f6 --- /dev/null +++ b/node_modules/@sveltejs/kit/svelte-kit.js @@ -0,0 +1,2 @@ +#!/usr/bin/env node +import './src/cli.js'; diff --git a/node_modules/@sveltejs/kit/types/index.d.ts b/node_modules/@sveltejs/kit/types/index.d.ts new file mode 100644 index 00000000..687ac768 --- /dev/null +++ b/node_modules/@sveltejs/kit/types/index.d.ts @@ -0,0 +1,2318 @@ +/// +/// + +declare module '@sveltejs/kit' { + import type { CompileOptions } from 'svelte/compiler'; + import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; + /** + * [Adapters](https://kit.svelte.dev/docs/adapters) are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing. + */ + export interface Adapter { + /** + * The name of the adapter, using for logging. Will typically correspond to the package name. + */ + name: string; + /** + * This function is called after SvelteKit has built your app. + * @param builder An object provided by SvelteKit that contains methods for adapting the app + */ + adapt(builder: Builder): MaybePromise; + /** + * Checks called during dev and build to determine whether specific features will work in production with this adapter + */ + supports?: { + /** + * Test support for `read` from `$app/server` + * @param config The merged route config + */ + read?: (details: { config: any; route: { id: string } }) => boolean; + }; + /** + * Creates an `Emulator`, which allows the adapter to influence the environment + * during dev, build and prerendering + */ + emulate?(): MaybePromise; + } + + export type LoadProperties | void> = input extends void + ? undefined // needs to be undefined, because void will break intellisense + : input extends Record + ? input + : unknown; + + export type AwaitedActions any>> = OptionalUnion< + { + [Key in keyof T]: UnpackValidationError>>; + }[keyof T] + >; + + // Takes a union type and returns a union type where each type also has all properties + // of all possible types (typed as undefined), making accessing them more ergonomic + type OptionalUnion< + U extends Record, // not unknown, else interfaces don't satisfy this constraint + A extends keyof U = U extends U ? keyof U : never + > = U extends unknown ? { [P in Exclude]?: never } & U : never; + + const uniqueSymbol: unique symbol; + + export interface ActionFailure | undefined = undefined> { + status: number; + data: T; + [uniqueSymbol]: true; // necessary or else UnpackValidationError could wrongly unpack objects with the same shape as ActionFailure + } + + type UnpackValidationError = + T extends ActionFailure + ? X + : T extends void + ? undefined // needs to be undefined, because void will corrupt union type + : T; + + /** + * This object is passed to the `adapt` function of adapters. + * It contains various methods and properties that are useful for adapting the app. + */ + export interface Builder { + /** Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`. */ + log: Logger; + /** Remove `dir` and all its contents. */ + rimraf(dir: string): void; + /** Create `dir` and any required parent directories. */ + mkdirp(dir: string): void; + + /** The fully resolved `svelte.config.js`. */ + config: ValidatedConfig; + /** Information about prerendered pages and assets, if any. */ + prerendered: Prerendered; + /** An array of all routes (including prerendered) */ + routes: RouteDefinition[]; + + // TODO 3.0 remove this method + /** + * Create separate functions that map to one or more routes of your app. + * @param fn A function that groups a set of routes into an entry point + * @deprecated Use `builder.routes` instead + */ + createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise; + + /** + * Find all the assets imported by server files belonging to `routes` + */ + findServerAssets(routes: RouteDefinition[]): string[]; + + /** + * Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps. + */ + generateFallback(dest: string): Promise; + + /** + * Generate a module exposing build-time environment variables as `$env/dynamic/public`. + */ + generateEnvModule(): void; + + /** + * Generate a server-side manifest to initialise the SvelteKit [server](https://kit.svelte.dev/docs/types#public-types-server) with. + * @param opts a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated + */ + generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string; + + /** + * Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`. + * @param name path to the file, relative to the build directory + */ + getBuildDirectory(name: string): string; + /** Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory. */ + getClientDirectory(): string; + /** Get the fully resolved path to the directory containing server-side code. */ + getServerDirectory(): string; + /** Get the application path including any configured `base` path, e.g. `my-base-path/_app`. */ + getAppPath(): string; + + /** + * Write client assets to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writeClient(dest: string): string[]; + /** + * Write prerendered files to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writePrerendered(dest: string): string[]; + /** + * Write server-side code to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writeServer(dest: string): string[]; + /** + * Copy a file or directory. + * @param from the source file or directory + * @param to the destination file or directory + * @param opts.filter a function to determine whether a file or directory should be copied + * @param opts.replace a map of strings to replace + * @returns an array of files that were copied + */ + copy( + from: string, + to: string, + opts?: { + filter?(basename: string): boolean; + replace?: Record; + } + ): string[]; + + /** + * Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals. + * @param directory The directory containing the files to be compressed + */ + compress(directory: string): Promise; + } + + export interface Config { + /** + * Options passed to [`svelte.compile`](https://svelte.dev/docs#compile-time-svelte-compile). + * @default {} + */ + compilerOptions?: CompileOptions; + /** + * List of file extensions that should be treated as Svelte files. + * @default [".svelte"] + */ + extensions?: string[]; + /** SvelteKit options */ + kit?: KitConfig; + /** Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. */ + preprocess?: any; + /** `vite-plugin-svelte` plugin options. */ + vitePlugin?: PluginOptions; + /** Any additional options required by tooling that integrates with Svelte. */ + [key: string]: any; + } + + export interface Cookies { + /** + * Gets a cookie that was previously set with `cookies.set`, or from the request headers. + * @param name the name of the cookie + * @param opts the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) + */ + get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined; + + /** + * Gets all cookies that were previously set with `cookies.set`, or from the request headers. + * @param opts the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) + */ + getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>; + + /** + * Sets a cookie. This will add a `set-cookie` header to the response, but also make the cookie available via `cookies.get` or `cookies.getAll` during the current request. + * + * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. + * + * You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children + * @param name the name of the cookie + * @param value the cookie value + * @param opts the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + set( + name: string, + value: string, + opts: import('cookie').CookieSerializeOptions & { path: string } + ): void; + + /** + * Deletes a cookie by setting its value to an empty string and setting the expiry date in the past. + * + * You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children + * @param name the name of the cookie + * @param opts the options, passed directly to `cookie.serialize`. The `path` must match the path of the cookie you want to delete. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + delete(name: string, opts: import('cookie').CookieSerializeOptions & { path: string }): void; + + /** + * Serialize a cookie name-value pair into a `Set-Cookie` header string, but don't apply it to the response. + * + * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. + * + * You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children + * + * @param name the name of the cookie + * @param value the cookie value + * @param opts the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + serialize( + name: string, + value: string, + opts: import('cookie').CookieSerializeOptions & { path: string } + ): string; + } + + /** + * A collection of functions that influence the environment during dev, build and prerendering + */ + export interface Emulator { + /** + * A function that is called with the current route `config` and `prerender` option + * and returns an `App.Platform` object + */ + platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise; + } + + export interface KitConfig { + /** + * Your [adapter](https://kit.svelte.dev/docs/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. + * @default undefined + */ + adapter?: Adapter; + /** + * An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. + * + * ```js + * /// file: svelte.config.js + * /// type: import('@sveltejs/kit').Config + * const config = { + * kit: { + * alias: { + * // this will match a file + * 'my-file': 'path/to/my-file.js', + * + * // this will match a directory and its contents + * // (`my-directory/x` resolves to `path/to/my-directory/x`) + * 'my-directory': 'path/to/my-directory', + * + * // an alias ending /* will only match + * // the contents of a directory, not the directory itself + * 'my-directory/*': 'path/to/my-directory/*' + * } + * } + * }; + * ``` + * + * > The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging. + * + * > You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`. + * @default {} + */ + alias?: Record; + /** + * The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes. + * + * If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`. + * @default "_app" + */ + appDir?: string; + /** + * [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this... + * + * ```js + * /// file: svelte.config.js + * /// type: import('@sveltejs/kit').Config + * const config = { + * kit: { + * csp: { + * directives: { + * 'script-src': ['self'] + * }, + * reportOnly: { + * 'script-src': ['self'] + * } + * } + * } + * }; + * + * export default config; + * ``` + * + * ...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates. + * + * To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example ` + * ``` + * + * If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the [`updated`](/docs/modules#$app-stores-updated) store to `true` when it detects one. + */ + version?: { + /** + * The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build. + * + * For example, to use the current commit hash, you could do use `git rev-parse HEAD`: + * + * ```js + * /// file: svelte.config.js + * import * as child_process from 'node:child_process'; + * + * export default { + * kit: { + * version: { + * name: child_process.execSync('git rev-parse HEAD').toString().trim() + * } + * } + * }; + * ``` + */ + name?: string; + /** + * The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. + * @default 0 + */ + pollInterval?: number; + }; + } + + /** + * The [`handle`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) hook runs every time the SvelteKit server receives a [request](https://kit.svelte.dev/docs/web-standards#fetch-apis-request) and + * determines the [response](https://kit.svelte.dev/docs/web-standards#fetch-apis-response). + * It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`. + * This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example). + */ + export type Handle = (input: { + event: RequestEvent; + resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; + }) => MaybePromise; + + /** + * The server-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while responding to a request. + * + * If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. + * Make sure that this function _never_ throws an error. + */ + export type HandleServerError = (input: { + error: unknown; + event: RequestEvent; + status: number; + message: string; + }) => MaybePromise; + + /** + * The client-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while navigating. + * + * If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. + * Make sure that this function _never_ throws an error. + */ + export type HandleClientError = (input: { + error: unknown; + event: NavigationEvent; + status: number; + message: string; + }) => MaybePromise; + + /** + * The [`handleFetch`](https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch) hook allows you to modify (or replace) a `fetch` request that happens inside a `load` function that runs on the server (or during pre-rendering) + */ + export type HandleFetch = (input: { + event: RequestEvent; + request: Request; + fetch: typeof fetch; + }) => MaybePromise; + + /** + * The [`reroute`](https://kit.svelte.dev/docs/hooks#universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render. + * @since 2.3.0 + */ + export type Reroute = (event: { url: URL }) => void | string; + + /** + * The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `Load` directly. + */ + export type Load< + Params extends Partial> = Partial>, + InputData extends Record | null = Record | null, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > = (event: LoadEvent) => MaybePromise; + + /** + * The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `LoadEvent` directly. + */ + export interface LoadEvent< + Params extends Partial> = Partial>, + Data extends Record | null = Record | null, + ParentData extends Record = Record, + RouteId extends string | null = string | null + > extends NavigationEvent { + /** + * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: + * + * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. + * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). + * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. + * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) + * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. + * + * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) + */ + fetch: typeof fetch; + /** + * Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any. + */ + data: Data; + /** + * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: + * + * ```js + * /// file: src/routes/blog/+page.js + * export async function load({ fetch, setHeaders }) { + * const url = `https://cms.example.com/articles.json`; + * const response = await fetch(url); + * + * setHeaders({ + * age: response.headers.get('age'), + * 'cache-control': response.headers.get('cache-control') + * }); + * + * return response.json(); + * } + * ``` + * + * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. + * + * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API in a server-only `load` function instead. + * + * `setHeaders` has no effect when a `load` function runs in the browser. + */ + setHeaders(headers: Record): void; + /** + * `await parent()` returns data from parent `+layout.js` `load` functions. + * Implicitly, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will return and forward data from parent `+layout.server.js` files. + * + * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. + */ + parent(): Promise; + /** + * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. + * + * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. + * + * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). + * + * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). + * + * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. + * + * ```js + * /// file: src/routes/+page.js + * let count = 0; + * export async function load({ depends }) { + * depends('increase:count'); + * + * return { count: count++ }; + * } + * ``` + * + * ```html + * /// file: src/routes/+page.svelte + * + * + *

{data.count}

+ * + * ``` + */ + depends(...deps: Array<`${string}:${string}`>): void; + /** + * Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: + * + * ```js + * /// file: src/routes/+page.server.js + * export async function load({ untrack, url }) { + * // Untrack url.pathname so that path changes don't trigger a rerun + * if (untrack(() => url.pathname === '/')) { + * return { message: 'Welcome!' }; + * } + * } + * ``` + */ + untrack(fn: () => T): T; + } + + export interface NavigationEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null + > { + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * The URL of the current page + */ + url: URL; + } + + /** + * Information about the target of a specific navigation. + */ + export interface NavigationTarget { + /** + * Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object. + * Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route). + */ + params: Record | null; + /** + * Info about the target route + */ + route: { id: string | null }; + /** + * The URL that is navigated to + */ + url: URL; + } + + /** + * - `enter`: The app has hydrated + * - `form`: The user submitted a `` with a GET method + * - `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + export type NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'; + + export interface Navigation { + /** + * Where navigation was triggered from + */ + from: NavigationTarget | null; + /** + * Where navigation is going to/has gone to + */ + to: NavigationTarget | null; + /** + * The type of navigation: + * - `form`: The user submitted a `` + * - `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Exclude; + /** + * Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) + */ + willUnload: boolean; + /** + * In case of a history back/forward navigation, the number of steps to go back/forward + */ + delta?: number; + /** + * A promise that resolves once the navigation is complete, and rejects if the navigation + * fails or is aborted. In the case of a `willUnload` navigation, the promise will never resolve + */ + complete: Promise; + } + + /** + * The argument passed to [`beforeNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-beforenavigate) callbacks. + */ + export interface BeforeNavigate extends Navigation { + /** + * Call this to prevent the navigation from starting. + */ + cancel(): void; + } + + /** + * The argument passed to [`onNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-onnavigate) callbacks. + */ + export interface OnNavigate extends Navigation { + /** + * The type of navigation: + * - `form`: The user submitted a `` + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Exclude; + /** + * Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page. + */ + willUnload: false; + } + + /** + * The argument passed to [`afterNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-afternavigate) callbacks. + */ + export interface AfterNavigate extends Omit { + /** + * The type of navigation: + * - `enter`: The app has hydrated + * - `form`: The user submitted a `` + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Exclude; + /** + * Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page. + */ + willUnload: false; + } + + /** + * The shape of the `$page` store + */ + export interface Page< + Params extends Record = Record, + RouteId extends string | null = string | null + > { + /** + * The URL of the current page + */ + url: URL; + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * Http status code of the current page + */ + status: number; + /** + * The error object of the current page, if any. Filled from the `handleError` hooks. + */ + error: App.Error | null; + /** + * The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`. + */ + data: App.PageData & Record; + /** + * The page state, which can be manipulated using the [`pushState`](https://kit.svelte.dev/docs/modules#$app-navigation-pushstate) and [`replaceState`](https://kit.svelte.dev/docs/modules#$app-navigation-replacestate) functions from `$app/navigation`. + */ + state: App.PageState; + /** + * Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. + */ + form: any; + } + + /** + * The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. + */ + export type ParamMatcher = (param: string) => boolean; + + export interface RequestEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null + > { + /** + * Get or set cookies related to the current request + */ + cookies: Cookies; + /** + * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: + * + * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. + * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). + * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. + * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) + * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. + * + * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) + */ + fetch: typeof fetch; + /** + * The client's IP address, set by the adapter. + */ + getClientAddress(): string; + /** + * Contains custom data that was added to the request within the [`handle hook`](https://kit.svelte.dev/docs/hooks#server-hooks-handle). + */ + locals: App.Locals; + /** + * The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Additional data made available through the adapter. + */ + platform: Readonly | undefined; + /** + * The original request object + */ + request: Request; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: + * + * ```js + * /// file: src/routes/blog/+page.js + * export async function load({ fetch, setHeaders }) { + * const url = `https://cms.example.com/articles.json`; + * const response = await fetch(url); + * + * setHeaders({ + * age: response.headers.get('age'), + * 'cache-control': response.headers.get('cache-control') + * }); + * + * return response.json(); + * } + * ``` + * + * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. + * + * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API instead. + */ + setHeaders(headers: Record): void; + /** + * The requested URL. + */ + url: URL; + /** + * `true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information + * related to the data request in this case. Use this property instead if the distinction is important to you. + */ + isDataRequest: boolean; + /** + * `true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server. + */ + isSubRequest: boolean; + } + + /** + * A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method. + * + * It receives `Params` as the first generic argument, which you can skip by using [generated types](https://kit.svelte.dev/docs/types#generated-types) instead. + */ + export type RequestHandler< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null + > = (event: RequestEvent) => MaybePromise; + + export interface ResolveOptions { + /** + * Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML + * (they could include an element's opening tag but not its closing tag, for example) + * but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components. + * @param input the html chunk and the info if this is the last chunk + */ + transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; + /** + * Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. + * By default, none will be included. + * @param name header name + * @param value header value + */ + filterSerializedResponseHeaders?(name: string, value: string): boolean; + /** + * Determines what should be added to the `` tag to preload it. + * By default, `js` and `css` files will be preloaded. + * @param input the type of the file and its path + */ + preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; + } + + export interface RouteDefinition { + id: string; + api: { + methods: Array; + }; + page: { + methods: Array>; + }; + pattern: RegExp; + prerender: PrerenderOption; + segments: RouteSegment[]; + methods: Array; + config: Config; + } + + export class Server { + constructor(manifest: SSRManifest); + init(options: ServerInitOptions): Promise; + respond(request: Request, options: RequestOptions): Promise; + } + + export interface ServerInitOptions { + /** A map of environment variables */ + env: Record; + /** A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work */ + read?: (file: string) => ReadableStream; + } + + export interface SSRManifest { + appDir: string; + appPath: string; + assets: Set; + mimeTypes: Record; + + /** private fields */ + _: { + client: NonNullable; + nodes: SSRNodeLoader[]; + routes: SSRRoute[]; + matchers(): Promise>; + /** A `[file]: size` map of all assets imported by server code */ + server_assets: Record; + }; + } + + /** + * The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `ServerLoad` directly. + */ + export type ServerLoad< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > = (event: ServerLoadEvent) => MaybePromise; + + export interface ServerLoadEvent< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + RouteId extends string | null = string | null + > extends RequestEvent { + /** + * `await parent()` returns data from parent `+layout.server.js` `load` functions. + * + * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. + */ + parent(): Promise; + /** + * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. + * + * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. + * + * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). + * + * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). + * + * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. + * + * ```js + * /// file: src/routes/+page.js + * let count = 0; + * export async function load({ depends }) { + * depends('increase:count'); + * + * return { count: count++ }; + * } + * ``` + * + * ```html + * /// file: src/routes/+page.svelte + * + * + *

{data.count}

+ * + * ``` + */ + depends(...deps: string[]): void; + /** + * Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: + * + * ```js + * /// file: src/routes/+page.js + * export async function load({ untrack, url }) { + * // Untrack url.pathname so that path changes don't trigger a rerun + * if (untrack(() => url.pathname === '/')) { + * return { message: 'Welcome!' }; + * } + * } + * ``` + */ + untrack(fn: () => T): T; + } + + /** + * Shape of a form action method that is part of `export const actions = {..}` in `+page.server.js`. + * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. + */ + export type Action< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > = (event: RequestEvent) => MaybePromise; + + /** + * Shape of the `export const actions = {..}` object in `+page.server.js`. + * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. + */ + export type Actions< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > = Record>; + + /** + * When calling a form action via fetch, the response will be one of these shapes. + * ```svelte + * { + * return ({ result }) => { + * // result is of type ActionResult + * }; + * }} + * ``` + */ + export type ActionResult< + Success extends Record | undefined = Record, + Failure extends Record | undefined = Record + > = + | { type: 'success'; status: number; data?: Success } + | { type: 'failure'; status: number; data?: Failure } + | { type: 'redirect'; status: number; location: string } + | { type: 'error'; status?: number; error: any }; + + /** + * The object returned by the [`error`](https://kit.svelte.dev/docs/modules#sveltejs-kit-error) function. + */ + export interface HttpError { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ + status: number; + /** The content of the error. */ + body: App.Error; + } + + /** + * The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function + */ + export interface Redirect { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. */ + status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; + /** The location to redirect to. */ + location: string; + } + + export type SubmitFunction< + Success extends Record | undefined = Record, + Failure extends Record | undefined = Record + > = (input: { + action: URL; + formData: FormData; + formElement: HTMLFormElement; + controller: AbortController; + submitter: HTMLElement | null; + cancel(): void; + }) => MaybePromise< + | void + | ((opts: { + formData: FormData; + formElement: HTMLFormElement; + action: URL; + result: ActionResult; + /** + * Call this to get the default behavior of a form submission response. + * @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. + * @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission. + */ + update(options?: { reset?: boolean; invalidateAll?: boolean }): Promise; + }) => void) + >; + + /** + * The type of `export const snapshot` exported from a page or layout component. + */ + export interface Snapshot { + capture: () => T; + restore: (snapshot: T) => void; + } + interface AdapterEntry { + /** + * A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication. + * For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both + * be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID + */ + id: string; + + /** + * A function that compares the candidate route with the current route to determine + * if it should be grouped with the current route. + * + * Use cases: + * - Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes + * - Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function + */ + filter(route: RouteDefinition): boolean; + + /** + * A function that is invoked once the entry has been created. This is where you + * should write the function to the filesystem and generate redirect manifests. + */ + complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise; + } + + // Based on https://github.com/josh-hemphill/csp-typed-directives/blob/latest/src/csp.types.ts + // + // MIT License + // + // Copyright (c) 2021-present, Joshua Hemphill + // Copyright (c) 2021, Tecnico Corporation + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to deal + // in the Software without restriction, including without limitation the rights + // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + // copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in all + // copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + // SOFTWARE. + + namespace Csp { + type ActionSource = 'strict-dynamic' | 'report-sample'; + type BaseSource = + | 'self' + | 'unsafe-eval' + | 'unsafe-hashes' + | 'unsafe-inline' + | 'wasm-unsafe-eval' + | 'none'; + type CryptoSource = `${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`; + type FrameSource = HostSource | SchemeSource | 'self' | 'none'; + type HostNameScheme = `${string}.${string}` | 'localhost'; + type HostSource = `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`; + type HostProtocolSchemes = `${string}://` | ''; + type HttpDelineator = '/' | '?' | '#' | '\\'; + type PortScheme = `:${number}` | '' | ':*'; + type SchemeSource = 'http:' | 'https:' | 'data:' | 'mediastream:' | 'blob:' | 'filesystem:'; + type Source = HostSource | SchemeSource | CryptoSource | BaseSource; + type Sources = Source[]; + } + + interface CspDirectives { + 'child-src'?: Csp.Sources; + 'default-src'?: Array; + 'frame-src'?: Csp.Sources; + 'worker-src'?: Csp.Sources; + 'connect-src'?: Csp.Sources; + 'font-src'?: Csp.Sources; + 'img-src'?: Csp.Sources; + 'manifest-src'?: Csp.Sources; + 'media-src'?: Csp.Sources; + 'object-src'?: Csp.Sources; + 'prefetch-src'?: Csp.Sources; + 'script-src'?: Array; + 'script-src-elem'?: Csp.Sources; + 'script-src-attr'?: Csp.Sources; + 'style-src'?: Array; + 'style-src-elem'?: Csp.Sources; + 'style-src-attr'?: Csp.Sources; + 'base-uri'?: Array; + sandbox?: Array< + | 'allow-downloads-without-user-activation' + | 'allow-forms' + | 'allow-modals' + | 'allow-orientation-lock' + | 'allow-pointer-lock' + | 'allow-popups' + | 'allow-popups-to-escape-sandbox' + | 'allow-presentation' + | 'allow-same-origin' + | 'allow-scripts' + | 'allow-storage-access-by-user-activation' + | 'allow-top-navigation' + | 'allow-top-navigation-by-user-activation' + >; + 'form-action'?: Array; + 'frame-ancestors'?: Array; + 'navigate-to'?: Array; + 'report-uri'?: string[]; + 'report-to'?: string[]; + + 'require-trusted-types-for'?: Array<'script'>; + 'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>; + 'upgrade-insecure-requests'?: boolean; + + /** @deprecated */ + 'require-sri-for'?: Array<'script' | 'style' | 'script style'>; + + /** @deprecated */ + 'block-all-mixed-content'?: boolean; + + /** @deprecated */ + 'plugin-types'?: Array<`${string}/${string}` | 'none'>; + + /** @deprecated */ + referrer?: Array< + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url' + | 'none' + >; + } + + type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; + + interface Logger { + (msg: string): void; + success(msg: string): void; + error(msg: string): void; + warn(msg: string): void; + minor(msg: string): void; + info(msg: string): void; + } + + type MaybePromise = T | Promise; + + interface Prerendered { + /** + * A map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo.html` and a path like `/bar/` corresponds to `bar/index.html`. + */ + pages: Map< + string, + { + /** The location of the .html file relative to the output directory */ + file: string; + } + >; + /** + * A map of `path` to `{ type }` objects. + */ + assets: Map< + string, + { + /** The MIME type of the asset */ + type: string; + } + >; + /** + * A map of redirects encountered during prerendering. + */ + redirects: Map< + string, + { + status: number; + location: string; + } + >; + /** An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config) */ + paths: string[]; + } + + interface PrerenderHttpErrorHandler { + (details: { + status: number; + path: string; + referrer: string | null; + referenceType: 'linked' | 'fetched'; + message: string; + }): void; + } + + interface PrerenderMissingIdHandler { + (details: { path: string; id: string; referrers: string[]; message: string }): void; + } + + interface PrerenderEntryGeneratorMismatchHandler { + (details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void; + } + + type PrerenderHttpErrorHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler; + type PrerenderMissingIdHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler; + type PrerenderEntryGeneratorMismatchHandlerValue = + | 'fail' + | 'warn' + | 'ignore' + | PrerenderEntryGeneratorMismatchHandler; + + export type PrerenderOption = boolean | 'auto'; + + interface RequestOptions { + getClientAddress(): string; + platform?: App.Platform; + } + + interface RouteSegment { + content: string; + dynamic: boolean; + rest: boolean; + } + + type TrailingSlash = 'never' | 'always' | 'ignore'; + interface Asset { + file: string; + size: number; + type: string | null; + } + + interface BuildData { + app_dir: string; + app_path: string; + manifest_data: ManifestData; + out_dir: string; + service_worker: string | null; + client: { + start: string; + app: string; + imports: string[]; + stylesheets: string[]; + fonts: string[]; + uses_env_dynamic_public: boolean; + } | null; + server_manifest: import('vite').Manifest; + } + + interface ManifestData { + assets: Asset[]; + hooks: { + client: string | null; + server: string | null; + universal: string | null; + }; + nodes: PageNode[]; + routes: RouteData[]; + matchers: Record; + } + + interface PageNode { + depth: number; + /** The +page.svelte */ + component?: string; // TODO supply default component if it's missing (bit of an edge case) + /** The +page.js/.ts */ + universal?: string; + /** The +page.server.js/ts */ + server?: string; + parent_id?: string; + parent?: PageNode; + /** Filled with the pages that reference this layout (if this is a layout) */ + child_pages?: PageNode[]; + } + + type RecursiveRequired = { + // Recursive implementation of TypeScript's Required utility type. + // Will recursively continue until it reaches a primitive or Function + [K in keyof T]-?: Extract extends never // If it does not have a Function type + ? RecursiveRequired // recursively continue through. + : T[K]; // Use the exact type for everything else + }; + + interface RouteParam { + name: string; + matcher: string; + optional: boolean; + rest: boolean; + chained: boolean; + } + + /** + * Represents a route segment in the app. It can either be an intermediate node + * with only layout/error pages, or a leaf, at which point either `page` and `leaf` + * or `endpoint` is set. + */ + interface RouteData { + id: string; + parent: RouteData | null; + + segment: string; + pattern: RegExp; + params: RouteParam[]; + + layout: PageNode | null; + error: PageNode | null; + leaf: PageNode | null; + + page: { + layouts: Array; + errors: Array; + leaf: number; + } | null; + + endpoint: { + file: string; + } | null; + } + + interface SSRComponent { + default: { + render(props: Record): { + html: string; + head: string; + css: { + code: string; + map: any; // TODO + }; + }; + }; + } + + type SSRComponentLoader = () => Promise; + + interface SSRNode { + component: SSRComponentLoader; + /** index into the `components` array in client/manifest.js */ + index: number; + /** external JS files */ + imports: string[]; + /** external CSS files */ + stylesheets: string[]; + /** external font files */ + fonts: string[]; + /** inlined styles */ + inline_styles?(): MaybePromise>; + + universal: { + load?: Load; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + server: { + load?: ServerLoad; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + actions?: Actions; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + universal_id: string; + server_id: string; + } + + type SSRNodeLoader = () => Promise; + + interface PageNodeIndexes { + errors: Array; + layouts: Array; + leaf: number; + } + + type PrerenderEntryGenerator = () => MaybePromise>>; + + type SSREndpoint = Partial> & { + prerender?: PrerenderOption; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; + fallback?: RequestHandler; + }; + + interface SSRRoute { + id: string; + pattern: RegExp; + params: RouteParam[]; + page: PageNodeIndexes | null; + endpoint: (() => Promise) | null; + endpoint_id?: string; + } + + type ValidatedConfig = Config & { + kit: ValidatedKitConfig; + extensions: string[]; + }; + + type ValidatedKitConfig = Omit, 'adapter'> & { + adapter?: Adapter; + }; + /** + * Throws an error with a HTTP status code and an optional message. + * When called during request handling, this will cause SvelteKit to + * return an error response without invoking `handleError`. + * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. + * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. + * @throws {HttpError} This error instructs SvelteKit to initiate HTTP error handling. + * @throws {Error} If the provided status is invalid (not between 400 and 599). + */ + export function error(status: number, body: App.Error): never; + /** + * Throws an error with a HTTP status code and an optional message. + * When called during request handling, this will cause SvelteKit to + * return an error response without invoking `handleError`. + * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. + * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. + * @throws {HttpError} This error instructs SvelteKit to initiate HTTP error handling. + * @throws {Error} If the provided status is invalid (not between 400 and 599). + */ + export function error(status: number, body?: { + message: string; + } extends App.Error ? App.Error | string | undefined : never): never; + /** + * Checks whether this is an error thrown by {@link error}. + * @param status The status to filter for. + * */ + export function isHttpError(e: unknown, status?: T | undefined): e is HttpError_1 & { + status: T extends undefined ? never : T; + }; + /** + * Redirect a request. When called during request handling, SvelteKit will return a redirect response. + * Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it. + * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308. + * @param location The location to redirect to. + * @throws {Redirect} This error instructs SvelteKit to redirect to the specified location. + * @throws {Error} If the provided status is invalid. + * */ + export function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number), location: string | URL): never; + /** + * Checks whether this is a redirect thrown by {@link redirect}. + * @param e The object to check. + * */ + export function isRedirect(e: unknown): e is Redirect_1; + /** + * Create a JSON `Response` object from the supplied data. + * @param data The value that will be serialized as JSON. + * @param init Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically. + */ + export function json(data: any, init?: ResponseInit | undefined): Response; + /** + * Create a `Response` object from the supplied body. + * @param body The value that will be used as-is. + * @param init Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically. + */ + export function text(body: string, init?: ResponseInit | undefined): Response; + /** + * Create an `ActionFailure` object. + * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * */ + export function fail(status: number): ActionFailure; + /** + * Create an `ActionFailure` object. + * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param data Data associated with the failure (e.g. validation errors) + * */ + export function fail | undefined = undefined>(status: number, data: T): ActionFailure; + export type LessThan = TNumber extends TArray['length'] ? TArray[number] : LessThan; + export type NumericRange = Exclude, LessThan>; + export const VERSION: string; + class HttpError_1 { + + constructor(status: number, body: { + message: string; + } extends App.Error ? (App.Error | string | undefined) : App.Error); + status: number; + body: App.Error; + toString(): string; + } + class Redirect_1 { + + constructor(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308, location: string); + status: 301 | 302 | 303 | 307 | 308 | 300 | 304 | 305 | 306; + location: string; + } + + export {}; +} + +declare module '@sveltejs/kit/hooks' { + /** + * A helper function for sequencing multiple `handle` calls in a middleware-like manner. + * The behavior for the `handle` options is as follows: + * - `transformPageChunk` is applied in reverse order and merged + * - `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called + * - `filterSerializedResponseHeaders` behaves the same as `preload` + * + * ```js + * /// file: src/hooks.server.js + * import { sequence } from '@sveltejs/kit/hooks'; + * + * /// type: import('@sveltejs/kit').Handle + * async function first({ event, resolve }) { + * console.log('first pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * // transforms are applied in reverse order + * console.log('first transform'); + * return html; + * }, + * preload: () => { + * // this one wins as it's the first defined in the chain + * console.log('first preload'); + * } + * }); + * console.log('first post-processing'); + * return result; + * } + * + * /// type: import('@sveltejs/kit').Handle + * async function second({ event, resolve }) { + * console.log('second pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * console.log('second transform'); + * return html; + * }, + * preload: () => { + * console.log('second preload'); + * }, + * filterSerializedResponseHeaders: () => { + * // this one wins as it's the first defined in the chain + * console.log('second filterSerializedResponseHeaders'); + * } + * }); + * console.log('second post-processing'); + * return result; + * } + * + * export const handle = sequence(first, second); + * ``` + * + * The example above would print: + * + * ``` + * first pre-processing + * first preload + * second pre-processing + * second filterSerializedResponseHeaders + * second transform + * first transform + * second post-processing + * first post-processing + * ``` + * + * @param handlers The chain of `handle` functions + * */ + export function sequence(...handlers: import('@sveltejs/kit').Handle[]): import('@sveltejs/kit').Handle; + + export {}; +} + +declare module '@sveltejs/kit/node' { + export function getRequest({ request, base, bodySizeLimit }: { + request: import('http').IncomingMessage; + base: string; + bodySizeLimit?: number; + }): Promise; + + export function setResponse(res: import('http').ServerResponse, response: Response): Promise; + /** + * Converts a file on disk to a readable stream + * @since 2.4.0 + */ + export function createReadableStream(file: string): ReadableStream; + + export {}; +} + +declare module '@sveltejs/kit/node/polyfills' { + /** + * Make various web APIs available as globals: + * - `crypto` + * - `File` + */ + export function installPolyfills(): void; + + export {}; +} + +declare module '@sveltejs/kit/vite' { + /** + * Returns the SvelteKit Vite plugins. + * */ + export function sveltekit(): Promise; + + export {}; +} + +declare module '$app/environment' { + /** + * `true` if the app is running in the browser. + */ + export const browser: boolean; + + /** + * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. + */ + export const dev: boolean; + + /** + * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. + */ + export const building: boolean; + + /** + * The value of `config.kit.version.name`. + */ + export const version: string; + + export {}; +} + +declare module '$app/forms' { + /** + * Use this function to deserialize the response from a form submission. + * Usage: + * + * ```js + * import { deserialize } from '$app/forms'; + * + * async function handleSubmit(event) { + * const response = await fetch('/form?/action', { + * method: 'POST', + * body: new FormData(event.target) + * }); + * + * const result = deserialize(await response.text()); + * // ... + * } + * ``` + * */ + export function deserialize | undefined, Failure extends Record | undefined>(result: string): import("@sveltejs/kit").ActionResult; + /** + * This action enhances a `` element that otherwise would work without JavaScript. + * + * The `submit` function is called upon submission with the given FormData and the `action` that should be triggered. + * If `cancel` is called, the form will not be submitted. + * You can use the abort `controller` to cancel the submission in case another one starts. + * If a function is returned, that function is called with the response from the server. + * If nothing is returned, the fallback will be used. + * + * If this function or its return value isn't set, it + * - falls back to updating the `form` prop with the returned data if the action is on the same page as the form + * - updates `$page.status` + * - resets the `` element and invalidates all data in case of successful submission with no redirect response + * - redirects in case of a redirect response + * - redirects to the nearest error page in case of an unexpected error + * + * If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. + * @param form_element The form element + * @param submit Submit callback + */ + export function enhance | undefined, Failure extends Record | undefined>(form_element: HTMLFormElement, submit?: import("@sveltejs/kit").SubmitFunction): { + destroy(): void; + }; + /** + * This action updates the `form` property of the current page with the given data and updates `$page.status`. + * In case of an error, it redirects to the nearest error page. + * */ + export function applyAction | undefined, Failure extends Record | undefined>(result: import("@sveltejs/kit").ActionResult): Promise; + + export {}; +} + +declare module '$app/navigation' { + /** + * A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. + * + * `afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * */ + export function afterNavigate(callback: (navigation: import('@sveltejs/kit').AfterNavigate) => void): void; + /** + * A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. + * + * Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response. + * + * When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`. + * + * If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`. + * + * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * */ + export function beforeNavigate(callback: (navigation: import('@sveltejs/kit').BeforeNavigate) => void): void; + /** + * A lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations. + * + * If you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user. + * + * If a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated. + * + * `onNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * */ + export function onNavigate(callback: (navigation: import('@sveltejs/kit').OnNavigate) => MaybePromise<(() => void) | void>): void; + /** + * If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. + * This is generally discouraged, since it breaks user expectations. + * */ + export function disableScrollHandling(): void; + /** + * Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`. + * For external URLs, use `window.location = url` instead of calling `goto(url)`. + * + * @param url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. + * @param {Object} opts Options related to the navigation + * */ + export function goto(url: string | URL, opts?: { + replaceState?: boolean | undefined; + noScroll?: boolean | undefined; + keepFocus?: boolean | undefined; + invalidateAll?: boolean | undefined; + state?: App.PageState | undefined; + } | undefined): Promise; + /** + * Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. + * + * If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). + * To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. + * + * The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. + * This can be useful if you want to invalidate based on a pattern instead of a exact match. + * + * ```ts + * // Example: Match '/path' regardless of the query parameters + * import { invalidate } from '$app/navigation'; + * + * invalidate((url) => url.pathname === '/path'); + * ``` + * @param resource The invalidated URL + * */ + export function invalidate(resource: string | URL | ((url: URL) => boolean)): Promise; + /** + * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. + * */ + export function invalidateAll(): Promise; + /** + * Programmatically preloads the given page, which means + * 1. ensuring that the code for the page is loaded, and + * 2. calling the page's load function with the appropriate options. + * + * This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. + * If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. + * Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete. + * + * @param href Page to preload + * */ + export function preloadData(href: string): Promise<{ + type: 'loaded'; + status: number; + data: Record; + } | { + type: 'redirect'; + location: string; + }>; + /** + * Programmatically imports the code for routes that haven't yet been fetched. + * Typically, you might call this to speed up subsequent navigation. + * + * You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`). + * + * Unlike `preloadData`, this won't call `load` functions. + * Returns a Promise that resolves when the modules have been imported. + * + * */ + export function preloadCode(pathname: string): Promise; + /** + * Programmatically create a new history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing). + * + * */ + export function pushState(url: string | URL, state: App.PageState): void; + /** + * Programmatically replace the current history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing). + * + * */ + export function replaceState(url: string | URL, state: App.PageState): void; + type MaybePromise = T | Promise; + + export {}; +} + +declare module '$app/paths' { + /** + * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). + * + * Example usage: `Link` + */ + export let base: '' | `/${string}`; + + /** + * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/configuration#paths). + * + * > If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL. + */ + export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; + + /** + * Populate a route ID with params to resolve a pathname. + * @example + * ```js + * resolveRoute( + * `/blog/[slug]/[...somethingElse]`, + * { + * slug: 'hello-world', + * somethingElse: 'something/else' + * } + * ); // `/blog/hello-world/something/else` + * ``` + */ + export function resolveRoute(id: string, params: Record): string; + + export {}; +} + +declare module '$app/server' { + /** + * Read the contents of an imported asset from the filesystem + * @example + * ```js + * import { read } from '$app/server'; + * import somefile from './somefile.txt'; + * + * const asset = read(somefile); + * const text = await asset.text(); + * ``` + * @since 2.4.0 + */ + export function read(asset: string): Response; + + export {}; +} + +declare module '$app/stores' { + export function getStores(): { + + page: typeof page; + + navigating: typeof navigating; + + updated: typeof updated; + }; + /** + * A readable store whose value contains page data. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * + * */ + export const page: import('svelte/store').Readable; + /** + * A readable store. + * When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. + * When navigating finishes, its value reverts to `null`. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * */ + export const navigating: import('svelte/store').Readable; + /** + * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * */ + export const updated: import('svelte/store').Readable & { + check(): Promise; + }; + + export {}; +}/** + * It's possible to tell SvelteKit how to type objects inside your app by declaring the `App` namespace. By default, a new project will have a file called `src/app.d.ts` containing the following: + * + * ```ts + * declare global { + * namespace App { + * // interface Error {} + * // interface Locals {} + * // interface PageData {} + * // interface PageState {} + * // interface Platform {} + * } + * } + * + * export {}; + * ``` + * + * The `export {}` line exists because without it, the file would be treated as an _ambient module_ which prevents you from adding `import` declarations. + * If you need to add ambient `declare module` declarations, do so in a separate file like `src/ambient.d.ts`. + * + * By populating these interfaces, you will gain type safety when using `event.locals`, `event.platform`, and `data` from `load` functions. + */ +declare namespace App { + /** + * Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape. + */ + export interface Error { + message: string; + } + + /** + * The interface that defines `event.locals`, which can be accessed in [hooks](https://kit.svelte.dev/docs/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. + */ + export interface Locals {} + + /** + * Defines the common shape of the [$page.data store](https://kit.svelte.dev/docs/modules#$app-stores-page) - that is, the data that is shared between all pages. + * The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly. + * Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`). + */ + export interface PageData {} + + /** + * The shape of the `$page.state` object, which can be manipulated using the [`pushState`](https://kit.svelte.dev/docs/modules#$app-navigation-pushstate) and [`replaceState`](https://kit.svelte.dev/docs/modules#$app-navigation-replacestate) functions from `$app/navigation`. + */ + export interface PageState {} + + /** + * If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. + */ + export interface Platform {} +} + +/** + * This module is only available to [service workers](https://kit.svelte.dev/docs/service-workers). + */ +declare module '$service-worker' { + /** + * The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory. + * Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified. + */ + export const base: string; + /** + * An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. + * During development, this is an empty array. + */ + export const build: string[]; + /** + * An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](https://kit.svelte.dev/docs/configuration) + */ + export const files: string[]; + /** + * An array of pathnames corresponding to prerendered pages and endpoints. + * During development, this is an empty array. + */ + export const prerendered: string[]; + /** + * See [`config.kit.version`](https://kit.svelte.dev/docs/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches. + */ + export const version: string; +} + +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@sveltejs/kit/types/index.d.ts.map b/node_modules/@sveltejs/kit/types/index.d.ts.map new file mode 100644 index 00000000..b4a957fc --- /dev/null +++ b/node_modules/@sveltejs/kit/types/index.d.ts.map @@ -0,0 +1,159 @@ +{ + "version": 3, + "file": "index.d.ts", + "names": [ + "Adapter", + "LoadProperties", + "AwaitedActions", + "ActionFailure", + "Builder", + "Config", + "Cookies", + "Emulator", + "KitConfig", + "Handle", + "HandleServerError", + "HandleClientError", + "HandleFetch", + "Reroute", + "Load", + "LoadEvent", + "NavigationEvent", + "NavigationTarget", + "NavigationType", + "Navigation", + "BeforeNavigate", + "OnNavigate", + "AfterNavigate", + "Page", + "ParamMatcher", + "RequestEvent", + "RequestHandler", + "ResolveOptions", + "RouteDefinition", + "Server", + "ServerInitOptions", + "SSRManifest", + "ServerLoad", + "ServerLoadEvent", + "Action", + "Actions", + "ActionResult", + "HttpError", + "Redirect", + "SubmitFunction", + "Snapshot", + "AdapterEntry", + "Csp", + "CspDirectives", + "HttpMethod", + "Logger", + "MaybePromise", + "Prerendered", + "PrerenderHttpErrorHandler", + "PrerenderMissingIdHandler", + "PrerenderEntryGeneratorMismatchHandler", + "PrerenderHttpErrorHandlerValue", + "PrerenderMissingIdHandlerValue", + "PrerenderEntryGeneratorMismatchHandlerValue", + "PrerenderOption", + "RequestOptions", + "RouteSegment", + "TrailingSlash", + "Asset", + "BuildData", + "ManifestData", + "PageNode", + "RecursiveRequired", + "RouteParam", + "RouteData", + "SSRComponent", + "SSRComponentLoader", + "SSRNode", + "SSRNodeLoader", + "PageNodeIndexes", + "PrerenderEntryGenerator", + "SSREndpoint", + "SSRRoute", + "ValidatedConfig", + "ValidatedKitConfig", + "isHttpError", + "redirect", + "isRedirect", + "json", + "text", + "LessThan", + "NumericRange", + "VERSION", + "sequence", + "getRequest", + "setResponse", + "createReadableStream", + "installPolyfills", + "sveltekit", + "browser", + "dev", + "building", + "version", + "deserialize", + "enhance", + "applyAction", + "afterNavigate", + "beforeNavigate", + "onNavigate", + "disableScrollHandling", + "goto", + "invalidate", + "invalidateAll", + "preloadData", + "preloadCode", + "pushState", + "replaceState", + "base", + "assets", + "resolveRoute", + "read", + "getStores", + "page", + "navigating", + "updated" + ], + "sources": [ + "../src/exports/public.d.ts", + "../src/runtime/control.js", + "../src/types/private.d.ts", + "../src/types/internal.d.ts", + "../src/exports/index.js", + "../src/version.js", + "../src/exports/hooks/sequence.js", + "../src/exports/node/index.js", + "../src/exports/node/polyfills.js", + "../src/exports/vite/index.js", + "../src/runtime/app/environment/types.d.ts", + "../src/runtime/app/forms.js", + "../src/runtime/client/client.js", + "../src/runtime/app/paths/types.d.ts", + "../src/runtime/app/server/index.js", + "../src/runtime/app/stores.js" + ], + "sourcesContent": [ + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null + ], + "mappings": ";;;;;;;;;kBA2BiBA,OAAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;aA2BZC,cAAcA;;;;;;aAMdC,cAAcA;;;;;;;;;;;;;;;kBAeTC,aAAaA;;;;;;;;;;;;;;;;;kBAiBbC,OAAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkGPC,MAAMA;;;;;;;;;;;;;;;;;;;;;kBAqBNC,OAAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA4DPC,QAAQA;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iBAoCjBC,WAAWA;;;;;iBA2BXC,SAASA;;;;;iBA4CTC,YAAYA;MV1sDhB5D,YAAYA;;;;;;;;;;;YWtJb6D,IAAIA;;;;;;;YAOJC,MAAMA;;;;;;;;;;;;;;;iBAeDC,YAAYA;;;;;;;;;;;;;;;;;;iBCRZC,IAAIA;;;;;;iBCXPC,SAASA;;;;;;;;;;;;;;cAwBTC,IAAIA;;;;;;;;cAeJC,UAAUA;;;;;;cAaVC,OAAOA", + "ignoreList": [] +} \ No newline at end of file diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/LICENSE b/node_modules/@sveltejs/vite-plugin-svelte-inspector/LICENSE new file mode 100644 index 00000000..c1a5d8f0 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 [these people](https://github.com/sveltejs/vite-plugin-svelte/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/README.md b/node_modules/@sveltejs/vite-plugin-svelte-inspector/README.md new file mode 100644 index 00000000..bbdf50c8 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/README.md @@ -0,0 +1,26 @@ +# @sveltejs/vite-plugin-svelte-inspector + +A [Svelte](https://svelte.dev) inspector plugin for [Vite](https://vitejs.dev). + +## Usage + +```js +// vite.config.js +import { defineConfig } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { svelteInspector } from '@sveltejs/vite-plugin-svelte-inspector'; + +export default defineConfig({ + plugins: [ + // the svelte plugin is required to work + svelte(), + svelteInspector({ + /* plugin options */ + }) + ] +}); +``` + +## License + +[MIT](./LICENSE) diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/package.json b/node_modules/@sveltejs/vite-plugin-svelte-inspector/package.json new file mode 100644 index 00000000..aedd57b6 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/package.json @@ -0,0 +1,56 @@ +{ + "name": "@sveltejs/vite-plugin-svelte-inspector", + "version": "2.1.0", + "license": "MIT", + "author": "dominikg", + "files": [ + "src", + "types" + ], + "type": "module", + "types": "types/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./types/index.d.ts", + "default": "./src/index.js" + } + } + }, + "engines": { + "node": "^18.0.0 || >=20" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sveltejs/vite-plugin-svelte.git", + "directory": "packages/vite-plugin-svelte-inspector" + }, + "keywords": [ + "vite-plugin", + "vite plugin", + "vite", + "svelte" + ], + "bugs": { + "url": "https://github.com/sveltejs/vite-plugin-svelte/issues" + }, + "homepage": "https://github.com/sveltejs/vite-plugin-svelte#readme", + "dependencies": { + "debug": "^4.3.4" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^3.0.0", + "svelte": "^4.0.0 || ^5.0.0-next.0", + "vite": "^5.0.0" + }, + "devDependencies": { + "@types/debug": "^4.1.12", + "svelte": "^4.2.12", + "vite": "^5.2.8" + }, + "scripts": { + "check:publint": "publint --strict", + "check:types": "tsc --noEmit", + "generate:types": "dts-buddy -m \"@sveltejs/vite-plugin-svelte-inspector:src/public.d.ts\"" + } +} \ No newline at end of file diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/debug.js b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/debug.js new file mode 100644 index 00000000..0575a83f --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/debug.js @@ -0,0 +1,3 @@ +import _debug from 'debug'; + +export const debug = _debug('vite-plugin-svelte-inspector'); diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/index.js b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/index.js new file mode 100644 index 00000000..1f2e6ca4 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/index.js @@ -0,0 +1,113 @@ +import { normalizePath } from 'vite'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { debug } from './debug.js'; +import { defaultInspectorOptions, parseEnvironmentOptions } from './options.js'; +import { cleanUrl } from './utils.js'; + +function getInspectorPath() { + const pluginPath = normalizePath(path.dirname(fileURLToPath(import.meta.url))); + return pluginPath.replace( + /\/vite-plugin-svelte-inspector\/src$/, + '/vite-plugin-svelte-inspector/src/runtime/' + ); +} + +/** + * @param {Partial} [options] + * @returns {import('vite').Plugin} + */ +export function svelteInspector(options) { + const inspectorPath = getInspectorPath(); + debug(`svelte inspector path: ${inspectorPath}`); + + /** @type {import('vite').ResolvedConfig} */ + let viteConfig; + /** @type {import('./public.d.ts').Options} */ + let inspectorOptions; + let disabled = false; + + return { + name: 'vite-plugin-svelte-inspector', + apply: 'serve', + enforce: 'pre', + + configResolved(config) { + viteConfig = config; + + const environmentOptions = parseEnvironmentOptions(config); + if (environmentOptions === false) { + debug('environment options set to false, inspector disabled'); + disabled = true; + return; + } + + // Handle config from svelte.config.js through vite-plugin-svelte + const vps = config.plugins.find((p) => p.name === 'vite-plugin-svelte'); + const configFileOptions = vps?.api?.options?.inspector; + + // vite-plugin-svelte can only pass options through it's `api` instead of `options`. + // that means this plugin could be created but should be disabled, so we check this case here. + if (vps && !options && !configFileOptions && !environmentOptions) { + debug("vite-plugin-svelte didn't pass options, inspector disabled"); + disabled = true; + return; + } + + if (environmentOptions === true) { + inspectorOptions = defaultInspectorOptions; + } else { + inspectorOptions = { + ...defaultInspectorOptions, + ...configFileOptions, + ...options, + ...(environmentOptions || {}) + }; + } + + inspectorOptions.__internal = { + base: config.base?.replace(/\/$/, '') || '' + }; + }, + + async resolveId(importee, _, options) { + if (options?.ssr || disabled) { + return; + } + if (importee.startsWith('virtual:svelte-inspector-options')) { + return importee; + } else if (importee.startsWith('virtual:svelte-inspector-path:')) { + return importee.replace('virtual:svelte-inspector-path:', inspectorPath); + } + }, + + async load(id, options) { + if (options?.ssr || disabled) { + return; + } + if (id === 'virtual:svelte-inspector-options') { + return `export default ${JSON.stringify(inspectorOptions ?? {})}`; + } else if (id.startsWith(inspectorPath)) { + // read file ourselves to avoid getting shut out by vites fs.allow check + const file = cleanUrl(id); + if (fs.existsSync(id)) { + return await fs.promises.readFile(file, 'utf-8'); + } else { + viteConfig.logger.error( + `[vite-plugin-svelte-inspector] failed to find svelte-inspector: ${id}` + ); + } + } + }, + + transform(code, id, options) { + if (options?.ssr || disabled) { + return; + } + if (id.includes('vite/dist/client/client.mjs')) { + return { code: `${code}\nimport('virtual:svelte-inspector-path:load-inspector.js')` }; + } + } + }; +} diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/options.js b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/options.js new file mode 100644 index 00000000..a4537b99 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/options.js @@ -0,0 +1,62 @@ +import { loadEnv } from 'vite'; +import { debug } from './debug.js'; + +/** @type {import('./public.d.ts').Options} */ +export const defaultInspectorOptions = { + toggleKeyCombo: process.platform === 'darwin' ? 'meta-shift' : 'control-shift', + navKeys: { parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }, + escapeKeys: ['Backspace', 'Escape'], + openKey: 'Enter', + holdMode: true, + showToggleButton: 'active', + toggleButtonPos: 'top-right', + customStyles: true +}; + +/** + * @param {import('vite').ResolvedConfig} config + * @returns {Partial | boolean | void} + */ +export function parseEnvironmentOptions(config) { + const env = loadEnv(config.mode, config.envDir ?? process.cwd(), 'SVELTE_INSPECTOR'); + const options = env?.SVELTE_INSPECTOR_OPTIONS; + const toggle = env?.SVELTE_INSPECTOR_TOGGLE; + if (options) { + try { + const parsed = JSON.parse(options); + const parsedType = typeof parsed; + if (parsedType === 'boolean') { + return parsed; + } else if (parsedType === 'object') { + if (Array.isArray(parsed)) { + throw new Error('invalid type, expected object map but got array'); + } + const parsedKeys = Object.keys(parsed); + const defaultKeys = Object.keys(defaultInspectorOptions); + const unknownKeys = parsedKeys.filter((k) => !defaultKeys.includes(k)); + if (unknownKeys.length) { + config.logger.warn( + `[vite-plugin-svelte-inspector] ignoring unknown options in environment SVELTE_INSPECTOR_OPTIONS: ${unknownKeys.join( + ', ' + )}` + ); + for (const key of unknownKeys) { + delete parsed[key]; + } + } + debug('loaded environment config', parsed); + return parsed; + } + } catch (e) { + config.logger.error( + `[vite-plugin-svelte-inspector] failed to parse inspector options from environment SVELTE_INSPECTOR_OPTIONS="${options}"\n${e}` + ); + } + } else if (toggle) { + const keyConfig = { + toggleKeyCombo: toggle + }; + debug('loaded environment config', keyConfig); + return keyConfig; + } +} diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/public.d.ts b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/public.d.ts new file mode 100644 index 00000000..7932bb75 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/public.d.ts @@ -0,0 +1,78 @@ +export interface Options { + /** + * define a key combo to toggle inspector, + * @default 'meta-shift' on mac, 'control-shift' on other os + * + * any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by - + * examples: control-shift, control-o, control-alt-s meta-x control-meta + * Some keys have native behavior (e.g. alt-s opens history menu on firefox). + * To avoid conflicts or accidentally typing into inputs, modifier only combinations are recommended. + */ + toggleKeyCombo?: string; + + /** + * define keys to select elements with via keyboard + * @default {parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' } + * + * improves accessibility and also helps when you want to select elements that do not have a hoverable surface area + * due to tight wrapping + * + * A note for users of screen-readers: + * If you are using arrow keys to navigate the page itself, change the navKeys to avoid conflicts. + * e.g. navKeys: {parent: 'w', prev: 'a', child: 's', next: 'd'} + * + * + * parent: select closest parent + * child: select first child (or grandchild) + * next: next sibling (or parent if no next sibling exists) + * prev: previous sibling (or parent if no prev sibling exists) + */ + navKeys?: { parent: string; child: string; next: string; prev: string }; + + /** + * define key to open the editor for the currently selected dom node + * + * @default 'Enter' + */ + openKey?: string; + + /** + * define keys to close the inspector + * @default ['Backspace', 'Escape'] + */ + escapeKeys?: string[]; + + /** + * inspector is automatically disabled when releasing toggleKeyCombo after holding it for a longpress + * @default true + */ + holdMode?: boolean; + + /** + * when to show the toggle button + * @default 'active' + */ + showToggleButton?: 'always' | 'active' | 'never'; + + /** + * where to display the toggle button + * @default top-right + */ + toggleButtonPos?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; + + /** + * inject custom styles when inspector is active + */ + customStyles?: boolean; + + /** + * internal options that are automatically set, not to be set or used by users + * @internal + */ + __internal?: { + // vite base url + base: string; + }; +} + +export * from './index.js'; diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/runtime/Inspector.svelte b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/runtime/Inspector.svelte new file mode 100644 index 00000000..7bcf719f --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/runtime/Inspector.svelte @@ -0,0 +1,400 @@ + + +{#if show_toggle} +