From 36578be81519cbe5114537530f0d8eeda3b6766b Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 00:24:13 +0200 Subject: [PATCH 01/31] feat: replace pnpmBuildDependency with sv.file + pnpm helper and file.findUp --- .changeset/remove-pnpm-build-dependency.md | 6 ++ documentation/docs/50-api/10-sv.md | 2 +- documentation/docs/50-api/20-sv-utils.md | 15 +++++ packages/sv-utils/src/index.ts | 3 + packages/sv-utils/src/pnpm.ts | 25 ++++++++ packages/sv/src/addons/drizzle.ts | 7 +- packages/sv/src/addons/tailwindcss.ts | 8 ++- packages/sv/src/cli/add.ts | 7 +- .../pnpm-workspace.yaml | 2 + packages/sv/src/core/config.ts | 2 - packages/sv/src/core/engine.ts | 11 +--- packages/sv/src/core/package-manager.ts | 64 ++++--------------- packages/sv/src/core/workspace.ts | 15 +++++ packages/sv/src/testing.ts | 4 +- 14 files changed, 94 insertions(+), 77 deletions(-) create mode 100644 .changeset/remove-pnpm-build-dependency.md create mode 100644 packages/sv-utils/src/pnpm.ts create mode 100644 packages/sv/src/cli/tests/snapshots/create-with-all-addons/pnpm-workspace.yaml diff --git a/.changeset/remove-pnpm-build-dependency.md b/.changeset/remove-pnpm-build-dependency.md new file mode 100644 index 000000000..41b340900 --- /dev/null +++ b/.changeset/remove-pnpm-build-dependency.md @@ -0,0 +1,6 @@ +--- +'sv': minor +'@sveltejs/sv-utils': minor +--- + +feat: replace `sv.pnpmBuildDependency` with `sv.file` + `pnpm.onlyBuiltDependencies` helper and `file.findUp` diff --git a/documentation/docs/50-api/10-sv.md b/documentation/docs/50-api/10-sv.md index 70809023a..7e74f6f57 100644 --- a/documentation/docs/50-api/10-sv.md +++ b/documentation/docs/50-api/10-sv.md @@ -48,7 +48,7 @@ export default defineAddon({ }); ``` -The `sv` object in `run` provides `file`, `dependency`, `devDependency`, `execute`, and `pnpmBuildDependency`. For file transforms (AST-based editing of scripts, Svelte components, CSS, JSON, etc.), see [`@sveltejs/sv-utils`](sv-utils). +The `sv` object in `run` provides `file`, `dependency`, `devDependency`, and `execute`. For file transforms (AST-based editing of scripts, Svelte components, CSS, JSON, etc.) and package manager helpers, see [`@sveltejs/sv-utils`](sv-utils). ## `defineAddonOptions` diff --git a/documentation/docs/50-api/20-sv-utils.md b/documentation/docs/50-api/20-sv-utils.md index 600ca9a0c..b8dcccf43 100644 --- a/documentation/docs/50-api/20-sv-utils.md +++ b/documentation/docs/50-api/20-sv-utils.md @@ -229,3 +229,18 @@ Namespaced helpers for AST manipulation: - **`json.*`** - arrayUpsert, packageScriptsUpsert - **`html.*`** - attribute manipulation - **`text.*`** - upsert lines in flat files (.env, .gitignore) + +## Package manager helpers + +### `pnpm.onlyBuiltDependencies` + +Returns a transform for `pnpm-workspace.yaml` that adds packages to the `onlyBuiltDependencies` list. Use with `sv.file` when the project uses pnpm. + +```js +// @noErrors +import { pnpm } from '@sveltejs/sv-utils'; + +if (packageManager === 'pnpm') { + sv.file(file.findUp('pnpm-workspace.yaml'), pnpm.onlyBuiltDependencies('my-native-dep')); +} +``` diff --git a/packages/sv-utils/src/index.ts b/packages/sv-utils/src/index.ts index 29005fa4a..64c7b21e2 100644 --- a/packages/sv-utils/src/index.ts +++ b/packages/sv-utils/src/index.ts @@ -39,6 +39,9 @@ export * as text from './tooling/text.ts'; export * as json from './tooling/json.ts'; export * as svelte from './tooling/svelte/index.ts'; +// Package manager helpers +export * as pnpm from './pnpm.ts'; + // Transforms — sv-utils = what to do to content, sv = where and when to do it. export { transforms } from './tooling/transforms.ts'; diff --git a/packages/sv-utils/src/pnpm.ts b/packages/sv-utils/src/pnpm.ts new file mode 100644 index 000000000..b9cc34987 --- /dev/null +++ b/packages/sv-utils/src/pnpm.ts @@ -0,0 +1,25 @@ +import type { TransformFn } from './tooling/transforms.ts'; +import { transforms } from './tooling/transforms.ts'; + +/** + * Returns a TransformFn for `pnpm-workspace.yaml` that adds packages to `onlyBuiltDependencies`. + * + * Use with `sv.file`: + * ```ts + * if (packageManager === 'pnpm') { + * sv.file(file.findUp('pnpm-workspace.yaml'), pnpm.onlyBuiltDependencies('my-native-dep')); + * } + * ``` + */ +export function onlyBuiltDependencies(...packages: string[]): TransformFn { + return transforms.yaml(({ data }) => { + const existing = data.get('onlyBuiltDependencies'); + const items: Array<{ value: string } | string> = existing?.items ?? []; + for (const pkg of packages) { + if (items.includes(pkg)) continue; + if (items.some((y) => typeof y === 'object' && y.value === pkg)) continue; + items.push(pkg); + } + data.set('onlyBuiltDependencies', items); + }); +} diff --git a/packages/sv/src/addons/drizzle.ts b/packages/sv/src/addons/drizzle.ts index f807f11cc..d4269a705 100644 --- a/packages/sv/src/addons/drizzle.ts +++ b/packages/sv/src/addons/drizzle.ts @@ -3,6 +3,7 @@ import { dedent, type TransformFn, transforms, + pnpm, resolveCommandArray, fileExists, createPrinter @@ -89,7 +90,7 @@ export default defineAddon({ if (!isKit) return unsupported('Requires SvelteKit'); }, - run: ({ sv, language, options, directory, dependencyVersion, cwd, cancel, file }) => { + run: ({ sv, language, options, directory, dependencyVersion, cwd, cancel, file, packageManager }) => { if (options.database === 'd1' && !dependencyVersion('@sveltejs/adapter-cloudflare')) { return cancel('Cloudflare D1 requires @sveltejs/adapter-cloudflare - add the adapter first'); } @@ -124,7 +125,9 @@ export default defineAddon({ // not a devDependency due to bundling issues sv.dependency('better-sqlite3', '^12.6.2'); sv.devDependency('@types/better-sqlite3', '^7.6.13'); - sv.pnpmBuildDependency('better-sqlite3'); + if (packageManager === 'pnpm') { + sv.file(file.findUp('pnpm-workspace.yaml'), pnpm.onlyBuiltDependencies('better-sqlite3')); + } } if (options.sqlite === 'libsql' || options.sqlite === 'turso') diff --git a/packages/sv/src/addons/tailwindcss.ts b/packages/sv/src/addons/tailwindcss.ts index 5dd26ce2c..151d0fe66 100644 --- a/packages/sv/src/addons/tailwindcss.ts +++ b/packages/sv/src/addons/tailwindcss.ts @@ -1,4 +1,4 @@ -import { transforms } from '@sveltejs/sv-utils'; +import { pnpm, transforms } from '@sveltejs/sv-utils'; import { defineAddon, defineAddonOptions } from '../core/config.ts'; const plugins = [ @@ -30,12 +30,14 @@ export default defineAddon({ shortDescription: 'css framework', homepage: 'https://tailwindcss.com', options, - run: ({ sv, options, file, isKit, directory, dependencyVersion, language }) => { + run: ({ sv, options, file, isKit, directory, dependencyVersion, language, packageManager }) => { const prettierInstalled = Boolean(dependencyVersion('prettier')); sv.devDependency('tailwindcss', '^4.1.18'); sv.devDependency('@tailwindcss/vite', '^4.1.18'); - sv.pnpmBuildDependency('@tailwindcss/oxide'); + if (packageManager === 'pnpm') { + sv.file(file.findUp('pnpm-workspace.yaml'), pnpm.onlyBuiltDependencies('@tailwindcss/oxide')); + } if (prettierInstalled) sv.devDependency('prettier-plugin-tailwindcss', '^0.7.2'); diff --git a/packages/sv/src/cli/add.ts b/packages/sv/src/cli/add.ts index 466613ab6..71c617449 100644 --- a/packages/sv/src/cli/add.ts +++ b/packages/sv/src/cli/add.ts @@ -677,7 +677,7 @@ export async function runAddonsApply({ setupResults: {} }; - const { filesToFormat, pnpmBuildDependencies, status } = await applyAddons({ + const { filesToFormat, status } = await applyAddons({ loadedAddons, workspace, setupResults, @@ -712,10 +712,7 @@ export async function runAddonsApply({ ? await packageManagerPrompt(options.cwd) : options.install; - await addPnpmBuildDependencies(workspace.cwd, packageManager, [ - 'esbuild', - ...pnpmBuildDependencies - ]); + await addPnpmBuildDependencies(workspace.cwd, packageManager, ['esbuild']); const argsFormattedAddons: string[] = []; for (const loaded of successfulAddons) { diff --git a/packages/sv/src/cli/tests/snapshots/create-with-all-addons/pnpm-workspace.yaml b/packages/sv/src/cli/tests/snapshots/create-with-all-addons/pnpm-workspace.yaml new file mode 100644 index 000000000..fd050a463 --- /dev/null +++ b/packages/sv/src/cli/tests/snapshots/create-with-all-addons/pnpm-workspace.yaml @@ -0,0 +1,2 @@ +onlyBuiltDependencies: + - '@tailwindcss/oxide' diff --git a/packages/sv/src/core/config.ts b/packages/sv/src/core/config.ts index 3d00c1412..b0c02226e 100644 --- a/packages/sv/src/core/config.ts +++ b/packages/sv/src/core/config.ts @@ -21,8 +21,6 @@ export type Scripts = { }; export type SvApi = { - /** Add a package to the pnpm onlyBuiltDependencies. */ - pnpmBuildDependency: (pkg: string) => void; /** Add a package to the dependencies. */ dependency: (pkg: string, version: string) => void; /** Add a package to the dev dependencies. */ diff --git a/packages/sv/src/core/engine.ts b/packages/sv/src/core/engine.ts index b0bc4d053..8a8be6df1 100644 --- a/packages/sv/src/core/engine.ts +++ b/packages/sv/src/core/engine.ts @@ -71,11 +71,9 @@ export async function applyAddons({ options }: ApplyAddonOptions): Promise<{ filesToFormat: string[]; - pnpmBuildDependencies: string[]; status: Record; }> { const filesToFormat = new Set(); - const allPnpmBuildDependencies: string[] = []; const status: Record = {}; const addonDefs = loadedAddons.map((l) => l.addon); @@ -95,7 +93,7 @@ export async function applyAddons({ // If we don't have a formatter yet, check if the addon adds one if (!hasFormatter) hasFormatter = !!addonWorkspace.dependencyVersion('prettier'); - const { files, pnpmBuildDependencies, cancels } = await runAddon({ + const { files, cancels } = await runAddon({ workspace: addonWorkspace, workspaceOptions, addon, @@ -104,7 +102,6 @@ export async function applyAddons({ }); files.forEach((f) => filesToFormat.add(f)); - pnpmBuildDependencies.forEach((s) => allPnpmBuildDependencies.push(s)); if (cancels.length === 0) { status[addon.id] = 'success'; } else { @@ -114,7 +111,6 @@ export async function applyAddons({ return { filesToFormat: hasFormatter ? Array.from(filesToFormat) : [], - pnpmBuildDependencies: allPnpmBuildDependencies, status }; } @@ -176,7 +172,6 @@ async function runAddon({ addon, loaded, multiple, workspace, workspaceOptions } } const dependencies: Array<{ pkg: string; version: string; dev: boolean }> = []; - const pnpmBuildDependencies: string[] = []; const sv: SvApi = { file: (path, edit) => { try { @@ -225,9 +220,6 @@ async function runAddon({ addon, loaded, multiple, workspace, workspaceOptions } }, devDependency: (pkg, version) => { dependencies.push({ pkg, version, dev: true }); - }, - pnpmBuildDependency: (pkg) => { - pnpmBuildDependencies.push(pkg); } }; @@ -256,7 +248,6 @@ async function runAddon({ addon, loaded, multiple, workspace, workspaceOptions } return { files: Array.from(files), - pnpmBuildDependencies, cancels }; } diff --git a/packages/sv/src/core/package-manager.ts b/packages/sv/src/core/package-manager.ts index c0ed185c7..8dba53fc8 100644 --- a/packages/sv/src/core/package-manager.ts +++ b/packages/sv/src/core/package-manager.ts @@ -6,7 +6,6 @@ import { color, constructCommand, detect, - isVersionUnsupportedBelow, parse } from '@sveltejs/sv-utils'; import { Option } from 'commander'; @@ -98,63 +97,24 @@ export async function addPnpmBuildDependencies( packageManager: AgentName | null | undefined, allowedPackages: string[] ): Promise { - // other package managers are currently not affected by this change if (!packageManager || packageManager !== 'pnpm' || allowedPackages.length === 0) return; - let confIn: 'package.json' | 'pnpm-workspace.yaml' = 'package.json'; - const pnpmVersion = await getPnpmVersion(); - if (pnpmVersion) { - confIn = isVersionUnsupportedBelow(pnpmVersion, '10.5') - ? 'package.json' - : 'pnpm-workspace.yaml'; - } - // find the workspace root (if present) const found = find.up('pnpm-workspace.yaml', { cwd }); + const content = found ? fs.readFileSync(found, 'utf-8') : ''; + const { data, generateCode } = parse.yaml(content); - if (confIn === 'pnpm-workspace.yaml') { - const content = found ? fs.readFileSync(found, 'utf-8') : ''; - const { data, generateCode } = parse.yaml(content); - - const onlyBuiltDependencies = data.get('onlyBuiltDependencies'); - const items: Array<{ value: string } | string> = onlyBuiltDependencies?.items ?? []; - - for (const item of allowedPackages) { - if (items.includes(item)) continue; - if (items.some((y) => typeof y === 'object' && y.value === item)) continue; - items.push(item); - } - data.set('onlyBuiltDependencies', items); - - const newContent = generateCode(); - const pnpmWorkspacePath = found ?? path.join(cwd, 'pnpm-workspace.yaml'); - if (newContent !== content) fs.writeFileSync(pnpmWorkspacePath, newContent, 'utf-8'); - } else { - // else is package.json (fallback) - const rootDir = found ? path.dirname(found) : cwd; - const pkgPath = path.join(rootDir, 'package.json'); - const content = fs.readFileSync(pkgPath, 'utf-8'); - const { data, generateCode } = parse.json(content); - - // add the packages where we install scripts should be executed - data.pnpm ??= {}; - data.pnpm.onlyBuiltDependencies ??= []; - for (const allowedPackage of allowedPackages) { - if (data.pnpm.onlyBuiltDependencies.includes(allowedPackage)) continue; - data.pnpm.onlyBuiltDependencies.push(allowedPackage); - } + const onlyBuiltDependencies = data.get('onlyBuiltDependencies'); + const items: Array<{ value: string } | string> = onlyBuiltDependencies?.items ?? []; - // save the updated package.json - const newContent = generateCode(); - if (newContent !== content) fs.writeFileSync(pkgPath, newContent, 'utf-8'); + for (const item of allowedPackages) { + if (items.includes(item)) continue; + if (items.some((y) => typeof y === 'object' && y.value === item)) continue; + items.push(item); } -} + data.set('onlyBuiltDependencies', items); -async function getPnpmVersion(): Promise { - let v: string | undefined = undefined; - try { - const proc = await exec('pnpm', ['--version'], { throwOnError: true }); - v = proc.stdout.trim(); - } catch {} - return v; + const newContent = generateCode(); + const pnpmWorkspacePath = found ?? path.join(cwd, 'pnpm-workspace.yaml'); + if (newContent !== content) fs.writeFileSync(pnpmWorkspacePath, newContent, 'utf-8'); } diff --git a/packages/sv/src/core/workspace.ts b/packages/sv/src/core/workspace.ts index 987787419..092d75627 100644 --- a/packages/sv/src/core/workspace.ts +++ b/packages/sv/src/core/workspace.ts @@ -46,6 +46,12 @@ export type Workspace = { /** Get the relative path between two files */ getRelative: ({ from, to }: { from?: string; to: string }) => string; + + /** + * Find a file by walking up the directory tree from cwd. + * Returns the relative path from cwd, or the filename itself if not found. + */ + findUp: (filename: string) => string; }; isKit: boolean; directory: { @@ -155,6 +161,15 @@ export async function createWorkspace({ relativePath = `./${relativePath}`; } return relativePath; + }, + findUp(filename) { + const found = find.up(filename, { cwd: resolvedCwd }); + if (!found) return filename; + // don't escape .test-output during tests + if (resolvedCwd.includes('.test-output') && !found.includes('.test-output')) { + return filename; + } + return path.relative(resolvedCwd, found); } }, isKit, diff --git a/packages/sv/src/testing.ts b/packages/sv/src/testing.ts index 14bfb309a..4adc8a1fd 100644 --- a/packages/sv/src/testing.ts +++ b/packages/sv/src/testing.ts @@ -326,13 +326,13 @@ export function createSetupTest(vitest: VitestContext): Date: Sat, 4 Apr 2026 00:41:07 +0200 Subject: [PATCH 02/31] =?UTF-8?q?fmt=C2=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/sv/src/addons/drizzle.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/sv/src/addons/drizzle.ts b/packages/sv/src/addons/drizzle.ts index d4269a705..756a08ba2 100644 --- a/packages/sv/src/addons/drizzle.ts +++ b/packages/sv/src/addons/drizzle.ts @@ -90,7 +90,17 @@ export default defineAddon({ if (!isKit) return unsupported('Requires SvelteKit'); }, - run: ({ sv, language, options, directory, dependencyVersion, cwd, cancel, file, packageManager }) => { + run: ({ + sv, + language, + options, + directory, + dependencyVersion, + cwd, + cancel, + file, + packageManager + }) => { if (options.database === 'd1' && !dependencyVersion('@sveltejs/adapter-cloudflare')) { return cancel('Cloudflare D1 requires @sveltejs/adapter-cloudflare - add the adapter first'); } From d4ea793aef99d25bbb1582b8c1c837975325fa23 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 08:15:57 +0200 Subject: [PATCH 03/31] rmv addPnpmBuildDependencies --- packages/sv/src/cli/add.ts | 4 ++-- packages/sv/src/cli/create.ts | 4 ++-- packages/sv/src/core/package-manager.ts | 29 +++++++------------------ packages/sv/src/testing.ts | 6 ++--- 4 files changed, 15 insertions(+), 28 deletions(-) diff --git a/packages/sv/src/cli/add.ts b/packages/sv/src/cli/add.ts index 71c617449..b07778da2 100644 --- a/packages/sv/src/cli/add.ts +++ b/packages/sv/src/cli/add.ts @@ -23,7 +23,7 @@ import { downloadPackage, getPackageJSON } from '../core/fetch-packages.ts'; import { formatFiles } from '../core/formatFiles.ts'; import { AGENT_NAMES, - addPnpmBuildDependencies, + addOnlyBuiltDependencies, installDependencies, installOption, packageManagerPrompt @@ -712,7 +712,7 @@ export async function runAddonsApply({ ? await packageManagerPrompt(options.cwd) : options.install; - await addPnpmBuildDependencies(workspace.cwd, packageManager, ['esbuild']); + addOnlyBuiltDependencies(workspace.cwd, packageManager, 'esbuild'); const argsFormattedAddons: string[] = []; for (const loaded of successfulAddons) { diff --git a/packages/sv/src/cli/create.ts b/packages/sv/src/cli/create.ts index 28f93a997..ec3683602 100644 --- a/packages/sv/src/cli/create.ts +++ b/packages/sv/src/cli/create.ts @@ -10,7 +10,7 @@ import type { LoadedAddon, OptionValues, SetupResult } from '../core/config.ts'; import { formatFiles } from '../core/formatFiles.ts'; import { AGENT_NAMES, - addPnpmBuildDependencies, + addOnlyBuiltDependencies, detectPackageManager, installDependencies, installOption, @@ -384,7 +384,7 @@ async function createProject(cwd: ProjectPath, options: Options) { } const addOnNextSteps = getNextSteps(addOnSuccessfulAddons, workspace, answers, addonSetupResults); - await addPnpmBuildDependencies(projectPath, packageManager, ['esbuild']); + addOnlyBuiltDependencies(projectPath, packageManager, 'esbuild'); if (packageManager) { await installDependencies(packageManager, projectPath); await formatFiles({ packageManager, cwd: projectPath, filesToFormat: addOnFilesToFormat }); diff --git a/packages/sv/src/core/package-manager.ts b/packages/sv/src/core/package-manager.ts index 8dba53fc8..16b319e3f 100644 --- a/packages/sv/src/core/package-manager.ts +++ b/packages/sv/src/core/package-manager.ts @@ -6,7 +6,7 @@ import { color, constructCommand, detect, - parse + pnpm } from '@sveltejs/sv-utils'; import { Option } from 'commander'; import * as find from 'empathic/find'; @@ -92,29 +92,16 @@ export function getUserAgent(): AgentName | undefined { return AGENTS.includes(name) ? name : undefined; } -export async function addPnpmBuildDependencies( +export function addOnlyBuiltDependencies( cwd: string, packageManager: AgentName | null | undefined, - allowedPackages: string[] -): Promise { - if (!packageManager || packageManager !== 'pnpm' || allowedPackages.length === 0) return; + ...packages: string[] +): void { + if (packageManager !== 'pnpm' || packages.length === 0) return; - // find the workspace root (if present) const found = find.up('pnpm-workspace.yaml', { cwd }); + const filePath = found ?? path.join(cwd, 'pnpm-workspace.yaml'); const content = found ? fs.readFileSync(found, 'utf-8') : ''; - const { data, generateCode } = parse.yaml(content); - - const onlyBuiltDependencies = data.get('onlyBuiltDependencies'); - const items: Array<{ value: string } | string> = onlyBuiltDependencies?.items ?? []; - - for (const item of allowedPackages) { - if (items.includes(item)) continue; - if (items.some((y) => typeof y === 'object' && y.value === item)) continue; - items.push(item); - } - data.set('onlyBuiltDependencies', items); - - const newContent = generateCode(); - const pnpmWorkspacePath = found ?? path.join(cwd, 'pnpm-workspace.yaml'); - if (newContent !== content) fs.writeFileSync(pnpmWorkspacePath, newContent, 'utf-8'); + const newContent = pnpm.onlyBuiltDependencies(...packages)(content); + if (newContent !== content) fs.writeFileSync(filePath, newContent, 'utf-8'); } diff --git a/packages/sv/src/testing.ts b/packages/sv/src/testing.ts index 4adc8a1fd..b2666b46f 100644 --- a/packages/sv/src/testing.ts +++ b/packages/sv/src/testing.ts @@ -7,10 +7,10 @@ import pstree, { type PS } from 'ps-tree'; import { exec, x } from 'tinyexec'; import type { TestProject } from 'vitest/node'; import { add, type AddonMap, type OptionMap } from './core/engine.ts'; -import { addPnpmBuildDependencies } from './core/package-manager.ts'; +import { addOnlyBuiltDependencies } from './core/package-manager.ts'; import { create } from './create/index.ts'; -export { addPnpmBuildDependencies } from './core/package-manager.ts'; +export { addOnlyBuiltDependencies } from './core/package-manager.ts'; export type ProjectVariant = 'kit-js' | 'kit-ts' | 'vite-js' | 'vite-ts'; export const variants: ProjectVariant[] = ['kit-js', 'kit-ts', 'vite-js', 'vite-ts']; @@ -332,7 +332,7 @@ export function createSetupTest(vitest: VitestContext): Date: Sat, 4 Apr 2026 08:28:53 +0200 Subject: [PATCH 04/31] don't export he internal of addPnpmOnlyBuiltDependencies --- packages/sv/src/cli/add.ts | 4 ++-- packages/sv/src/cli/create.ts | 4 ++-- packages/sv/src/core/package-manager.ts | 2 +- packages/sv/src/testing.ts | 5 ++--- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/packages/sv/src/cli/add.ts b/packages/sv/src/cli/add.ts index b07778da2..5f967f901 100644 --- a/packages/sv/src/cli/add.ts +++ b/packages/sv/src/cli/add.ts @@ -23,7 +23,7 @@ import { downloadPackage, getPackageJSON } from '../core/fetch-packages.ts'; import { formatFiles } from '../core/formatFiles.ts'; import { AGENT_NAMES, - addOnlyBuiltDependencies, + addPnpmOnlyBuiltDependencies, installDependencies, installOption, packageManagerPrompt @@ -712,7 +712,7 @@ export async function runAddonsApply({ ? await packageManagerPrompt(options.cwd) : options.install; - addOnlyBuiltDependencies(workspace.cwd, packageManager, 'esbuild'); + addPnpmOnlyBuiltDependencies(workspace.cwd, packageManager, 'esbuild'); const argsFormattedAddons: string[] = []; for (const loaded of successfulAddons) { diff --git a/packages/sv/src/cli/create.ts b/packages/sv/src/cli/create.ts index ec3683602..a2cf4d388 100644 --- a/packages/sv/src/cli/create.ts +++ b/packages/sv/src/cli/create.ts @@ -10,7 +10,7 @@ import type { LoadedAddon, OptionValues, SetupResult } from '../core/config.ts'; import { formatFiles } from '../core/formatFiles.ts'; import { AGENT_NAMES, - addOnlyBuiltDependencies, + addPnpmOnlyBuiltDependencies, detectPackageManager, installDependencies, installOption, @@ -384,7 +384,7 @@ async function createProject(cwd: ProjectPath, options: Options) { } const addOnNextSteps = getNextSteps(addOnSuccessfulAddons, workspace, answers, addonSetupResults); - addOnlyBuiltDependencies(projectPath, packageManager, 'esbuild'); + addPnpmOnlyBuiltDependencies(projectPath, packageManager, 'esbuild'); if (packageManager) { await installDependencies(packageManager, projectPath); await formatFiles({ packageManager, cwd: projectPath, filesToFormat: addOnFilesToFormat }); diff --git a/packages/sv/src/core/package-manager.ts b/packages/sv/src/core/package-manager.ts index 16b319e3f..5154a3ceb 100644 --- a/packages/sv/src/core/package-manager.ts +++ b/packages/sv/src/core/package-manager.ts @@ -92,7 +92,7 @@ export function getUserAgent(): AgentName | undefined { return AGENTS.includes(name) ? name : undefined; } -export function addOnlyBuiltDependencies( +export function addPnpmOnlyBuiltDependencies( cwd: string, packageManager: AgentName | null | undefined, ...packages: string[] diff --git a/packages/sv/src/testing.ts b/packages/sv/src/testing.ts index b2666b46f..35d624cce 100644 --- a/packages/sv/src/testing.ts +++ b/packages/sv/src/testing.ts @@ -7,10 +7,9 @@ import pstree, { type PS } from 'ps-tree'; import { exec, x } from 'tinyexec'; import type { TestProject } from 'vitest/node'; import { add, type AddonMap, type OptionMap } from './core/engine.ts'; -import { addOnlyBuiltDependencies } from './core/package-manager.ts'; +import { addPnpmOnlyBuiltDependencies } from './core/package-manager.ts'; import { create } from './create/index.ts'; -export { addOnlyBuiltDependencies } from './core/package-manager.ts'; export type ProjectVariant = 'kit-js' | 'kit-ts' | 'vite-js' | 'vite-ts'; export const variants: ProjectVariant[] = ['kit-js', 'kit-ts', 'vite-js', 'vite-ts']; @@ -332,7 +331,7 @@ export function createSetupTest(vitest: VitestContext): Date: Sat, 4 Apr 2026 08:34:06 +0200 Subject: [PATCH 05/31] lint --- packages/sv-utils/src/pnpm.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/sv-utils/src/pnpm.ts b/packages/sv-utils/src/pnpm.ts index b9cc34987..aa86f928e 100644 --- a/packages/sv-utils/src/pnpm.ts +++ b/packages/sv-utils/src/pnpm.ts @@ -1,5 +1,4 @@ -import type { TransformFn } from './tooling/transforms.ts'; -import { transforms } from './tooling/transforms.ts'; +import { transforms, type TransformFn } from './tooling/transforms.ts'; /** * Returns a TransformFn for `pnpm-workspace.yaml` that adds packages to `onlyBuiltDependencies`. From 8671cd23db4e8ed7adbeeaf7d1a69fdde1aed9c9 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 12:29:22 +0200 Subject: [PATCH 06/31] chore: add api-surface generator and tsdown hooks Wire generateApiSurface into each config's build:done (with a shared counter so it runs once after all parallel builds). Add scripts/ generate-api-surface.js (strip regions, sourceMappingURL, optional JSDoc; keep @deprecated blocks). Made-with: Cursor --- scripts/generate-api-surface.js | 125 ++++++++++++++++++++++++++++++++ tsdown.config.ts | 26 ++++++- 2 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 scripts/generate-api-surface.js diff --git a/scripts/generate-api-surface.js b/scripts/generate-api-surface.js new file mode 100644 index 000000000..d34bf160b --- /dev/null +++ b/scripts/generate-api-surface.js @@ -0,0 +1,125 @@ +/** + * Reads the generated .d.mts files and produces a cleaned-up + * api-surface.md for each package. Strips `//#region` / `//#endregion` + * directives, `//# sourceMappingURL=...` lines, non-deprecated JSDoc, import-only lines, + * and blank runs so the result is a compact, diff-friendly snapshot + * of the public API. JSDoc blocks that contain `@deprecated` are kept + * in full. + * + * Run: node scripts/generate-api-surface.js + * Or: invoked from tsdown `build:done` after all configs finish (see tsdown.config.ts). + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); + +const packages = [ + { + name: 'sv', + dts: 'packages/sv/dist/src/index.d.mts', + out: 'packages/sv/api-surface.md' + }, + { + name: 'sv (testing)', + dts: 'packages/sv/dist/src/testing.d.mts', + out: 'packages/sv/api-surface-testing.md' + }, + { + name: '@sveltejs/sv-utils', + dts: 'packages/sv-utils/dist/index.d.mts', + out: 'packages/sv-utils/api-surface.md' + } +]; + +/** Remove `//#region` / `//#endregion` lines emitted by the DTS bundler. */ +function stripRegionDirectives(source) { + return source + .split('\n') + .filter((line) => !/^\s*\/\/#(region|endregion)\b/.test(line)) + .join('\n'); +} + +/** Remove `//# sourceMappingURL=...` lines from declaration emit. */ +function stripSourceMappingUrl(source) { + return source + .split('\n') + .filter((line) => !/^\s*\/\/#\s*sourceMappingURL=/.test(line)) + .join('\n'); +} + +/** + * Remove `/** ... *\/` blocks unless they contain `@deprecated`, in which case + * the full block is preserved (including inline trailing JSDoc on a line). + */ +function stripJsDoc(source) { + return source.replace(/\/\*\*[\s\S]*?\*\//g, (match) => { + if (/@deprecated\b/.test(match)) { + return match; + } + return ''; + }); +} + +function stripImportLines(source) { + // Remove `import ...` lines that are only used for type resolution + return source + .split('\n') + .filter((line) => !line.match(/^import\s/)) + .join('\n'); +} + +function collapseBlankLines(source) { + return source.replace(/\n{3,}/g, '\n\n'); +} + +function clean(source) { + let result = stripRegionDirectives(source); + result = stripSourceMappingUrl(result); + result = stripJsDoc(result); + result = stripImportLines(result); + result = collapseBlankLines(result); + return result.trim() + '\n'; +} + +/** @returns {number} number of api-surface files written */ +export function generateApiSurface() { + let generated = 0; + for (const pkg of packages) { + const dtsPath = path.resolve(ROOT, pkg.dts); + if (!fs.existsSync(dtsPath)) { + console.warn(` skipped ${pkg.name} - ${pkg.dts} not found (run build first)`); + continue; + } + + const raw = fs.readFileSync(dtsPath, 'utf8'); + const cleaned = clean(raw); + + const header = + `# ${pkg.name} - Public API Surface\n\n` + + `\n\n` + + '```ts\n'; + const footer = '```\n'; + + const outPath = path.resolve(ROOT, pkg.out); + fs.writeFileSync(outPath, header + cleaned + footer, 'utf8'); + generated++; + console.log(` ${pkg.name} -> ${pkg.out}`); + } + + if (generated === 0) { + console.warn('No .d.mts files found - run `pnpm build` first.'); + process.exit(1); + } + + return generated; +} + +const isMain = + process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1]); + +if (isMain) { + generateApiSurface(); +} diff --git a/tsdown.config.ts b/tsdown.config.ts index 1a564bdcc..7de467cb0 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -3,6 +3,23 @@ import process from 'node:process'; import { defineConfig } from 'tsdown'; import { buildTemplates } from './packages/sv/src/create/scripts/build-templates.js'; +/** + * tsdown runs each `defineConfig` entry in parallel. There is no single + * "all builds finished" hook, so we count `build:done` (must match the number + * of config objects below) and run api-surface generation once all `.d.mts` + * outputs exist. + */ +const API_SURFACE_CONFIG_COUNT = 3; +let apiSurfaceBuildsDone = 0; + +function hookApiSurfaceBuildDone(): void | Promise { + apiSurfaceBuildsDone++; + if (apiSurfaceBuildsDone === API_SURFACE_CONFIG_COUNT) { + apiSurfaceBuildsDone = 0; + return import('./scripts/generate-api-surface.js').then((m) => m.generateApiSurface()); + } +} + export default defineConfig([ { cwd: path.resolve('packages/sv'), @@ -57,7 +74,8 @@ export default defineConfig([ hooks: { async 'build:before'() { await buildCliTemplates(); - } + }, + 'build:done': () => hookApiSurfaceBuildDone() } }, // sv-utils: runtime build (bundles everything including svelte) @@ -88,6 +106,9 @@ export default defineConfig([ 'yaml', 'zimmerframe' ] + }, + hooks: { + 'build:done': () => hookApiSurfaceBuildDone() } }, // sv-utils: DTS-only build (svelte externalized) @@ -105,6 +126,9 @@ export default defineConfig([ deps: { neverBundle: [/^svelte/, '@types/estree', 'estree'], onlyBundle: ['dedent', 'package-manager-detector', 'smol-toml', 'yaml', 'zimmerframe'] + }, + hooks: { + 'build:done': () => hookApiSurfaceBuildDone() } } ]); From d058caae0755c417500cf92a3ee88b2913b27898 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 12:29:27 +0200 Subject: [PATCH 07/31] chore: add generated public API surface snapshots Snapshots from built .d.mts (baseline before coupling/deprecation work). Made-with: Cursor --- packages/sv-utils/api-surface.md | 1310 ++++++++++++++++++++++++++++ packages/sv/api-surface-testing.md | 109 +++ packages/sv/api-surface.md | 25 + 3 files changed, 1444 insertions(+) create mode 100644 packages/sv-utils/api-surface.md create mode 100644 packages/sv/api-surface-testing.md create mode 100644 packages/sv/api-surface.md diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md new file mode 100644 index 000000000..983b6d046 --- /dev/null +++ b/packages/sv-utils/api-surface.md @@ -0,0 +1,1310 @@ +# @sveltejs/sv-utils - Public API Surface + + + +```ts +type Agent = 'npm' | 'yarn' | 'yarn@berry' | 'pnpm' | 'pnpm@6' | 'bun' | 'deno'; +type AgentName = 'npm' | 'yarn' | 'pnpm' | 'bun' | 'deno'; +type AgentCommandValue = (string | number)[] | ((args: string[]) => string[]) | null; +interface AgentCommands { + 'agent': AgentCommandValue; + 'run': AgentCommandValue; + 'install': AgentCommandValue; + 'frozen': AgentCommandValue; + 'global': AgentCommandValue; + 'add': AgentCommandValue; + 'upgrade': AgentCommandValue; + 'upgrade-interactive': AgentCommandValue; + 'dedupe': AgentCommandValue; + 'execute': AgentCommandValue; + 'execute-local': AgentCommandValue; + 'uninstall': AgentCommandValue; + 'global_uninstall': AgentCommandValue; +} +type Command = keyof AgentCommands; +interface ResolvedCommand { + + command: string; + + args: string[]; +} +type DetectStrategy = 'lockfile' | 'packageManager-field' | 'devEngines-field' | 'install-metadata'; +interface DetectOptions { + + cwd?: string; + + strategies?: DetectStrategy[]; + + onUnknown?: (packageManager: string) => DetectResult | null | undefined; + + stopDir?: string | ((currentDir: string) => boolean); + + packageJsonParser?: (content: string, filepath: string) => any | Promise; +} +interface DetectResult { + + name: AgentName; + + agent: Agent; + + version?: string; +} +declare const COMMANDS: { + npm: AgentCommands; + yarn: AgentCommands; + 'yarn@berry': AgentCommands; + pnpm: AgentCommands; + 'pnpm@6': AgentCommands; + bun: AgentCommands; + deno: AgentCommands; +}; + +declare function resolveCommand(agent: Agent, command: Command, args: string[]): ResolvedCommand | null; + +declare function constructCommand(value: AgentCommandValue, args: string[]): ResolvedCommand | null; +declare const AGENTS: Agent[]; + +declare function detect(options?: DetectOptions): Promise; +/*! + * Copyright (c) Squirrel Chat et al., All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +declare class TomlDate extends Date { + #private; + constructor(date: string | Date); + isDateTime(): boolean; + isLocal(): boolean; + isDate(): boolean; + isTime(): boolean; + isValid(): boolean; + toISOString(): string; + static wrapAsOffsetDateTime(jsDate: Date, offset?: string): TomlDate; + static wrapAsLocalDateTime(jsDate: Date): TomlDate; + static wrapAsLocalDate(jsDate: Date): TomlDate; + static wrapAsLocalTime(jsDate: Date): TomlDate; +} +type TomlPrimitive = string | number | bigint | boolean | TomlDate; +type TomlTable = { + [key: string]: TomlValue; +}; +type TomlValue = TomlPrimitive | TomlValue[] | TomlTable; + +declare class LineCounter { + lineStarts: number[]; + + addNewLine: (offset: number) => number; + + linePos: (offset: number) => { + line: number; + col: number; + }; +} +type ErrorCode = 'ALIAS_PROPS' | 'BAD_ALIAS' | 'BAD_DIRECTIVE' | 'BAD_DQ_ESCAPE' | 'BAD_INDENT' | 'BAD_PROP_ORDER' | 'BAD_SCALAR_START' | 'BLOCK_AS_IMPLICIT_KEY' | 'BLOCK_IN_FLOW' | 'DUPLICATE_KEY' | 'IMPOSSIBLE' | 'KEY_OVER_1024_CHARS' | 'MISSING_CHAR' | 'MULTILINE_IMPLICIT_KEY' | 'MULTIPLE_ANCHORS' | 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'NON_STRING_KEY' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED' | 'UNEXPECTED_TOKEN' | 'BAD_COLLECTION_TYPE'; +type LinePos = { + line: number; + col: number; +}; +declare class YAMLError extends Error { + name: 'YAMLParseError' | 'YAMLWarning'; + code: ErrorCode; + message: string; + pos: [number, number]; + linePos?: [LinePos] | [LinePos, LinePos]; + constructor(name: YAMLError['name'], pos: [number, number], code: ErrorCode, message: string); +} +declare class YAMLWarning extends YAMLError { + constructor(pos: [number, number], code: ErrorCode, message: string); +} +type Reviver = (key: unknown, value: unknown) => unknown; +type LogLevelId = 'silent' | 'error' | 'warn' | 'debug'; +interface AnchorData { + aliasCount: number; + count: number; + res: unknown; +} +interface ToJSContext { + anchors: Map; + + aliasResolveCache?: Node[]; + doc: Document; + keep: boolean; + mapAsMap: boolean; + mapKeyWarned: boolean; + maxAliasCount: number; + onCreate?: (res: unknown) => void; +} +declare namespace Scalar { + interface Parsed extends Scalar { + range: Range; + source: string; + srcToken?: FlowScalar | BlockScalar; + } + type BLOCK_FOLDED = 'BLOCK_FOLDED'; + type BLOCK_LITERAL = 'BLOCK_LITERAL'; + type PLAIN = 'PLAIN'; + type QUOTE_DOUBLE = 'QUOTE_DOUBLE'; + type QUOTE_SINGLE = 'QUOTE_SINGLE'; + type Type = BLOCK_FOLDED | BLOCK_LITERAL | PLAIN | QUOTE_DOUBLE | QUOTE_SINGLE; +} +declare class Scalar extends NodeBase { + static readonly BLOCK_FOLDED = "BLOCK_FOLDED"; + static readonly BLOCK_LITERAL = "BLOCK_LITERAL"; + static readonly PLAIN = "PLAIN"; + static readonly QUOTE_DOUBLE = "QUOTE_DOUBLE"; + static readonly QUOTE_SINGLE = "QUOTE_SINGLE"; + value: T; + + anchor?: string; + + format?: string; + + minFractionDigits?: number; + + source?: string; + + type?: Scalar.Type; + constructor(value: T); + toJSON(arg?: any, ctx?: ToJSContext): any; + toString(): string; +} +type StringifyContext = { + actualString?: boolean; + allNullValues?: boolean; + anchors: Set; + doc: Document; + forceBlockIndent?: boolean; + implicitKey?: boolean; + indent: string; + indentStep: string; + indentAtStart?: number; + inFlow: boolean | null; + inStringifyKey?: boolean; + flowCollectionPadding: string; + options: Readonly>>; + resolvedAliases?: Set; +}; +declare abstract class Collection extends NodeBase { + schema: Schema | undefined; + [NODE_TYPE]: symbol; + items: unknown[]; + + anchor?: string; + + flow?: boolean; + constructor(type: symbol, schema?: Schema); + + clone(schema?: Schema): Collection; + + abstract add(value: unknown): void; + + abstract delete(key: unknown): boolean; + + abstract get(key: unknown, keepScalar?: boolean): unknown; + + abstract has(key: unknown): boolean; + + abstract set(key: unknown, value: unknown): void; + + addIn(path: Iterable, value: unknown): void; + + deleteIn(path: Iterable): boolean; + + getIn(path: Iterable, keepScalar?: boolean): unknown; + hasAllNullValues(allowScalar?: boolean): boolean; + + hasIn(path: Iterable): boolean; + + setIn(path: Iterable, value: unknown): void; +} +declare namespace YAMLSeq { + interface Parsed = ParsedNode> extends YAMLSeq { + items: T[]; + range: Range; + srcToken?: BlockSequence | FlowCollection; + } +} +declare class YAMLSeq extends Collection { + static get tagName(): 'tag:yaml.org,2002:seq'; + items: T[]; + constructor(schema?: Schema); + add(value: T): void; + + delete(key: unknown): boolean; + + get(key: unknown, keepScalar: true): Scalar | undefined; + get(key: unknown, keepScalar?: false): T | undefined; + get(key: unknown, keepScalar?: boolean): T | Scalar | undefined; + + has(key: unknown): boolean; + + set(key: unknown, value: T): void; + toJSON(_?: unknown, ctx?: ToJSContext): unknown[]; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq; +} +interface TagBase { + + createNode?: (schema: Schema, value: unknown, ctx: CreateNodeContext) => Node; + + default?: boolean | 'key'; + + format?: string; + + identify?: (value: unknown) => boolean; + + tag: string; +} +interface ScalarTag extends TagBase { + collection?: never; + nodeClass?: never; + + resolve(value: string, onError: (message: string) => void, options: ParseOptions): unknown; + + stringify?: (item: Scalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void) => string; + + test?: RegExp; +} +interface CollectionTag extends TagBase { + stringify?: never; + test?: never; + + collection: 'map' | 'seq'; + + nodeClass?: { + new (schema?: Schema): Node; + from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node; + }; + + resolve?: (value: YAMLMap.Parsed | YAMLSeq.Parsed, onError: (message: string) => void, options: ParseOptions) => unknown; +} +type MapLike = Map | Set | Record; +declare namespace YAMLMap { + interface Parsed extends YAMLMap { + items: Pair[]; + range: Range; + srcToken?: BlockMap | FlowCollection; + } +} +declare class YAMLMap extends Collection { + static get tagName(): 'tag:yaml.org,2002:map'; + items: Pair[]; + constructor(schema?: Schema); + + static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap; + + add(pair: Pair | { + key: K; + value: V; + }, overwrite?: boolean): void; + delete(key: unknown): boolean; + get(key: unknown, keepScalar: true): Scalar | undefined; + get(key: unknown, keepScalar?: false): V | undefined; + get(key: unknown, keepScalar?: boolean): V | Scalar | undefined; + has(key: unknown): boolean; + set(key: K, value: V): void; + + toJSON>(_?: unknown, ctx?: ToJSContext, Type?: { + new (): T; + }): any; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; +} +declare const MAP: unique symbol; +declare const SCALAR: unique symbol; +declare const SEQ: unique symbol; +declare const NODE_TYPE: unique symbol; +declare class Schema { + compat: Array | null; + knownTags: Record; + name: string; + sortMapEntries: ((a: Pair, b: Pair) => number) | null; + tags: Array; + toStringOptions: Readonly | null; + readonly [MAP]: CollectionTag; + readonly [SCALAR]: ScalarTag; + readonly [SEQ]: CollectionTag; + constructor({ + compat, + customTags, + merge, + resolveKnownTags, + schema, + sortMapEntries, + toStringDefaults + }: SchemaOptions); + clone(): Schema; +} +interface CreateNodeContext { + aliasDuplicateObjects: boolean; + keepUndefined: boolean; + onAnchor: (source: unknown) => string; + onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; + sourceObjects: Map; + replacer?: Replacer; + schema: Schema; +} +declare function addPairToJSMap(ctx: ToJSContext | undefined, map: MapLike, { + key, + value +}: Pair): MapLike; +declare class Pair { + readonly [NODE_TYPE]: symbol; + + key: K; + + value: V | null; + + srcToken?: CollectionItem; + constructor(key: K, value?: V | null); + clone(schema?: Schema): Pair; + toJSON(_?: unknown, ctx?: ToJSContext): ReturnType; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; +} +declare const tagsByName: { + binary: ScalarTag; + bool: ScalarTag & { + test: RegExp; + }; + float: ScalarTag; + floatExp: ScalarTag; + floatNaN: ScalarTag; + floatTime: ScalarTag; + int: ScalarTag; + intHex: ScalarTag; + intOct: ScalarTag; + intTime: ScalarTag; + map: CollectionTag; + merge: ScalarTag & { + identify(value: unknown): boolean; + test: RegExp; + }; + null: ScalarTag & { + test: RegExp; + }; + omap: CollectionTag; + pairs: CollectionTag; + seq: CollectionTag; + set: CollectionTag; + timestamp: ScalarTag & { + test: RegExp; + }; +}; +type TagId = keyof typeof tagsByName; +type Tags = Array; +type ParseOptions = { + + intAsBigInt?: boolean; + + keepSourceTokens?: boolean; + + lineCounter?: LineCounter; + + prettyErrors?: boolean; + + strict?: boolean; + + stringKeys?: boolean; + + uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean); +}; +type DocumentOptions = { + + _directives?: Directives; + + logLevel?: LogLevelId; + + version?: '1.1' | '1.2' | 'next'; +}; +type SchemaOptions = { + + compat?: string | Tags | null; + + customTags?: Tags | ((tags: Tags) => Tags) | null; + + merge?: boolean; + + resolveKnownTags?: boolean; + + schema?: string | Schema; + + sortMapEntries?: boolean | ((a: Pair, b: Pair) => number); + + toStringDefaults?: ToStringOptions; +}; +type CreateNodeOptions = { + + aliasDuplicateObjects?: boolean; + + anchorPrefix?: string; + flow?: boolean; + + keepUndefined?: boolean | null; + onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; + + tag?: string; +}; +type ToJSOptions = { + + mapAsMap?: boolean; + + maxAliasCount?: number; + + onAnchor?: (value: unknown, count: number) => void; + + reviver?: Reviver; +}; +type ToStringOptions = { + + blockQuote?: boolean | 'folded' | 'literal'; + + collectionStyle?: 'any' | 'block' | 'flow'; + + commentString?: (comment: string) => string; + + defaultKeyType?: Scalar.Type | null; + + defaultStringType?: Scalar.Type; + + directives?: boolean | null; + + doubleQuotedAsJSON?: boolean; + + doubleQuotedMinMultiLineLength?: number; + + falseStr?: string; + + flowCollectionPadding?: boolean; + + indent?: number; + + indentSeq?: boolean; + + lineWidth?: number; + + minContentWidth?: number; + + nullStr?: string; + + simpleKeys?: boolean; + + singleQuote?: boolean | null; + + trueStr?: string; + + verifyAliasOrder?: boolean; +}; +type Node = Alias | Scalar | YAMLMap | YAMLSeq; + +type NodeType = T extends string | number | bigint | boolean | null | undefined ? Scalar : T extends Date ? Scalar : T extends Array ? YAMLSeq> : T extends { + [key: string]: any; +} ? YAMLMap, NodeType> : T extends { + [key: number]: any; +} ? YAMLMap, NodeType> : Node; +type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed; + +type Range = [number, number, number]; +declare abstract class NodeBase { + readonly [NODE_TYPE]: symbol; + + comment?: string | null; + + commentBefore?: string | null; + + range?: Range | null; + + spaceBefore?: boolean; + + srcToken?: Token; + + tag?: string; + + addToJSMap?: (ctx: ToJSContext | undefined, map: MapLike, value: unknown) => void; + + abstract toJSON(): any; + abstract toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + constructor(type: symbol); + + clone(): NodeBase; + + toJS(doc: Document, { + mapAsMap, + maxAliasCount, + onAnchor, + reviver + }?: ToJSOptions): any; +} +interface SourceToken { + type: 'byte-order-mark' | 'doc-mode' | 'doc-start' | 'space' | 'comment' | 'newline' | 'directive-line' | 'anchor' | 'tag' | 'seq-item-ind' | 'explicit-key-ind' | 'map-value-ind' | 'flow-map-start' | 'flow-map-end' | 'flow-seq-start' | 'flow-seq-end' | 'flow-error-end' | 'comma' | 'block-scalar-header'; + offset: number; + indent: number; + source: string; +} +interface ErrorToken { + type: 'error'; + offset: number; + source: string; + message: string; +} +interface Directive$1 { + type: 'directive'; + offset: number; + source: string; +} +interface Document$1 { + type: 'document'; + offset: number; + start: SourceToken[]; + value?: Token; + end?: SourceToken[]; +} +interface DocumentEnd { + type: 'doc-end'; + offset: number; + source: string; + end?: SourceToken[]; +} +interface FlowScalar { + type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar'; + offset: number; + indent: number; + source: string; + end?: SourceToken[]; +} +interface BlockScalar { + type: 'block-scalar'; + offset: number; + indent: number; + props: Token[]; + source: string; +} +interface BlockMap { + type: 'block-map'; + offset: number; + indent: number; + items: Array<{ + start: SourceToken[]; + explicitKey?: true; + key?: never; + sep?: never; + value?: never; + } | { + start: SourceToken[]; + explicitKey?: true; + key: Token | null; + sep: SourceToken[]; + value?: Token; + }>; +} +interface BlockSequence { + type: 'block-seq'; + offset: number; + indent: number; + items: Array<{ + start: SourceToken[]; + key?: never; + sep?: never; + value?: Token; + }>; +} +type CollectionItem = { + start: SourceToken[]; + key?: Token | null; + sep?: SourceToken[]; + value?: Token; +}; +interface FlowCollection { + type: 'flow-collection'; + offset: number; + indent: number; + start: SourceToken; + items: CollectionItem[]; + end: SourceToken[]; +} +type Token = SourceToken | ErrorToken | Directive$1 | Document$1 | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection; +declare namespace Alias { + interface Parsed extends Alias { + range: Range; + srcToken?: FlowScalar & { + type: 'alias'; + }; + } +} +declare class Alias extends NodeBase { + source: string; + anchor?: never; + constructor(source: string); + + resolve(doc: Document, ctx?: ToJSContext): Scalar | YAMLMap | YAMLSeq | undefined; + toJSON(_arg?: unknown, ctx?: ToJSContext): unknown; + toString(ctx?: StringifyContext, _onComment?: () => void, _onChompKeep?: () => void): string; +} +type Replacer = any[] | ((key: any, value: any) => unknown); +declare namespace Document { + + interface Parsed extends Document { + directives: Directives; + range: Range; + } +} +declare class Document { + readonly [NODE_TYPE]: symbol; + + commentBefore: string | null; + + comment: string | null; + + contents: Strict extends true ? Contents | null : Contents; + directives: Strict extends true ? Directives | undefined : Directives; + + errors: YAMLError[]; + options: Required>; + + range?: Range; + + schema: Schema; + + warnings: YAMLWarning[]; + + constructor(value?: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions); + constructor(value: any, replacer: null | Replacer, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions); + + clone(): Document; + + add(value: any): void; + + addIn(path: Iterable, value: unknown): void; + + createAlias(node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, name?: string): Alias; + + createNode(value: T, options?: CreateNodeOptions): NodeType; + createNode(value: T, replacer: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions): NodeType; + + createPair(key: unknown, value: unknown, options?: CreateNodeOptions): Pair; + + delete(key: unknown): boolean; + + deleteIn(path: Iterable | null): boolean; + + get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any; + + getIn(path: Iterable | null, keepScalar?: boolean): Strict extends true ? unknown : any; + + has(key: unknown): boolean; + + hasIn(path: Iterable | null): boolean; + + set(key: any, value: unknown): void; + + setIn(path: Iterable | null, value: unknown): void; + + setSchema(version: '1.1' | '1.2' | 'next' | null, options?: SchemaOptions): void; + + toJS(opt?: ToJSOptions & { + [ignored: string]: unknown; + }): any; + + toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']): any; + + toString(options?: ToStringOptions): string; +} +declare class Directives { + static defaultYaml: Directives['yaml']; + static defaultTags: Directives['tags']; + yaml: { + version: '1.1' | '1.2' | 'next'; + explicit?: boolean; + }; + tags: Record; + + docStart: true | null; + + docEnd: boolean; + + private atNextDocument?; + constructor(yaml?: Directives['yaml'], tags?: Directives['tags']); + clone(): Directives; + + atDocument(): Directives; + + add(line: string, onError: (offset: number, message: string, warning?: boolean) => void): boolean; + + tagName(source: string, onError: (message: string) => void): string | null; + + tagString(tag: string): string; + toString(doc?: Document): string; +} + +declare function parseDocument(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Contents extends ParsedNode ? Document.Parsed : Document; +declare module "estree" { + interface TSTypeAnnotation { + type: "TSTypeAnnotation"; + typeAnnotation: TSStringKeyword | TSTypeReference | TSUnionType | TSIndexedAccessType; + } + interface TSStringKeyword { + type: "TSStringKeyword"; + } + interface TSNullKeyword { + type: "TSNullKeyword"; + } + interface TSTypeReference { + type: "TSTypeReference"; + typeName: Identifier; + } + interface TSAsExpression extends BaseNode { + type: "TSAsExpression"; + expression: Expression; + typeAnnotation: TSTypeAnnotation["typeAnnotation"]; + } + interface TSModuleDeclaration extends BaseNode { + type: "TSModuleDeclaration"; + global: boolean; + declare: boolean; + id: Identifier; + body: TSModuleBlock; + } + interface TSModuleBlock extends BaseNode { + type: "TSModuleBlock"; + body: Array; + } + interface TSInterfaceDeclaration extends BaseNode { + type: "TSInterfaceDeclaration"; + id: Identifier; + body: TSInterfaceBody; + } + interface TSInterfaceBody extends BaseNode { + type: "TSInterfaceBody"; + body: TSPropertySignature[]; + } + interface TSPropertySignature extends BaseNode { + type: "TSPropertySignature"; + computed: boolean; + key: Identifier; + optional?: boolean; + typeAnnotation: TSTypeAnnotation; + } + interface TSProgram extends Omit { + body: Array; + } + interface TSUnionType { + type: "TSUnionType"; + types: Array; + } + interface TSImportType { + type: "TSImportType"; + argument: Literal; + qualifier: Identifier; + } + interface TSIndexedAccessType { + type: "TSIndexedAccessType"; + objectType: TSImportType; + indexType: TSLiteralType; + } + interface TSLiteralType { + type: "TSLiteralType"; + literal: Literal; + } + interface TSSatisfiesExpression extends BaseNode { + type: "TSSatisfiesExpression"; + expression: Expression; + typeAnnotation: TSTypeAnnotation["typeAnnotation"]; + } + interface BaseNodeWithoutComments { + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; + start?: number; + end?: number; + } + interface Identifier { + typeAnnotation?: TSTypeAnnotation; + } + interface ExpressionMap { + TSAsExpression: TSAsExpression; + TSSatisfiesExpression: TSSatisfiesExpression; + } + interface NodeMap { + TSModuleDeclaration: TSModuleDeclaration; + TSInterfaceDeclaration: TSInterfaceDeclaration; + } + interface ImportDeclaration { + importKind: "type" | "value"; + } +} +declare function parseYaml$1(content: string): ReturnType; +type CommentType = { + type: "Line" | "Block"; + value: string; +}; +declare class Comments { + private original; + private leading; + private trailing; + constructor(); + add(node: BaseNode$1, comment: CommentType, options?: { + position?: "leading" | "trailing"; + }): void; + remove(predicate: (comment: estree.Comment) => boolean | undefined | null): void; +} +type ParseBase = { + source: string; + + generateCode(): string; +}; +declare function parseScript(source: string): { + ast: estree.Program; + comments: Comments; +} & ParseBase; +declare function parseCss(source: string): { + ast: Omit; +} & ParseBase; +declare function parseHtml(source: string): { + ast: SvelteAst.Fragment; +} & ParseBase; +declare function parseJson(source: string): { + data: any; +} & ParseBase; +declare function parseYaml(source: string): { + data: ReturnType; +} & ParseBase; +declare function parseSvelte(source: string): { + ast: SvelteAst.Root; +} & ParseBase; +declare function parseToml(source: string): { + data: TomlTable; +} & ParseBase; +interface DedentOptions { + alignValues?: boolean; + escapeSpecialCharacters?: boolean; + trimWhitespace?: boolean; +} +interface Dedent { + (literals: string): string; + (strings: TemplateStringsArray, ...values: unknown[]): string; + withOptions: CreateDedent; +} +type CreateDedent = (options: DedentOptions) => Dedent; +declare const dedent: Dedent; +declare module 'zimmerframe' { + export function walk | null>(node: T, state: U, visitors: Visitors): T; + type BaseNode = { + type: string; + }; + type NodeOf = X extends { + type: T; + } ? X : never; + type SpecialisedVisitors = { [K in T['type']]?: Visitor, U, T> }; + export type Visitor = (node: T, context: Context) => V | void; + export type Visitors = T['type'] extends '_' ? never : SpecialisedVisitors & { + _?: Visitor; + }; + export interface Context { + next: (state?: U) => T | void; + path: T[]; + state: U; + stop: () => void; + visit: (node: T, state?: U) => T; + } + export {}; +} //# sourceMappingURL=index.d.ts.map +declare namespace index_d_exports$1 { + export { addAtRule, addDeclaration, addImports, addRule }; +} +declare function addRule(node: SvelteAst.CSS.StyleSheetBase, options: { + selector: string; +}): SvelteAst.CSS.Rule; +declare function addDeclaration(node: SvelteAst.CSS.Rule, options: { + property: string; + value: string; +}): void; +declare function addImports(node: SvelteAst.CSS.StyleSheetBase, options: { + imports: string[]; +}): void; +declare function addAtRule(node: SvelteAst.CSS.StyleSheetBase, options: { + name: string; + params: string; + append: boolean; +}): SvelteAst.CSS.Atrule; +declare namespace array_d_exports { + export { append, create$1 as create, prepend }; +} +declare function create$1(): estree.ArrayExpression; +declare function append(node: estree.ArrayExpression, element: string | estree.Expression | estree.SpreadElement): void; +declare function prepend(node: estree.ArrayExpression, element: string | estree.Expression | estree.SpreadElement): void; +declare namespace object_d_exports { + export { create, overrideProperties, property, propertyNode }; +} +type ObjectPrimitiveValues = string | number | boolean | undefined | null; +type ObjectValues = ObjectPrimitiveValues | Record | ObjectValues[]; +type ObjectMap = Record; +declare function property(node: estree.ObjectExpression, options: { + name: string; + fallback: T; +}): T; +declare function propertyNode(node: estree.ObjectExpression, options: { + name: string; + fallback: T; +}): estree.Property; +declare function create(properties: ObjectMap): estree.ObjectExpression; +declare function overrideProperties(objectExpression: estree.ObjectExpression, properties: ObjectMap): void; +declare namespace common_d_exports { + export { addJsDocComment, addJsDocTypeComment, appendFromString, appendStatement, areNodesEqual, contains, createBlockStatement, createExpressionStatement, createLiteral, createSatisfies, createSpread, createTypeProperty, hasTypeProperty, parseExpression, parseFromString, parseStatement, typeAnnotate }; +} +declare function addJsDocTypeComment(node: estree.Node, comments: Comments, options: { + type: string; +}): void; +declare function addJsDocComment(node: estree.Node, comments: Comments, options: { + params: Record; +}): void; +declare function typeAnnotate(node: estree.Expression, options: { + type: string; +}): estree.TSAsExpression; +declare function createSatisfies(node: estree.Expression, options: { + type: string; +}): estree.TSSatisfiesExpression; +declare function createSpread(argument: estree.Expression): estree.SpreadElement; +declare function createLiteral(value: string | number | boolean | null): estree.Literal; +declare function areNodesEqual(node: estree.Node, otherNode: estree.Node): boolean; +declare function createBlockStatement(): estree.BlockStatement; +declare function createExpressionStatement(options: { + expression: estree.Expression; +}): estree.ExpressionStatement; +declare function appendFromString(node: estree.BlockStatement | estree.Program, options: { + code: string; + comments?: Comments; +}): void; +declare function parseExpression(code: string): estree.Expression; +declare function parseStatement(code: string): estree.Statement; +declare function parseFromString(code: string): T; + +declare function appendStatement(node: estree.BlockStatement | estree.Program, options: { + statement: estree.Statement; +}): void; + +declare function contains(node: estree.Node, targetNode: estree.Node): boolean; +declare function hasTypeProperty(node: estree.TSInterfaceDeclaration["body"]["body"][number], options: { + name: string; +}): boolean; +declare function createTypeProperty(name: string, value: string, optional?: boolean): estree.TSInterfaceBody["body"][number]; +declare namespace function_d_exports { + export { createArrow, createCall, getArgument }; +} +declare function createCall(options: { + name: string; + args: string[]; + useIdentifiers?: boolean; +}): estree.CallExpression; +declare function createArrow(options: { + body: estree.Expression | estree.BlockStatement; + async: boolean; +}): estree.ArrowFunctionExpression; +declare function getArgument(node: estree.CallExpression, options: { + index: number; + fallback: T; +}): T; +declare namespace imports_d_exports { + export { addDefault, addEmpty, addNamed, addNamespace$1 as addNamespace, find, remove }; +} +declare function addEmpty(node: estree.Program, options: { + from: string; +}): void; +declare function addNamespace$1(node: estree.Program, options: { + from: string; + as: string; +}): void; +declare function addDefault(node: estree.Program, options: { + from: string; + as: string; +}): void; +declare function addNamed(node: estree.Program, options: { + + imports: Record | string[]; + from: string; + isType?: boolean; +}): void; +declare function find(ast: estree.Program, options: { + name: string; + from: string; +}): { + statement: estree.ImportDeclaration; + alias: string; +} | { + statement: undefined; + alias: undefined; +}; +declare function remove(ast: estree.Program, options: { + name: string; + from: string; + statement?: estree.ImportDeclaration; +}): void; +declare namespace variables_d_exports { + export { createIdentifier, declaration, typeAnnotateDeclarator }; +} +declare function declaration(node: estree.Program | estree.Declaration, options: { + kind: "const" | "let" | "var"; + name: string; + value: estree.Expression; +}): estree.VariableDeclaration; +declare function createIdentifier(name: string): estree.Identifier; +declare function typeAnnotateDeclarator(node: estree.VariableDeclarator, options: { + typeName: string; +}): estree.VariableDeclarator; +declare namespace exports_d_exports { + export { ExportDefaultResult, addNamespace, createDefault, createNamed }; +} +type ExportDefaultResult = { + astNode: estree.ExportDefaultDeclaration; + value: T; + isFallback: boolean; +}; +declare function createDefault(node: estree.Program, options: { + fallback: T; +}): ExportDefaultResult; +declare function createNamed(node: estree.Program, options: { + name: string; + fallback: estree.VariableDeclaration; +}): estree.ExportNamedDeclaration; +declare function addNamespace(node: estree.Program, options: { + from: string; + as?: string; +}): void; +declare namespace kit_d_exports { + export { addGlobalAppInterface, addHooksHandle }; +} +declare function addGlobalAppInterface(node: estree.TSProgram, options: { + name: "Error" | "Locals" | "PageData" | "PageState" | "Platform"; +}): estree.TSInterfaceDeclaration; +declare function addHooksHandle(node: estree.Program, options: { + language: "ts" | "js"; + newHandleName: string; + handleContent: string; + comments: Comments; +}): void; +declare namespace vite_d_exports { + export { addPlugin, configProperty, getConfig }; +} +declare const addPlugin: (ast: estree.Program, options: { + code: string; + mode?: "append" | "prepend"; +}) => void; + +declare function configProperty(ast: estree.Program, config: estree.ObjectExpression, options: { + name: string; + fallback: T; +}): T; +declare const getConfig: (ast: estree.Program) => estree.ObjectExpression; +declare namespace index_d_exports$3 { + export { array_d_exports as array, common_d_exports as common, exports_d_exports as exports, function_d_exports as functions, imports_d_exports as imports, kit_d_exports as kit, object_d_exports as object, variables_d_exports as variables, vite_d_exports as vite }; +} +declare namespace index_d_exports$2 { + export { addAttribute, addFromRawHtml, appendElement, createElement, insertElement }; +} +declare function createElement(tagName: string, attributes?: Record): SvelteAst.RegularElement; +declare function addAttribute(element: SvelteAst.RegularElement, name: string, value: string): void; +declare function insertElement(fragment: SvelteAst.Fragment, elementToInsert: SvelteAst.Fragment["nodes"][0]): void; +declare function appendElement(fragment: SvelteAst.Fragment, elementToAppend: SvelteAst.Fragment["nodes"][0]): void; +declare function addFromRawHtml(fragment: SvelteAst.Fragment, html: string): void; +declare namespace text_d_exports { + export { upsert }; +} +type CommentEntry = { + text: string; + mode: "append" | "prepend"; +}; +type CommentOption = string | Array; + +declare function upsert(content: string, key: string, options?: { + value?: string; + comment?: CommentOption; + separator?: boolean; +}): string; +declare namespace json_d_exports { + export { arrayUpsert, packageScriptsUpsert }; +} +declare function arrayUpsert(data: any, key: string, value: any, options?: { + mode?: "append" | "prepend"; +}): void; +declare function packageScriptsUpsert(data: any, key: string, value: string, options?: { + mode?: "append" | "prepend"; +}): void; +declare namespace index_d_exports$4 { + export { RootWithInstance, addFragment, addSlot, ensureScript }; +} +type RootWithInstance = SvelteAst.Root & { + instance: SvelteAst.Script; +}; +declare function ensureScript(ast: SvelteAst.Root, options?: { + language?: "ts" | "js"; +}): asserts ast is RootWithInstance; +declare function addSlot(ast: SvelteAst.Root, options: { + svelteVersion: string; + language?: "ts" | "js"; +}): void; +declare function addFragment(ast: SvelteAst.Root, content: string, options?: { + mode?: "append" | "prepend"; +}): void; +type TransformFn = (content: string) => string; +type TransformOptions = { + onError?: (error: unknown) => void; +}; + +declare const transforms: { + + script(cb: (file: { + ast: estree.Program; + comments: Comments; + content: string; + js: typeof index_d_exports$3; + }) => void | false, options?: TransformOptions): (content: string) => string; + + svelte(cb: (file: { + ast: SvelteAst.Root; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, options?: TransformOptions): (content: string) => string; + + svelteScript(scriptOptions: { + language: "ts" | "js"; + }, cb: (file: { + ast: RootWithInstance; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, options?: TransformOptions): TransformFn; + + css(cb: (file: { + ast: Omit; + content: string; + css: typeof index_d_exports$1; + }) => void | false, options?: TransformOptions): TransformFn; + + json(cb: (file: { + data: T; + content: string; + json: typeof json_d_exports; + }) => void | false, options?: TransformOptions): TransformFn; + + yaml(cb: (file: { + data: ReturnType["data"]; + content: string; + }) => void | false, options?: TransformOptions): TransformFn; + + toml(cb: (file: { + data: TomlTable; + content: string; + }) => void | false, options?: TransformOptions): TransformFn; + + html(cb: (file: { + ast: SvelteAst.Fragment; + content: string; + html: typeof index_d_exports$2; + }) => void | false, options?: TransformOptions): TransformFn; + + text(cb: (file: { + content: string; + text: typeof text_d_exports; + }) => string | false): TransformFn; +}; +type Version = { + major?: number; + minor?: number; + patch?: number; +}; +declare function splitVersion(str: string): Version; +declare function isVersionUnsupportedBelow(versionStr: string, belowStr: string): boolean | undefined; +type Printer = (content: string, alt?: string) => string; +declare function createPrinter(...conditions: boolean[]): Printer[]; + +declare function sanitizeName(name: string, style: "package" | "wrangler"): string; +declare const downloadJson: (url: string) => Promise; +type Package = { + name: string; + version: string; + dependencies?: Record; + devDependencies?: Record; + bugs?: string; + repository?: { + type: string; + url: string; + }; + keywords?: string[]; + workspaces?: string[]; +}; +declare function getPackageJson(cwd: string): { + source: string; + data: Package; + generateCode: () => string; +}; +declare function readFile(cwd: string, filePath: string): string; +declare function fileExists(cwd: string, filePath: string): boolean; +declare function writeFile(cwd: string, filePath: string, content: string): void; +declare function installPackages(dependencies: Array<{ + pkg: string; + version: string; + dev: boolean; +}>, cwd: string): string; +declare const commonFilePaths: { + readonly packageJson: "package.json"; + readonly svelteConfig: "svelte.config.js"; + readonly svelteConfigTS: "svelte.config.ts"; + readonly jsconfig: "jsconfig.json"; + readonly tsconfig: "tsconfig.json"; + readonly viteConfig: "vite.config.js"; + readonly viteConfigTS: "vite.config.ts"; +}; +type ColorInput = string | string[]; +declare const color: { + addon: (str: ColorInput) => string; + command: (str: ColorInput) => string; + env: (str: ColorInput) => string; + path: (str: ColorInput) => string; + route: (str: ColorInput) => string; + website: (str: ColorInput) => string; + optional: (str: ColorInput) => string; + dim: (str: ColorInput) => string; + success: (str: ColorInput) => string; + warning: (str: ColorInput) => string; + error: (str: ColorInput) => string; + hidden: (str: ColorInput) => string; +}; + +declare function resolveCommandArray(agent: Agent, command: Command, args: string[]): string[]; + +declare const parse: { + css: typeof parseCss; + html: typeof parseHtml; + json: typeof parseJson; + script: typeof parseScript; + svelte: typeof parseSvelte; + toml: typeof parseToml; + yaml: typeof parseYaml; +}; +export { AGENTS, type AgentName, type estree as AstTypes, COMMANDS, type Comments, type Package, type SvelteAst, type TransformFn, index_d_exports as Walker, color, commonFilePaths, constructCommand, createPrinter, index_d_exports$1 as css, dedent, detect, downloadJson, fileExists, getPackageJson, index_d_exports$2 as html, installPackages, isVersionUnsupportedBelow, index_d_exports$3 as js, json_d_exports as json, parse, readFile, resolveCommand, resolveCommandArray, sanitizeName, splitVersion, index_d_exports$4 as svelte, text_d_exports as text, transforms, writeFile }; +``` diff --git a/packages/sv/api-surface-testing.md b/packages/sv/api-surface-testing.md new file mode 100644 index 000000000..116eefd8c --- /dev/null +++ b/packages/sv/api-surface-testing.md @@ -0,0 +1,109 @@ +# sv (testing) - Public API Surface + + + +```ts +declare function addPnpmBuildDependencies(cwd: string, packageManager: AgentName | null | undefined, allowedPackages: string[]): Promise; +type ProjectVariant = "kit-js" | "kit-ts" | "vite-js" | "vite-ts"; +declare const variants: ProjectVariant[]; +type CreateProject = (options: { + testId: string; + variant: ProjectVariant; + clean?: boolean; +}) => string; +type SetupOptions = { + cwd: string; + variants: readonly ProjectVariant[]; + clean?: boolean; +}; +declare function setup({ + cwd, + clean, + variants +}: SetupOptions): { + templatesDir: string; +}; +type CreateOptions = { + cwd: string; + testName: string; + templatesDir: string; +}; +declare function createProject({ + cwd, + testName, + templatesDir +}: CreateOptions): CreateProject; +type PreviewOptions = { + cwd: string; + command?: string; +}; +declare function startPreview({ + cwd, + command +}: PreviewOptions): Promise<{ + url: string; + close: () => Promise; +}>; +declare module "vitest" { + interface ProvidedContext { + testDir: string; + templatesDir: string; + variants: ProjectVariant[]; + } +} +declare function setupGlobal({ + TEST_DIR, + pre, + post +}: { + TEST_DIR: string; + pre?: () => Promise; + post?: () => Promise; +}): ({ + provide +}: TestProject) => Promise<() => Promise>; +type Fixtures = { + page: Page; + cwd(addonTestCase: AddonTestCase): string; +}; +type AddonTestCase = { + variant: ProjectVariant; + kind: { + type: string; + options: OptionMap; + }; +}; +type SetupTestOptions = { + kinds: Array["kind"]>; + filter?: (addonTestCase: AddonTestCase) => boolean; + browser?: boolean; + preAdd?: (o: { + addonTestCase: AddonTestCase; + cwd: string; + }) => Promise | void; +}; +type PrepareServerOptions = { + cwd: string; + page: Page; + buildCommand?: string; + previewCommand?: string; +}; +type PrepareServerReturn = { + url: string; + close: () => Promise; +}; +declare function prepareServer({ + cwd, + page, + buildCommand, + previewCommand +}: PrepareServerOptions): Promise; +type PlaywrightContext = Pick; +type VitestContext = Pick; +declare function createSetupTest(vitest: VitestContext, playwright?: PlaywrightContext): (addons: Addons, options?: SetupTestOptions) => { + test: vitest.TestAPI; + testCases: Array>; + prepareServer: typeof prepareServer; +}; +export { AddonTestCase, CreateProject, Fixtures, PlaywrightContext, PrepareServerOptions, PrepareServerReturn, ProjectVariant, SetupTestOptions, VitestContext, addPnpmBuildDependencies, createProject, createSetupTest, prepareServer, setup, setupGlobal, startPreview, variants }; +``` diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md new file mode 100644 index 000000000..d5ecc3556 --- /dev/null +++ b/packages/sv/api-surface.md @@ -0,0 +1,25 @@ +# sv - Public API Surface + + + +```ts +type TemplateType = (typeof templateTypes)[number]; +type LanguageType = (typeof languageTypes)[number]; +declare const templateTypes: readonly ["minimal", "demo", "library", "addon", "svelte"]; +declare const languageTypes: readonly ["typescript", "checkjs", "none"]; +type Options = { + name: string; + template: TemplateType; + types: LanguageType; +}; +declare function create(cwd: string, options: Options): void; +type FileEditor = Workspace & { + content: string; +}; +type FileType = { + name: (options: Workspace) => string; + condition?: ConditionDefinition; + content: (editor: FileEditor) => string; +}; +export { Addon, AddonDefinition, AddonInput, type AddonMap, AddonReference, AddonResult, AddonSource, BaseQuestion, BooleanQuestion, ConditionDefinition, ConfiguredAddon, FileEditor, FileType, type InstallOptions, type LanguageType, LoadedAddon, MultiSelectQuestion, NumberQuestion, OptionBuilder, OptionDefinition, type OptionMap, OptionValues, PackageDefinition, PreparedAddon, Question, Scripts, SelectQuestion, SetupResult, StringQuestion, SvApi, type TemplateType, TestDefinition, Tests, Verification, Workspace, WorkspaceOptions, add, create, createWorkspace, defineAddon, defineAddonOptions, getErrorHint, officialAddons }; +``` From 622fed9648b913495237f52dc4817d25cdd1716b Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 23:16:31 +0200 Subject: [PATCH 08/31] chore: format api-surface snapshots via Prettier in generator Made-with: Cursor --- packages/sv-utils/api-surface.md | 1503 ++++++++++++++++++---------- packages/sv/api-surface-testing.md | 64 +- packages/sv/api-surface.md | 54 +- scripts/generate-api-surface.js | 22 +- 4 files changed, 1113 insertions(+), 530 deletions(-) diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index 983b6d046..164347766 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -3,65 +3,76 @@ ```ts -type Agent = 'npm' | 'yarn' | 'yarn@berry' | 'pnpm' | 'pnpm@6' | 'bun' | 'deno'; -type AgentName = 'npm' | 'yarn' | 'pnpm' | 'bun' | 'deno'; -type AgentCommandValue = (string | number)[] | ((args: string[]) => string[]) | null; +type Agent = "npm" | "yarn" | "yarn@berry" | "pnpm" | "pnpm@6" | "bun" | "deno"; +type AgentName = "npm" | "yarn" | "pnpm" | "bun" | "deno"; +type AgentCommandValue = + | (string | number)[] + | ((args: string[]) => string[]) + | null; interface AgentCommands { - 'agent': AgentCommandValue; - 'run': AgentCommandValue; - 'install': AgentCommandValue; - 'frozen': AgentCommandValue; - 'global': AgentCommandValue; - 'add': AgentCommandValue; - 'upgrade': AgentCommandValue; - 'upgrade-interactive': AgentCommandValue; - 'dedupe': AgentCommandValue; - 'execute': AgentCommandValue; - 'execute-local': AgentCommandValue; - 'uninstall': AgentCommandValue; - 'global_uninstall': AgentCommandValue; + agent: AgentCommandValue; + run: AgentCommandValue; + install: AgentCommandValue; + frozen: AgentCommandValue; + global: AgentCommandValue; + add: AgentCommandValue; + upgrade: AgentCommandValue; + "upgrade-interactive": AgentCommandValue; + dedupe: AgentCommandValue; + execute: AgentCommandValue; + "execute-local": AgentCommandValue; + uninstall: AgentCommandValue; + global_uninstall: AgentCommandValue; } type Command = keyof AgentCommands; interface ResolvedCommand { - command: string; - + args: string[]; } -type DetectStrategy = 'lockfile' | 'packageManager-field' | 'devEngines-field' | 'install-metadata'; +type DetectStrategy = + | "lockfile" + | "packageManager-field" + | "devEngines-field" + | "install-metadata"; interface DetectOptions { - cwd?: string; - + strategies?: DetectStrategy[]; - + onUnknown?: (packageManager: string) => DetectResult | null | undefined; - + stopDir?: string | ((currentDir: string) => boolean); - + packageJsonParser?: (content: string, filepath: string) => any | Promise; } interface DetectResult { - name: AgentName; - + agent: Agent; - + version?: string; } declare const COMMANDS: { npm: AgentCommands; yarn: AgentCommands; - 'yarn@berry': AgentCommands; + "yarn@berry": AgentCommands; pnpm: AgentCommands; - 'pnpm@6': AgentCommands; + "pnpm@6": AgentCommands; bun: AgentCommands; deno: AgentCommands; }; -declare function resolveCommand(agent: Agent, command: Command, args: string[]): ResolvedCommand | null; +declare function resolveCommand( + agent: Agent, + command: Command, + args: string[], +): ResolvedCommand | null; -declare function constructCommand(value: AgentCommandValue, args: string[]): ResolvedCommand | null; +declare function constructCommand( + value: AgentCommandValue, + args: string[], +): ResolvedCommand | null; declare const AGENTS: Agent[]; declare function detect(options?: DetectOptions): Promise; @@ -114,32 +125,59 @@ type TomlValue = TomlPrimitive | TomlValue[] | TomlTable; declare class LineCounter { lineStarts: number[]; - + addNewLine: (offset: number) => number; - + linePos: (offset: number) => { line: number; col: number; }; } -type ErrorCode = 'ALIAS_PROPS' | 'BAD_ALIAS' | 'BAD_DIRECTIVE' | 'BAD_DQ_ESCAPE' | 'BAD_INDENT' | 'BAD_PROP_ORDER' | 'BAD_SCALAR_START' | 'BLOCK_AS_IMPLICIT_KEY' | 'BLOCK_IN_FLOW' | 'DUPLICATE_KEY' | 'IMPOSSIBLE' | 'KEY_OVER_1024_CHARS' | 'MISSING_CHAR' | 'MULTILINE_IMPLICIT_KEY' | 'MULTIPLE_ANCHORS' | 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'NON_STRING_KEY' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED' | 'UNEXPECTED_TOKEN' | 'BAD_COLLECTION_TYPE'; +type ErrorCode = + | "ALIAS_PROPS" + | "BAD_ALIAS" + | "BAD_DIRECTIVE" + | "BAD_DQ_ESCAPE" + | "BAD_INDENT" + | "BAD_PROP_ORDER" + | "BAD_SCALAR_START" + | "BLOCK_AS_IMPLICIT_KEY" + | "BLOCK_IN_FLOW" + | "DUPLICATE_KEY" + | "IMPOSSIBLE" + | "KEY_OVER_1024_CHARS" + | "MISSING_CHAR" + | "MULTILINE_IMPLICIT_KEY" + | "MULTIPLE_ANCHORS" + | "MULTIPLE_DOCS" + | "MULTIPLE_TAGS" + | "NON_STRING_KEY" + | "TAB_AS_INDENT" + | "TAG_RESOLVE_FAILED" + | "UNEXPECTED_TOKEN" + | "BAD_COLLECTION_TYPE"; type LinePos = { line: number; col: number; }; declare class YAMLError extends Error { - name: 'YAMLParseError' | 'YAMLWarning'; + name: "YAMLParseError" | "YAMLWarning"; code: ErrorCode; message: string; pos: [number, number]; linePos?: [LinePos] | [LinePos, LinePos]; - constructor(name: YAMLError['name'], pos: [number, number], code: ErrorCode, message: string); + constructor( + name: YAMLError["name"], + pos: [number, number], + code: ErrorCode, + message: string, + ); } declare class YAMLWarning extends YAMLError { constructor(pos: [number, number], code: ErrorCode, message: string); } type Reviver = (key: unknown, value: unknown) => unknown; -type LogLevelId = 'silent' | 'error' | 'warn' | 'debug'; +type LogLevelId = "silent" | "error" | "warn" | "debug"; interface AnchorData { aliasCount: number; count: number; @@ -147,7 +185,7 @@ interface AnchorData { } interface ToJSContext { anchors: Map; - + aliasResolveCache?: Node[]; doc: Document; keep: boolean; @@ -162,12 +200,17 @@ declare namespace Scalar { source: string; srcToken?: FlowScalar | BlockScalar; } - type BLOCK_FOLDED = 'BLOCK_FOLDED'; - type BLOCK_LITERAL = 'BLOCK_LITERAL'; - type PLAIN = 'PLAIN'; - type QUOTE_DOUBLE = 'QUOTE_DOUBLE'; - type QUOTE_SINGLE = 'QUOTE_SINGLE'; - type Type = BLOCK_FOLDED | BLOCK_LITERAL | PLAIN | QUOTE_DOUBLE | QUOTE_SINGLE; + type BLOCK_FOLDED = "BLOCK_FOLDED"; + type BLOCK_LITERAL = "BLOCK_LITERAL"; + type PLAIN = "PLAIN"; + type QUOTE_DOUBLE = "QUOTE_DOUBLE"; + type QUOTE_SINGLE = "QUOTE_SINGLE"; + type Type = + | BLOCK_FOLDED + | BLOCK_LITERAL + | PLAIN + | QUOTE_DOUBLE + | QUOTE_SINGLE; } declare class Scalar extends NodeBase { static readonly BLOCK_FOLDED = "BLOCK_FOLDED"; @@ -176,15 +219,15 @@ declare class Scalar extends NodeBase { static readonly QUOTE_DOUBLE = "QUOTE_DOUBLE"; static readonly QUOTE_SINGLE = "QUOTE_SINGLE"; value: T; - + anchor?: string; - + format?: string; - + minFractionDigits?: number; - + source?: string; - + type?: Scalar.Type; constructor(value: T); toJSON(arg?: any, ctx?: ToJSContext): any; @@ -203,133 +246,172 @@ type StringifyContext = { inFlow: boolean | null; inStringifyKey?: boolean; flowCollectionPadding: string; - options: Readonly>>; + options: Readonly< + Required> + >; resolvedAliases?: Set; }; declare abstract class Collection extends NodeBase { schema: Schema | undefined; [NODE_TYPE]: symbol; items: unknown[]; - + anchor?: string; - + flow?: boolean; constructor(type: symbol, schema?: Schema); - + clone(schema?: Schema): Collection; - + abstract add(value: unknown): void; - + abstract delete(key: unknown): boolean; - + abstract get(key: unknown, keepScalar?: boolean): unknown; - + abstract has(key: unknown): boolean; - + abstract set(key: unknown, value: unknown): void; - + addIn(path: Iterable, value: unknown): void; - + deleteIn(path: Iterable): boolean; - + getIn(path: Iterable, keepScalar?: boolean): unknown; hasAllNullValues(allowScalar?: boolean): boolean; - + hasIn(path: Iterable): boolean; - + setIn(path: Iterable, value: unknown): void; } declare namespace YAMLSeq { - interface Parsed = ParsedNode> extends YAMLSeq { + interface Parsed< + T extends ParsedNode | Pair = ParsedNode, + > extends YAMLSeq { items: T[]; range: Range; srcToken?: BlockSequence | FlowCollection; } } declare class YAMLSeq extends Collection { - static get tagName(): 'tag:yaml.org,2002:seq'; + static get tagName(): "tag:yaml.org,2002:seq"; items: T[]; constructor(schema?: Schema); add(value: T): void; - + delete(key: unknown): boolean; - + get(key: unknown, keepScalar: true): Scalar | undefined; get(key: unknown, keepScalar?: false): T | undefined; get(key: unknown, keepScalar?: boolean): T | Scalar | undefined; - + has(key: unknown): boolean; - + set(key: unknown, value: T): void; toJSON(_?: unknown, ctx?: ToJSContext): unknown[]; - toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + toString( + ctx?: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ): string; static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq; } interface TagBase { - createNode?: (schema: Schema, value: unknown, ctx: CreateNodeContext) => Node; - - default?: boolean | 'key'; - + + default?: boolean | "key"; + format?: string; - + identify?: (value: unknown) => boolean; - + tag: string; } interface ScalarTag extends TagBase { collection?: never; nodeClass?: never; - - resolve(value: string, onError: (message: string) => void, options: ParseOptions): unknown; - - stringify?: (item: Scalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void) => string; - + + resolve( + value: string, + onError: (message: string) => void, + options: ParseOptions, + ): unknown; + + stringify?: ( + item: Scalar, + ctx: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ) => string; + test?: RegExp; } interface CollectionTag extends TagBase { stringify?: never; test?: never; - - collection: 'map' | 'seq'; - + + collection: "map" | "seq"; + nodeClass?: { new (schema?: Schema): Node; from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node; }; - - resolve?: (value: YAMLMap.Parsed | YAMLSeq.Parsed, onError: (message: string) => void, options: ParseOptions) => unknown; + + resolve?: ( + value: YAMLMap.Parsed | YAMLSeq.Parsed, + onError: (message: string) => void, + options: ParseOptions, + ) => unknown; } -type MapLike = Map | Set | Record; +type MapLike = + | Map + | Set + | Record; declare namespace YAMLMap { - interface Parsed extends YAMLMap { + interface Parsed< + K extends ParsedNode = ParsedNode, + V extends ParsedNode | null = ParsedNode | null, + > extends YAMLMap { items: Pair[]; range: Range; srcToken?: BlockMap | FlowCollection; } } declare class YAMLMap extends Collection { - static get tagName(): 'tag:yaml.org,2002:map'; + static get tagName(): "tag:yaml.org,2002:map"; items: Pair[]; constructor(schema?: Schema); - + static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap; - - add(pair: Pair | { - key: K; - value: V; - }, overwrite?: boolean): void; + + add( + pair: + | Pair + | { + key: K; + value: V; + }, + overwrite?: boolean, + ): void; delete(key: unknown): boolean; get(key: unknown, keepScalar: true): Scalar | undefined; get(key: unknown, keepScalar?: false): V | undefined; get(key: unknown, keepScalar?: boolean): V | Scalar | undefined; has(key: unknown): boolean; set(key: K, value: V): void; - - toJSON>(_?: unknown, ctx?: ToJSContext, Type?: { - new (): T; - }): any; - toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + + toJSON>( + _?: unknown, + ctx?: ToJSContext, + Type?: { + new (): T; + }, + ): any; + toString( + ctx?: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ): string; } declare const MAP: unique symbol; declare const SCALAR: unique symbol; @@ -352,7 +434,7 @@ declare class Schema { resolveKnownTags, schema, sortMapEntries, - toStringDefaults + toStringDefaults, }: SchemaOptions); clone(): Schema; } @@ -361,29 +443,37 @@ interface CreateNodeContext { keepUndefined: boolean; onAnchor: (source: unknown) => string; onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; - sourceObjects: Map; + sourceObjects: Map< + unknown, + { + anchor: string | null; + node: Node | null; + } + >; replacer?: Replacer; schema: Schema; } -declare function addPairToJSMap(ctx: ToJSContext | undefined, map: MapLike, { - key, - value -}: Pair): MapLike; +declare function addPairToJSMap( + ctx: ToJSContext | undefined, + map: MapLike, + { key, value }: Pair, +): MapLike; declare class Pair { readonly [NODE_TYPE]: symbol; - + key: K; - + value: V | null; - + srcToken?: CollectionItem; constructor(key: K, value?: V | null); clone(schema?: Schema): Pair; toJSON(_?: unknown, ctx?: ToJSContext): ReturnType; - toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + toString( + ctx?: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ): string; } declare const tagsByName: { binary: ScalarTag; @@ -417,211 +507,253 @@ declare const tagsByName: { type TagId = keyof typeof tagsByName; type Tags = Array; type ParseOptions = { - intAsBigInt?: boolean; - + keepSourceTokens?: boolean; - + lineCounter?: LineCounter; - + prettyErrors?: boolean; - + strict?: boolean; - + stringKeys?: boolean; - + uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean); }; type DocumentOptions = { - _directives?: Directives; - + logLevel?: LogLevelId; - - version?: '1.1' | '1.2' | 'next'; + + version?: "1.1" | "1.2" | "next"; }; type SchemaOptions = { - compat?: string | Tags | null; - + customTags?: Tags | ((tags: Tags) => Tags) | null; - + merge?: boolean; - + resolveKnownTags?: boolean; - + schema?: string | Schema; - + sortMapEntries?: boolean | ((a: Pair, b: Pair) => number); - + toStringDefaults?: ToStringOptions; }; type CreateNodeOptions = { - aliasDuplicateObjects?: boolean; - - anchorPrefix?: string; + + anchorPrefix?: string; flow?: boolean; - + keepUndefined?: boolean | null; onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; - + tag?: string; }; type ToJSOptions = { - mapAsMap?: boolean; - + maxAliasCount?: number; - + onAnchor?: (value: unknown, count: number) => void; - + reviver?: Reviver; }; type ToStringOptions = { - - blockQuote?: boolean | 'folded' | 'literal'; - - collectionStyle?: 'any' | 'block' | 'flow'; - + blockQuote?: boolean | "folded" | "literal"; + + collectionStyle?: "any" | "block" | "flow"; + commentString?: (comment: string) => string; - + defaultKeyType?: Scalar.Type | null; - + defaultStringType?: Scalar.Type; - + directives?: boolean | null; - + doubleQuotedAsJSON?: boolean; - + doubleQuotedMinMultiLineLength?: number; - + falseStr?: string; - + flowCollectionPadding?: boolean; - + indent?: number; - + indentSeq?: boolean; - + lineWidth?: number; - + minContentWidth?: number; - + nullStr?: string; - + simpleKeys?: boolean; - + singleQuote?: boolean | null; - + trueStr?: string; - + verifyAliasOrder?: boolean; }; type Node = Alias | Scalar | YAMLMap | YAMLSeq; -type NodeType = T extends string | number | bigint | boolean | null | undefined ? Scalar : T extends Date ? Scalar : T extends Array ? YAMLSeq> : T extends { - [key: string]: any; -} ? YAMLMap, NodeType> : T extends { - [key: number]: any; -} ? YAMLMap, NodeType> : Node; -type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed; +type NodeType = T extends + | string + | number + | bigint + | boolean + | null + | undefined + ? Scalar + : T extends Date + ? Scalar + : T extends Array + ? YAMLSeq> + : T extends { + [key: string]: any; + } + ? YAMLMap, NodeType> + : T extends { + [key: number]: any; + } + ? YAMLMap, NodeType> + : Node; +type ParsedNode = + | Alias.Parsed + | Scalar.Parsed + | YAMLMap.Parsed + | YAMLSeq.Parsed; type Range = [number, number, number]; declare abstract class NodeBase { readonly [NODE_TYPE]: symbol; - + comment?: string | null; - + commentBefore?: string | null; - + range?: Range | null; - + spaceBefore?: boolean; - + srcToken?: Token; - + tag?: string; - - addToJSMap?: (ctx: ToJSContext | undefined, map: MapLike, value: unknown) => void; - + + addToJSMap?: ( + ctx: ToJSContext | undefined, + map: MapLike, + value: unknown, + ) => void; + abstract toJSON(): any; - abstract toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + abstract toString( + ctx?: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ): string; constructor(type: symbol); - + clone(): NodeBase; - - toJS(doc: Document, { - mapAsMap, - maxAliasCount, - onAnchor, - reviver - }?: ToJSOptions): any; + + toJS( + doc: Document, + { mapAsMap, maxAliasCount, onAnchor, reviver }?: ToJSOptions, + ): any; } interface SourceToken { - type: 'byte-order-mark' | 'doc-mode' | 'doc-start' | 'space' | 'comment' | 'newline' | 'directive-line' | 'anchor' | 'tag' | 'seq-item-ind' | 'explicit-key-ind' | 'map-value-ind' | 'flow-map-start' | 'flow-map-end' | 'flow-seq-start' | 'flow-seq-end' | 'flow-error-end' | 'comma' | 'block-scalar-header'; + type: + | "byte-order-mark" + | "doc-mode" + | "doc-start" + | "space" + | "comment" + | "newline" + | "directive-line" + | "anchor" + | "tag" + | "seq-item-ind" + | "explicit-key-ind" + | "map-value-ind" + | "flow-map-start" + | "flow-map-end" + | "flow-seq-start" + | "flow-seq-end" + | "flow-error-end" + | "comma" + | "block-scalar-header"; offset: number; indent: number; source: string; } interface ErrorToken { - type: 'error'; + type: "error"; offset: number; source: string; message: string; } interface Directive$1 { - type: 'directive'; + type: "directive"; offset: number; source: string; } interface Document$1 { - type: 'document'; + type: "document"; offset: number; start: SourceToken[]; value?: Token; end?: SourceToken[]; } interface DocumentEnd { - type: 'doc-end'; + type: "doc-end"; offset: number; source: string; end?: SourceToken[]; } interface FlowScalar { - type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar'; + type: "alias" | "scalar" | "single-quoted-scalar" | "double-quoted-scalar"; offset: number; indent: number; source: string; end?: SourceToken[]; } interface BlockScalar { - type: 'block-scalar'; + type: "block-scalar"; offset: number; indent: number; props: Token[]; source: string; } interface BlockMap { - type: 'block-map'; + type: "block-map"; offset: number; indent: number; - items: Array<{ - start: SourceToken[]; - explicitKey?: true; - key?: never; - sep?: never; - value?: never; - } | { - start: SourceToken[]; - explicitKey?: true; - key: Token | null; - sep: SourceToken[]; - value?: Token; - }>; + items: Array< + | { + start: SourceToken[]; + explicitKey?: true; + key?: never; + sep?: never; + value?: never; + } + | { + start: SourceToken[]; + explicitKey?: true; + key: Token | null; + sep: SourceToken[]; + value?: Token; + } + >; } interface BlockSequence { - type: 'block-seq'; + type: "block-seq"; offset: number; indent: number; items: Array<{ @@ -638,19 +770,29 @@ type CollectionItem = { value?: Token; }; interface FlowCollection { - type: 'flow-collection'; + type: "flow-collection"; offset: number; indent: number; start: SourceToken; items: CollectionItem[]; end: SourceToken[]; } -type Token = SourceToken | ErrorToken | Directive$1 | Document$1 | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection; +type Token = + | SourceToken + | ErrorToken + | Directive$1 + | Document$1 + | DocumentEnd + | FlowScalar + | BlockScalar + | BlockMap + | BlockSequence + | FlowCollection; declare namespace Alias { interface Parsed extends Alias { range: Range; srcToken?: FlowScalar & { - type: 'alias'; + type: "alias"; }; } } @@ -658,112 +800,176 @@ declare class Alias extends NodeBase { source: string; anchor?: never; constructor(source: string); - - resolve(doc: Document, ctx?: ToJSContext): Scalar | YAMLMap | YAMLSeq | undefined; + + resolve( + doc: Document, + ctx?: ToJSContext, + ): Scalar | YAMLMap | YAMLSeq | undefined; toJSON(_arg?: unknown, ctx?: ToJSContext): unknown; - toString(ctx?: StringifyContext, _onComment?: () => void, _onChompKeep?: () => void): string; + toString( + ctx?: StringifyContext, + _onComment?: () => void, + _onChompKeep?: () => void, + ): string; } type Replacer = any[] | ((key: any, value: any) => unknown); declare namespace Document { - - interface Parsed extends Document { + interface Parsed< + Contents extends ParsedNode = ParsedNode, + Strict extends boolean = true, + > extends Document { directives: Directives; range: Range; } } -declare class Document { +declare class Document< + Contents extends Node = Node, + Strict extends boolean = true, +> { readonly [NODE_TYPE]: symbol; - + commentBefore: string | null; - + comment: string | null; - + contents: Strict extends true ? Contents | null : Contents; directives: Strict extends true ? Directives | undefined : Directives; - + errors: YAMLError[]; - options: Required>; - + options: Required< + Omit< + ParseOptions & DocumentOptions, + "_directives" | "lineCounter" | "version" + > + >; + range?: Range; - + schema: Schema; - + warnings: YAMLWarning[]; - - constructor(value?: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions); - constructor(value: any, replacer: null | Replacer, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions); - + + constructor( + value?: any, + options?: DocumentOptions & + SchemaOptions & + ParseOptions & + CreateNodeOptions, + ); + constructor( + value: any, + replacer: null | Replacer, + options?: DocumentOptions & + SchemaOptions & + ParseOptions & + CreateNodeOptions, + ); + clone(): Document; - + add(value: any): void; - + addIn(path: Iterable, value: unknown): void; - - createAlias(node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, name?: string): Alias; - + + createAlias( + node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, + name?: string, + ): Alias; + createNode(value: T, options?: CreateNodeOptions): NodeType; - createNode(value: T, replacer: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions): NodeType; - - createPair(key: unknown, value: unknown, options?: CreateNodeOptions): Pair; - + createNode( + value: T, + replacer: Replacer | CreateNodeOptions | null, + options?: CreateNodeOptions, + ): NodeType; + + createPair( + key: unknown, + value: unknown, + options?: CreateNodeOptions, + ): Pair; + delete(key: unknown): boolean; - + deleteIn(path: Iterable | null): boolean; - + get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any; - - getIn(path: Iterable | null, keepScalar?: boolean): Strict extends true ? unknown : any; - + + getIn( + path: Iterable | null, + keepScalar?: boolean, + ): Strict extends true ? unknown : any; + has(key: unknown): boolean; - + hasIn(path: Iterable | null): boolean; - + set(key: any, value: unknown): void; - + setIn(path: Iterable | null, value: unknown): void; - - setSchema(version: '1.1' | '1.2' | 'next' | null, options?: SchemaOptions): void; - - toJS(opt?: ToJSOptions & { - [ignored: string]: unknown; - }): any; - - toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']): any; - + + setSchema( + version: "1.1" | "1.2" | "next" | null, + options?: SchemaOptions, + ): void; + + toJS( + opt?: ToJSOptions & { + [ignored: string]: unknown; + }, + ): any; + + toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions["onAnchor"]): any; + toString(options?: ToStringOptions): string; } declare class Directives { - static defaultYaml: Directives['yaml']; - static defaultTags: Directives['tags']; + static defaultYaml: Directives["yaml"]; + static defaultTags: Directives["tags"]; yaml: { - version: '1.1' | '1.2' | 'next'; + version: "1.1" | "1.2" | "next"; explicit?: boolean; }; tags: Record; - + docStart: true | null; - + docEnd: boolean; - + private atNextDocument?; - constructor(yaml?: Directives['yaml'], tags?: Directives['tags']); + constructor(yaml?: Directives["yaml"], tags?: Directives["tags"]); clone(): Directives; - + atDocument(): Directives; - - add(line: string, onError: (offset: number, message: string, warning?: boolean) => void): boolean; - + + add( + line: string, + onError: (offset: number, message: string, warning?: boolean) => void, + ): boolean; + tagName(source: string, onError: (message: string) => void): string | null; - + tagString(tag: string): string; toString(doc?: Document): string; } -declare function parseDocument(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Contents extends ParsedNode ? Document.Parsed : Document; +declare function parseDocument< + Contents extends Node = ParsedNode, + Strict extends boolean = true, +>( + source: string, + options?: ParseOptions & DocumentOptions & SchemaOptions, +): Contents extends ParsedNode + ? Document.Parsed + : Document; declare module "estree" { interface TSTypeAnnotation { type: "TSTypeAnnotation"; - typeAnnotation: TSStringKeyword | TSTypeReference | TSUnionType | TSIndexedAccessType; + typeAnnotation: + | TSStringKeyword + | TSTypeReference + | TSUnionType + | TSIndexedAccessType; } interface TSStringKeyword { type: "TSStringKeyword"; @@ -808,7 +1014,9 @@ declare module "estree" { typeAnnotation: TSTypeAnnotation; } interface TSProgram extends Omit { - body: Array; + body: Array< + Directive | Statement | ModuleDeclaration | TSModuleDeclaration + >; } interface TSUnionType { type: "TSUnionType"; @@ -865,14 +1073,20 @@ declare class Comments { private leading; private trailing; constructor(); - add(node: BaseNode$1, comment: CommentType, options?: { - position?: "leading" | "trailing"; - }): void; - remove(predicate: (comment: estree.Comment) => boolean | undefined | null): void; + add( + node: BaseNode$1, + comment: CommentType, + options?: { + position?: "leading" | "trailing"; + }, + ): void; + remove( + predicate: (comment: estree.Comment) => boolean | undefined | null, + ): void; } type ParseBase = { source: string; - + generateCode(): string; }; declare function parseScript(source: string): { @@ -909,21 +1123,30 @@ interface Dedent { } type CreateDedent = (options: DedentOptions) => Dedent; declare const dedent: Dedent; -declare module 'zimmerframe' { - export function walk | null>(node: T, state: U, visitors: Visitors): T; +declare module "zimmerframe" { + export function walk< + T extends { + type: string; + }, + U extends Record | null, + >(node: T, state: U, visitors: Visitors): T; type BaseNode = { type: string; }; type NodeOf = X extends { type: T; - } ? X : never; - type SpecialisedVisitors = { [K in T['type']]?: Visitor, U, T> }; - export type Visitor = (node: T, context: Context) => V | void; - export type Visitors = T['type'] extends '_' ? never : SpecialisedVisitors & { - _?: Visitor; + } + ? X + : never; + type SpecialisedVisitors = { + [K in T["type"]]?: Visitor, U, T>; }; + export type Visitor = (node: T, context: Context) => V | void; + export type Visitors = T["type"] extends "_" + ? never + : SpecialisedVisitors & { + _?: Visitor; + }; export interface Context { next: (state?: U) => T | void; path: T[]; @@ -936,82 +1159,164 @@ declare module 'zimmerframe' { declare namespace index_d_exports$1 { export { addAtRule, addDeclaration, addImports, addRule }; } -declare function addRule(node: SvelteAst.CSS.StyleSheetBase, options: { - selector: string; -}): SvelteAst.CSS.Rule; -declare function addDeclaration(node: SvelteAst.CSS.Rule, options: { - property: string; - value: string; -}): void; -declare function addImports(node: SvelteAst.CSS.StyleSheetBase, options: { - imports: string[]; -}): void; -declare function addAtRule(node: SvelteAst.CSS.StyleSheetBase, options: { - name: string; - params: string; - append: boolean; -}): SvelteAst.CSS.Atrule; +declare function addRule( + node: SvelteAst.CSS.StyleSheetBase, + options: { + selector: string; + }, +): SvelteAst.CSS.Rule; +declare function addDeclaration( + node: SvelteAst.CSS.Rule, + options: { + property: string; + value: string; + }, +): void; +declare function addImports( + node: SvelteAst.CSS.StyleSheetBase, + options: { + imports: string[]; + }, +): void; +declare function addAtRule( + node: SvelteAst.CSS.StyleSheetBase, + options: { + name: string; + params: string; + append: boolean; + }, +): SvelteAst.CSS.Atrule; declare namespace array_d_exports { export { append, create$1 as create, prepend }; } declare function create$1(): estree.ArrayExpression; -declare function append(node: estree.ArrayExpression, element: string | estree.Expression | estree.SpreadElement): void; -declare function prepend(node: estree.ArrayExpression, element: string | estree.Expression | estree.SpreadElement): void; +declare function append( + node: estree.ArrayExpression, + element: string | estree.Expression | estree.SpreadElement, +): void; +declare function prepend( + node: estree.ArrayExpression, + element: string | estree.Expression | estree.SpreadElement, +): void; declare namespace object_d_exports { export { create, overrideProperties, property, propertyNode }; } type ObjectPrimitiveValues = string | number | boolean | undefined | null; -type ObjectValues = ObjectPrimitiveValues | Record | ObjectValues[]; +type ObjectValues = + | ObjectPrimitiveValues + | Record + | ObjectValues[]; type ObjectMap = Record; -declare function property(node: estree.ObjectExpression, options: { - name: string; - fallback: T; -}): T; -declare function propertyNode(node: estree.ObjectExpression, options: { - name: string; - fallback: T; -}): estree.Property; +declare function property( + node: estree.ObjectExpression, + options: { + name: string; + fallback: T; + }, +): T; +declare function propertyNode( + node: estree.ObjectExpression, + options: { + name: string; + fallback: T; + }, +): estree.Property; declare function create(properties: ObjectMap): estree.ObjectExpression; -declare function overrideProperties(objectExpression: estree.ObjectExpression, properties: ObjectMap): void; +declare function overrideProperties( + objectExpression: estree.ObjectExpression, + properties: ObjectMap, +): void; declare namespace common_d_exports { - export { addJsDocComment, addJsDocTypeComment, appendFromString, appendStatement, areNodesEqual, contains, createBlockStatement, createExpressionStatement, createLiteral, createSatisfies, createSpread, createTypeProperty, hasTypeProperty, parseExpression, parseFromString, parseStatement, typeAnnotate }; + export { + addJsDocComment, + addJsDocTypeComment, + appendFromString, + appendStatement, + areNodesEqual, + contains, + createBlockStatement, + createExpressionStatement, + createLiteral, + createSatisfies, + createSpread, + createTypeProperty, + hasTypeProperty, + parseExpression, + parseFromString, + parseStatement, + typeAnnotate, + }; } -declare function addJsDocTypeComment(node: estree.Node, comments: Comments, options: { - type: string; -}): void; -declare function addJsDocComment(node: estree.Node, comments: Comments, options: { - params: Record; -}): void; -declare function typeAnnotate(node: estree.Expression, options: { - type: string; -}): estree.TSAsExpression; -declare function createSatisfies(node: estree.Expression, options: { - type: string; -}): estree.TSSatisfiesExpression; -declare function createSpread(argument: estree.Expression): estree.SpreadElement; -declare function createLiteral(value: string | number | boolean | null): estree.Literal; -declare function areNodesEqual(node: estree.Node, otherNode: estree.Node): boolean; +declare function addJsDocTypeComment( + node: estree.Node, + comments: Comments, + options: { + type: string; + }, +): void; +declare function addJsDocComment( + node: estree.Node, + comments: Comments, + options: { + params: Record; + }, +): void; +declare function typeAnnotate( + node: estree.Expression, + options: { + type: string; + }, +): estree.TSAsExpression; +declare function createSatisfies( + node: estree.Expression, + options: { + type: string; + }, +): estree.TSSatisfiesExpression; +declare function createSpread( + argument: estree.Expression, +): estree.SpreadElement; +declare function createLiteral( + value: string | number | boolean | null, +): estree.Literal; +declare function areNodesEqual( + node: estree.Node, + otherNode: estree.Node, +): boolean; declare function createBlockStatement(): estree.BlockStatement; declare function createExpressionStatement(options: { expression: estree.Expression; }): estree.ExpressionStatement; -declare function appendFromString(node: estree.BlockStatement | estree.Program, options: { - code: string; - comments?: Comments; -}): void; +declare function appendFromString( + node: estree.BlockStatement | estree.Program, + options: { + code: string; + comments?: Comments; + }, +): void; declare function parseExpression(code: string): estree.Expression; declare function parseStatement(code: string): estree.Statement; declare function parseFromString(code: string): T; -declare function appendStatement(node: estree.BlockStatement | estree.Program, options: { - statement: estree.Statement; -}): void; +declare function appendStatement( + node: estree.BlockStatement | estree.Program, + options: { + statement: estree.Statement; + }, +): void; declare function contains(node: estree.Node, targetNode: estree.Node): boolean; -declare function hasTypeProperty(node: estree.TSInterfaceDeclaration["body"]["body"][number], options: { - name: string; -}): boolean; -declare function createTypeProperty(name: string, value: string, optional?: boolean): estree.TSInterfaceBody["body"][number]; +declare function hasTypeProperty( + node: estree.TSInterfaceDeclaration["body"]["body"][number], + options: { + name: string; + }, +): boolean; +declare function createTypeProperty( + name: string, + value: string, + optional?: boolean, +): estree.TSInterfaceBody["body"][number]; declare namespace function_d_exports { export { createArrow, createCall, getArgument }; } @@ -1024,57 +1329,92 @@ declare function createArrow(options: { body: estree.Expression | estree.BlockStatement; async: boolean; }): estree.ArrowFunctionExpression; -declare function getArgument(node: estree.CallExpression, options: { - index: number; - fallback: T; -}): T; +declare function getArgument( + node: estree.CallExpression, + options: { + index: number; + fallback: T; + }, +): T; declare namespace imports_d_exports { - export { addDefault, addEmpty, addNamed, addNamespace$1 as addNamespace, find, remove }; + export { + addDefault, + addEmpty, + addNamed, + addNamespace$1 as addNamespace, + find, + remove, + }; } -declare function addEmpty(node: estree.Program, options: { - from: string; -}): void; -declare function addNamespace$1(node: estree.Program, options: { - from: string; - as: string; -}): void; -declare function addDefault(node: estree.Program, options: { - from: string; - as: string; -}): void; -declare function addNamed(node: estree.Program, options: { - - imports: Record | string[]; - from: string; - isType?: boolean; -}): void; -declare function find(ast: estree.Program, options: { - name: string; - from: string; -}): { - statement: estree.ImportDeclaration; - alias: string; -} | { - statement: undefined; - alias: undefined; -}; -declare function remove(ast: estree.Program, options: { - name: string; - from: string; - statement?: estree.ImportDeclaration; -}): void; +declare function addEmpty( + node: estree.Program, + options: { + from: string; + }, +): void; +declare function addNamespace$1( + node: estree.Program, + options: { + from: string; + as: string; + }, +): void; +declare function addDefault( + node: estree.Program, + options: { + from: string; + as: string; + }, +): void; +declare function addNamed( + node: estree.Program, + options: { + imports: Record | string[]; + from: string; + isType?: boolean; + }, +): void; +declare function find( + ast: estree.Program, + options: { + name: string; + from: string; + }, +): + | { + statement: estree.ImportDeclaration; + alias: string; + } + | { + statement: undefined; + alias: undefined; + }; +declare function remove( + ast: estree.Program, + options: { + name: string; + from: string; + statement?: estree.ImportDeclaration; + }, +): void; declare namespace variables_d_exports { export { createIdentifier, declaration, typeAnnotateDeclarator }; } -declare function declaration(node: estree.Program | estree.Declaration, options: { - kind: "const" | "let" | "var"; - name: string; - value: estree.Expression; -}): estree.VariableDeclaration; +declare function declaration( + node: estree.Program | estree.Declaration, + options: { + kind: "const" | "let" | "var"; + name: string; + value: estree.Expression; + }, +): estree.VariableDeclaration; declare function createIdentifier(name: string): estree.Identifier; -declare function typeAnnotateDeclarator(node: estree.VariableDeclarator, options: { - typeName: string; -}): estree.VariableDeclarator; +declare function typeAnnotateDeclarator( + node: estree.VariableDeclarator, + options: { + typeName: string; + }, +): estree.VariableDeclarator; declare namespace exports_d_exports { export { ExportDefaultResult, addNamespace, createDefault, createNamed }; } @@ -1083,53 +1423,109 @@ type ExportDefaultResult = { value: T; isFallback: boolean; }; -declare function createDefault(node: estree.Program, options: { - fallback: T; -}): ExportDefaultResult; -declare function createNamed(node: estree.Program, options: { - name: string; - fallback: estree.VariableDeclaration; -}): estree.ExportNamedDeclaration; -declare function addNamespace(node: estree.Program, options: { - from: string; - as?: string; -}): void; +declare function createDefault( + node: estree.Program, + options: { + fallback: T; + }, +): ExportDefaultResult; +declare function createNamed( + node: estree.Program, + options: { + name: string; + fallback: estree.VariableDeclaration; + }, +): estree.ExportNamedDeclaration; +declare function addNamespace( + node: estree.Program, + options: { + from: string; + as?: string; + }, +): void; declare namespace kit_d_exports { export { addGlobalAppInterface, addHooksHandle }; } -declare function addGlobalAppInterface(node: estree.TSProgram, options: { - name: "Error" | "Locals" | "PageData" | "PageState" | "Platform"; -}): estree.TSInterfaceDeclaration; -declare function addHooksHandle(node: estree.Program, options: { - language: "ts" | "js"; - newHandleName: string; - handleContent: string; - comments: Comments; -}): void; +declare function addGlobalAppInterface( + node: estree.TSProgram, + options: { + name: "Error" | "Locals" | "PageData" | "PageState" | "Platform"; + }, +): estree.TSInterfaceDeclaration; +declare function addHooksHandle( + node: estree.Program, + options: { + language: "ts" | "js"; + newHandleName: string; + handleContent: string; + comments: Comments; + }, +): void; declare namespace vite_d_exports { export { addPlugin, configProperty, getConfig }; } -declare const addPlugin: (ast: estree.Program, options: { - code: string; - mode?: "append" | "prepend"; -}) => void; +declare const addPlugin: ( + ast: estree.Program, + options: { + code: string; + mode?: "append" | "prepend"; + }, +) => void; -declare function configProperty(ast: estree.Program, config: estree.ObjectExpression, options: { - name: string; - fallback: T; -}): T; +declare function configProperty< + T extends estree.Expression | estree.Identifier, +>( + ast: estree.Program, + config: estree.ObjectExpression, + options: { + name: string; + fallback: T; + }, +): T; declare const getConfig: (ast: estree.Program) => estree.ObjectExpression; declare namespace index_d_exports$3 { - export { array_d_exports as array, common_d_exports as common, exports_d_exports as exports, function_d_exports as functions, imports_d_exports as imports, kit_d_exports as kit, object_d_exports as object, variables_d_exports as variables, vite_d_exports as vite }; + export { + array_d_exports as array, + common_d_exports as common, + exports_d_exports as exports, + function_d_exports as functions, + imports_d_exports as imports, + kit_d_exports as kit, + object_d_exports as object, + variables_d_exports as variables, + vite_d_exports as vite, + }; } declare namespace index_d_exports$2 { - export { addAttribute, addFromRawHtml, appendElement, createElement, insertElement }; + export { + addAttribute, + addFromRawHtml, + appendElement, + createElement, + insertElement, + }; } -declare function createElement(tagName: string, attributes?: Record): SvelteAst.RegularElement; -declare function addAttribute(element: SvelteAst.RegularElement, name: string, value: string): void; -declare function insertElement(fragment: SvelteAst.Fragment, elementToInsert: SvelteAst.Fragment["nodes"][0]): void; -declare function appendElement(fragment: SvelteAst.Fragment, elementToAppend: SvelteAst.Fragment["nodes"][0]): void; -declare function addFromRawHtml(fragment: SvelteAst.Fragment, html: string): void; +declare function createElement( + tagName: string, + attributes?: Record, +): SvelteAst.RegularElement; +declare function addAttribute( + element: SvelteAst.RegularElement, + name: string, + value: string, +): void; +declare function insertElement( + fragment: SvelteAst.Fragment, + elementToInsert: SvelteAst.Fragment["nodes"][0], +): void; +declare function appendElement( + fragment: SvelteAst.Fragment, + elementToAppend: SvelteAst.Fragment["nodes"][0], +): void; +declare function addFromRawHtml( + fragment: SvelteAst.Fragment, + html: string, +): void; declare namespace text_d_exports { export { upsert }; } @@ -1139,98 +1535,145 @@ type CommentEntry = { }; type CommentOption = string | Array; -declare function upsert(content: string, key: string, options?: { - value?: string; - comment?: CommentOption; - separator?: boolean; -}): string; +declare function upsert( + content: string, + key: string, + options?: { + value?: string; + comment?: CommentOption; + separator?: boolean; + }, +): string; declare namespace json_d_exports { export { arrayUpsert, packageScriptsUpsert }; } -declare function arrayUpsert(data: any, key: string, value: any, options?: { - mode?: "append" | "prepend"; -}): void; -declare function packageScriptsUpsert(data: any, key: string, value: string, options?: { - mode?: "append" | "prepend"; -}): void; +declare function arrayUpsert( + data: any, + key: string, + value: any, + options?: { + mode?: "append" | "prepend"; + }, +): void; +declare function packageScriptsUpsert( + data: any, + key: string, + value: string, + options?: { + mode?: "append" | "prepend"; + }, +): void; declare namespace index_d_exports$4 { export { RootWithInstance, addFragment, addSlot, ensureScript }; } type RootWithInstance = SvelteAst.Root & { instance: SvelteAst.Script; }; -declare function ensureScript(ast: SvelteAst.Root, options?: { - language?: "ts" | "js"; -}): asserts ast is RootWithInstance; -declare function addSlot(ast: SvelteAst.Root, options: { - svelteVersion: string; - language?: "ts" | "js"; -}): void; -declare function addFragment(ast: SvelteAst.Root, content: string, options?: { - mode?: "append" | "prepend"; -}): void; +declare function ensureScript( + ast: SvelteAst.Root, + options?: { + language?: "ts" | "js"; + }, +): asserts ast is RootWithInstance; +declare function addSlot( + ast: SvelteAst.Root, + options: { + svelteVersion: string; + language?: "ts" | "js"; + }, +): void; +declare function addFragment( + ast: SvelteAst.Root, + content: string, + options?: { + mode?: "append" | "prepend"; + }, +): void; type TransformFn = (content: string) => string; type TransformOptions = { onError?: (error: unknown) => void; }; declare const transforms: { - - script(cb: (file: { - ast: estree.Program; - comments: Comments; - content: string; - js: typeof index_d_exports$3; - }) => void | false, options?: TransformOptions): (content: string) => string; - - svelte(cb: (file: { - ast: SvelteAst.Root; - content: string; - svelte: typeof index_d_exports$4; - js: typeof index_d_exports$3; - }) => void | false, options?: TransformOptions): (content: string) => string; - - svelteScript(scriptOptions: { - language: "ts" | "js"; - }, cb: (file: { - ast: RootWithInstance; - content: string; - svelte: typeof index_d_exports$4; - js: typeof index_d_exports$3; - }) => void | false, options?: TransformOptions): TransformFn; - - css(cb: (file: { - ast: Omit; - content: string; - css: typeof index_d_exports$1; - }) => void | false, options?: TransformOptions): TransformFn; - - json(cb: (file: { - data: T; - content: string; - json: typeof json_d_exports; - }) => void | false, options?: TransformOptions): TransformFn; - - yaml(cb: (file: { - data: ReturnType["data"]; - content: string; - }) => void | false, options?: TransformOptions): TransformFn; - - toml(cb: (file: { - data: TomlTable; - content: string; - }) => void | false, options?: TransformOptions): TransformFn; - - html(cb: (file: { - ast: SvelteAst.Fragment; - content: string; - html: typeof index_d_exports$2; - }) => void | false, options?: TransformOptions): TransformFn; - - text(cb: (file: { - content: string; - text: typeof text_d_exports; - }) => string | false): TransformFn; + script( + cb: (file: { + ast: estree.Program; + comments: Comments; + content: string; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions, + ): (content: string) => string; + + svelte( + cb: (file: { + ast: SvelteAst.Root; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions, + ): (content: string) => string; + + svelteScript( + scriptOptions: { + language: "ts" | "js"; + }, + cb: (file: { + ast: RootWithInstance; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + css( + cb: (file: { + ast: Omit; + content: string; + css: typeof index_d_exports$1; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + json( + cb: (file: { + data: T; + content: string; + json: typeof json_d_exports; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + yaml( + cb: (file: { + data: ReturnType["data"]; + content: string; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + toml( + cb: (file: { data: TomlTable; content: string }) => void | false, + options?: TransformOptions, + ): TransformFn; + + html( + cb: (file: { + ast: SvelteAst.Fragment; + content: string; + html: typeof index_d_exports$2; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + text( + cb: (file: { + content: string; + text: typeof text_d_exports; + }) => string | false, + ): TransformFn; }; type Version = { major?: number; @@ -1238,11 +1681,17 @@ type Version = { patch?: number; }; declare function splitVersion(str: string): Version; -declare function isVersionUnsupportedBelow(versionStr: string, belowStr: string): boolean | undefined; +declare function isVersionUnsupportedBelow( + versionStr: string, + belowStr: string, +): boolean | undefined; type Printer = (content: string, alt?: string) => string; declare function createPrinter(...conditions: boolean[]): Printer[]; -declare function sanitizeName(name: string, style: "package" | "wrangler"): string; +declare function sanitizeName( + name: string, + style: "package" | "wrangler", +): string; declare const downloadJson: (url: string) => Promise; type Package = { name: string; @@ -1264,12 +1713,19 @@ declare function getPackageJson(cwd: string): { }; declare function readFile(cwd: string, filePath: string): string; declare function fileExists(cwd: string, filePath: string): boolean; -declare function writeFile(cwd: string, filePath: string, content: string): void; -declare function installPackages(dependencies: Array<{ - pkg: string; - version: string; - dev: boolean; -}>, cwd: string): string; +declare function writeFile( + cwd: string, + filePath: string, + content: string, +): void; +declare function installPackages( + dependencies: Array<{ + pkg: string; + version: string; + dev: boolean; + }>, + cwd: string, +): string; declare const commonFilePaths: { readonly packageJson: "package.json"; readonly svelteConfig: "svelte.config.js"; @@ -1295,7 +1751,11 @@ declare const color: { hidden: (str: ColorInput) => string; }; -declare function resolveCommandArray(agent: Agent, command: Command, args: string[]): string[]; +declare function resolveCommandArray( + agent: Agent, + command: Command, + args: string[], +): string[]; declare const parse: { css: typeof parseCss; @@ -1306,5 +1766,40 @@ declare const parse: { toml: typeof parseToml; yaml: typeof parseYaml; }; -export { AGENTS, type AgentName, type estree as AstTypes, COMMANDS, type Comments, type Package, type SvelteAst, type TransformFn, index_d_exports as Walker, color, commonFilePaths, constructCommand, createPrinter, index_d_exports$1 as css, dedent, detect, downloadJson, fileExists, getPackageJson, index_d_exports$2 as html, installPackages, isVersionUnsupportedBelow, index_d_exports$3 as js, json_d_exports as json, parse, readFile, resolveCommand, resolveCommandArray, sanitizeName, splitVersion, index_d_exports$4 as svelte, text_d_exports as text, transforms, writeFile }; +export { + AGENTS, + type AgentName, + type estree as AstTypes, + COMMANDS, + type Comments, + type Package, + type SvelteAst, + type TransformFn, + index_d_exports as Walker, + color, + commonFilePaths, + constructCommand, + createPrinter, + index_d_exports$1 as css, + dedent, + detect, + downloadJson, + fileExists, + getPackageJson, + index_d_exports$2 as html, + installPackages, + isVersionUnsupportedBelow, + index_d_exports$3 as js, + json_d_exports as json, + parse, + readFile, + resolveCommand, + resolveCommandArray, + sanitizeName, + splitVersion, + index_d_exports$4 as svelte, + text_d_exports as text, + transforms, + writeFile, +}; ``` diff --git a/packages/sv/api-surface-testing.md b/packages/sv/api-surface-testing.md index 116eefd8c..c5f6824c2 100644 --- a/packages/sv/api-surface-testing.md +++ b/packages/sv/api-surface-testing.md @@ -3,24 +3,24 @@ ```ts -declare function addPnpmBuildDependencies(cwd: string, packageManager: AgentName | null | undefined, allowedPackages: string[]): Promise; +declare function addPnpmBuildDependencies( + cwd: string, + packageManager: AgentName | null | undefined, + allowedPackages: string[], +): Promise; type ProjectVariant = "kit-js" | "kit-ts" | "vite-js" | "vite-ts"; declare const variants: ProjectVariant[]; type CreateProject = (options: { testId: string; - variant: ProjectVariant; + variant: ProjectVariant; clean?: boolean; }) => string; type SetupOptions = { cwd: string; - variants: readonly ProjectVariant[]; + variants: readonly ProjectVariant[]; clean?: boolean; }; -declare function setup({ - cwd, - clean, - variants -}: SetupOptions): { +declare function setup({ cwd, clean, variants }: SetupOptions): { templatesDir: string; }; type CreateOptions = { @@ -31,16 +31,13 @@ type CreateOptions = { declare function createProject({ cwd, testName, - templatesDir + templatesDir, }: CreateOptions): CreateProject; type PreviewOptions = { cwd: string; command?: string; }; -declare function startPreview({ - cwd, - command -}: PreviewOptions): Promise<{ +declare function startPreview({ cwd, command }: PreviewOptions): Promise<{ url: string; close: () => Promise; }>; @@ -54,14 +51,12 @@ declare module "vitest" { declare function setupGlobal({ TEST_DIR, pre, - post + post, }: { TEST_DIR: string; pre?: () => Promise; post?: () => Promise; -}): ({ - provide -}: TestProject) => Promise<() => Promise>; +}): ({ provide }: TestProject) => Promise<() => Promise>; type Fixtures = { page: Page; cwd(addonTestCase: AddonTestCase): string; @@ -96,14 +91,41 @@ declare function prepareServer({ cwd, page, buildCommand, - previewCommand + previewCommand, }: PrepareServerOptions): Promise; type PlaywrightContext = Pick; -type VitestContext = Pick; -declare function createSetupTest(vitest: VitestContext, playwright?: PlaywrightContext): (addons: Addons, options?: SetupTestOptions) => { +type VitestContext = Pick< + typeof vitest, + "inject" | "test" | "beforeAll" | "beforeEach" +>; +declare function createSetupTest( + vitest: VitestContext, + playwright?: PlaywrightContext, +): ( + addons: Addons, + options?: SetupTestOptions, +) => { test: vitest.TestAPI; testCases: Array>; prepareServer: typeof prepareServer; }; -export { AddonTestCase, CreateProject, Fixtures, PlaywrightContext, PrepareServerOptions, PrepareServerReturn, ProjectVariant, SetupTestOptions, VitestContext, addPnpmBuildDependencies, createProject, createSetupTest, prepareServer, setup, setupGlobal, startPreview, variants }; +export { + AddonTestCase, + CreateProject, + Fixtures, + PlaywrightContext, + PrepareServerOptions, + PrepareServerReturn, + ProjectVariant, + SetupTestOptions, + VitestContext, + addPnpmBuildDependencies, + createProject, + createSetupTest, + prepareServer, + setup, + setupGlobal, + startPreview, + variants, +}; ``` diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md index d5ecc3556..0a10015f7 100644 --- a/packages/sv/api-surface.md +++ b/packages/sv/api-surface.md @@ -5,7 +5,13 @@ ```ts type TemplateType = (typeof templateTypes)[number]; type LanguageType = (typeof languageTypes)[number]; -declare const templateTypes: readonly ["minimal", "demo", "library", "addon", "svelte"]; +declare const templateTypes: readonly [ + "minimal", + "demo", + "library", + "addon", + "svelte", +]; declare const languageTypes: readonly ["typescript", "checkjs", "none"]; type Options = { name: string; @@ -21,5 +27,49 @@ type FileType = { condition?: ConditionDefinition; content: (editor: FileEditor) => string; }; -export { Addon, AddonDefinition, AddonInput, type AddonMap, AddonReference, AddonResult, AddonSource, BaseQuestion, BooleanQuestion, ConditionDefinition, ConfiguredAddon, FileEditor, FileType, type InstallOptions, type LanguageType, LoadedAddon, MultiSelectQuestion, NumberQuestion, OptionBuilder, OptionDefinition, type OptionMap, OptionValues, PackageDefinition, PreparedAddon, Question, Scripts, SelectQuestion, SetupResult, StringQuestion, SvApi, type TemplateType, TestDefinition, Tests, Verification, Workspace, WorkspaceOptions, add, create, createWorkspace, defineAddon, defineAddonOptions, getErrorHint, officialAddons }; +export { + Addon, + AddonDefinition, + AddonInput, + type AddonMap, + AddonReference, + AddonResult, + AddonSource, + BaseQuestion, + BooleanQuestion, + ConditionDefinition, + ConfiguredAddon, + FileEditor, + FileType, + type InstallOptions, + type LanguageType, + LoadedAddon, + MultiSelectQuestion, + NumberQuestion, + OptionBuilder, + OptionDefinition, + type OptionMap, + OptionValues, + PackageDefinition, + PreparedAddon, + Question, + Scripts, + SelectQuestion, + SetupResult, + StringQuestion, + SvApi, + type TemplateType, + TestDefinition, + Tests, + Verification, + Workspace, + WorkspaceOptions, + add, + create, + createWorkspace, + defineAddon, + defineAddonOptions, + getErrorHint, + officialAddons, +}; ``` diff --git a/scripts/generate-api-surface.js b/scripts/generate-api-surface.js index d34bf160b..bc7a5deaf 100644 --- a/scripts/generate-api-surface.js +++ b/scripts/generate-api-surface.js @@ -8,11 +8,14 @@ * * Run: node scripts/generate-api-surface.js * Or: invoked from tsdown `build:done` after all configs finish (see tsdown.config.ts). + * + * Finishes with Prettier (repo root config) so snapshots match `pnpm format`. */ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import * as prettier from 'prettier'; const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); @@ -84,8 +87,17 @@ function clean(source) { return result.trim() + '\n'; } -/** @returns {number} number of api-surface files written */ -export function generateApiSurface() { +/** + * @param {string} absPath absolute path to the markdown file + */ +async function formatWithPrettier(absPath) { + const raw = fs.readFileSync(absPath, 'utf8'); + const formatted = await prettier.format(raw, { filepath: absPath }); + fs.writeFileSync(absPath, formatted, 'utf8'); +} + +/** @returns {Promise} number of api-surface files written */ +export async function generateApiSurface() { let generated = 0; for (const pkg of packages) { const dtsPath = path.resolve(ROOT, pkg.dts); @@ -105,6 +117,7 @@ export function generateApiSurface() { const outPath = path.resolve(ROOT, pkg.out); fs.writeFileSync(outPath, header + cleaned + footer, 'utf8'); + await formatWithPrettier(outPath); generated++; console.log(` ${pkg.name} -> ${pkg.out}`); } @@ -121,5 +134,8 @@ const isMain = process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1]); if (isMain) { - generateApiSurface(); + generateApiSurface().catch((err) => { + console.error(err); + process.exit(1); + }); } From f05e03b5045df08201821334b79b31326daf0a9a Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 23:21:50 +0200 Subject: [PATCH 09/31] chore: satisfy lint (Prettier on api-surface, import process in generator) Made-with: Cursor --- packages/sv-utils/api-surface.md | 2488 +++++++++++++--------------- packages/sv/api-surface-testing.md | 166 +- packages/sv/api-surface.md | 110 +- scripts/generate-api-surface.js | 1 + 4 files changed, 1298 insertions(+), 1467 deletions(-) diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index 164347766..6c4e01448 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -3,76 +3,66 @@ ```ts -type Agent = "npm" | "yarn" | "yarn@berry" | "pnpm" | "pnpm@6" | "bun" | "deno"; -type AgentName = "npm" | "yarn" | "pnpm" | "bun" | "deno"; -type AgentCommandValue = - | (string | number)[] - | ((args: string[]) => string[]) - | null; +type Agent = 'npm' | 'yarn' | 'yarn@berry' | 'pnpm' | 'pnpm@6' | 'bun' | 'deno'; +type AgentName = 'npm' | 'yarn' | 'pnpm' | 'bun' | 'deno'; +type AgentCommandValue = (string | number)[] | ((args: string[]) => string[]) | null; interface AgentCommands { - agent: AgentCommandValue; - run: AgentCommandValue; - install: AgentCommandValue; - frozen: AgentCommandValue; - global: AgentCommandValue; - add: AgentCommandValue; - upgrade: AgentCommandValue; - "upgrade-interactive": AgentCommandValue; - dedupe: AgentCommandValue; - execute: AgentCommandValue; - "execute-local": AgentCommandValue; - uninstall: AgentCommandValue; - global_uninstall: AgentCommandValue; + agent: AgentCommandValue; + run: AgentCommandValue; + install: AgentCommandValue; + frozen: AgentCommandValue; + global: AgentCommandValue; + add: AgentCommandValue; + upgrade: AgentCommandValue; + 'upgrade-interactive': AgentCommandValue; + dedupe: AgentCommandValue; + execute: AgentCommandValue; + 'execute-local': AgentCommandValue; + uninstall: AgentCommandValue; + global_uninstall: AgentCommandValue; } type Command = keyof AgentCommands; interface ResolvedCommand { - command: string; + command: string; - args: string[]; + args: string[]; } -type DetectStrategy = - | "lockfile" - | "packageManager-field" - | "devEngines-field" - | "install-metadata"; +type DetectStrategy = 'lockfile' | 'packageManager-field' | 'devEngines-field' | 'install-metadata'; interface DetectOptions { - cwd?: string; + cwd?: string; - strategies?: DetectStrategy[]; + strategies?: DetectStrategy[]; - onUnknown?: (packageManager: string) => DetectResult | null | undefined; + onUnknown?: (packageManager: string) => DetectResult | null | undefined; - stopDir?: string | ((currentDir: string) => boolean); + stopDir?: string | ((currentDir: string) => boolean); - packageJsonParser?: (content: string, filepath: string) => any | Promise; + packageJsonParser?: (content: string, filepath: string) => any | Promise; } interface DetectResult { - name: AgentName; + name: AgentName; - agent: Agent; + agent: Agent; - version?: string; + version?: string; } declare const COMMANDS: { - npm: AgentCommands; - yarn: AgentCommands; - "yarn@berry": AgentCommands; - pnpm: AgentCommands; - "pnpm@6": AgentCommands; - bun: AgentCommands; - deno: AgentCommands; + npm: AgentCommands; + yarn: AgentCommands; + 'yarn@berry': AgentCommands; + pnpm: AgentCommands; + 'pnpm@6': AgentCommands; + bun: AgentCommands; + deno: AgentCommands; }; declare function resolveCommand( - agent: Agent, - command: Command, - args: string[], + agent: Agent, + command: Command, + args: string[] ): ResolvedCommand | null; -declare function constructCommand( - value: AgentCommandValue, - args: string[], -): ResolvedCommand | null; +declare function constructCommand(value: AgentCommandValue, args: string[]): ResolvedCommand | null; declare const AGENTS: Agent[]; declare function detect(options?: DetectOptions): Promise; @@ -104,1702 +94,1558 @@ declare function detect(options?: DetectOptions): Promise; * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare class TomlDate extends Date { - #private; - constructor(date: string | Date); - isDateTime(): boolean; - isLocal(): boolean; - isDate(): boolean; - isTime(): boolean; - isValid(): boolean; - toISOString(): string; - static wrapAsOffsetDateTime(jsDate: Date, offset?: string): TomlDate; - static wrapAsLocalDateTime(jsDate: Date): TomlDate; - static wrapAsLocalDate(jsDate: Date): TomlDate; - static wrapAsLocalTime(jsDate: Date): TomlDate; + #private; + constructor(date: string | Date); + isDateTime(): boolean; + isLocal(): boolean; + isDate(): boolean; + isTime(): boolean; + isValid(): boolean; + toISOString(): string; + static wrapAsOffsetDateTime(jsDate: Date, offset?: string): TomlDate; + static wrapAsLocalDateTime(jsDate: Date): TomlDate; + static wrapAsLocalDate(jsDate: Date): TomlDate; + static wrapAsLocalTime(jsDate: Date): TomlDate; } type TomlPrimitive = string | number | bigint | boolean | TomlDate; type TomlTable = { - [key: string]: TomlValue; + [key: string]: TomlValue; }; type TomlValue = TomlPrimitive | TomlValue[] | TomlTable; declare class LineCounter { - lineStarts: number[]; + lineStarts: number[]; - addNewLine: (offset: number) => number; + addNewLine: (offset: number) => number; - linePos: (offset: number) => { - line: number; - col: number; - }; + linePos: (offset: number) => { + line: number; + col: number; + }; } type ErrorCode = - | "ALIAS_PROPS" - | "BAD_ALIAS" - | "BAD_DIRECTIVE" - | "BAD_DQ_ESCAPE" - | "BAD_INDENT" - | "BAD_PROP_ORDER" - | "BAD_SCALAR_START" - | "BLOCK_AS_IMPLICIT_KEY" - | "BLOCK_IN_FLOW" - | "DUPLICATE_KEY" - | "IMPOSSIBLE" - | "KEY_OVER_1024_CHARS" - | "MISSING_CHAR" - | "MULTILINE_IMPLICIT_KEY" - | "MULTIPLE_ANCHORS" - | "MULTIPLE_DOCS" - | "MULTIPLE_TAGS" - | "NON_STRING_KEY" - | "TAB_AS_INDENT" - | "TAG_RESOLVE_FAILED" - | "UNEXPECTED_TOKEN" - | "BAD_COLLECTION_TYPE"; + | 'ALIAS_PROPS' + | 'BAD_ALIAS' + | 'BAD_DIRECTIVE' + | 'BAD_DQ_ESCAPE' + | 'BAD_INDENT' + | 'BAD_PROP_ORDER' + | 'BAD_SCALAR_START' + | 'BLOCK_AS_IMPLICIT_KEY' + | 'BLOCK_IN_FLOW' + | 'DUPLICATE_KEY' + | 'IMPOSSIBLE' + | 'KEY_OVER_1024_CHARS' + | 'MISSING_CHAR' + | 'MULTILINE_IMPLICIT_KEY' + | 'MULTIPLE_ANCHORS' + | 'MULTIPLE_DOCS' + | 'MULTIPLE_TAGS' + | 'NON_STRING_KEY' + | 'TAB_AS_INDENT' + | 'TAG_RESOLVE_FAILED' + | 'UNEXPECTED_TOKEN' + | 'BAD_COLLECTION_TYPE'; type LinePos = { - line: number; - col: number; + line: number; + col: number; }; declare class YAMLError extends Error { - name: "YAMLParseError" | "YAMLWarning"; - code: ErrorCode; - message: string; - pos: [number, number]; - linePos?: [LinePos] | [LinePos, LinePos]; - constructor( - name: YAMLError["name"], - pos: [number, number], - code: ErrorCode, - message: string, - ); + name: 'YAMLParseError' | 'YAMLWarning'; + code: ErrorCode; + message: string; + pos: [number, number]; + linePos?: [LinePos] | [LinePos, LinePos]; + constructor(name: YAMLError['name'], pos: [number, number], code: ErrorCode, message: string); } declare class YAMLWarning extends YAMLError { - constructor(pos: [number, number], code: ErrorCode, message: string); + constructor(pos: [number, number], code: ErrorCode, message: string); } type Reviver = (key: unknown, value: unknown) => unknown; -type LogLevelId = "silent" | "error" | "warn" | "debug"; +type LogLevelId = 'silent' | 'error' | 'warn' | 'debug'; interface AnchorData { - aliasCount: number; - count: number; - res: unknown; + aliasCount: number; + count: number; + res: unknown; } interface ToJSContext { - anchors: Map; - - aliasResolveCache?: Node[]; - doc: Document; - keep: boolean; - mapAsMap: boolean; - mapKeyWarned: boolean; - maxAliasCount: number; - onCreate?: (res: unknown) => void; + anchors: Map; + + aliasResolveCache?: Node[]; + doc: Document; + keep: boolean; + mapAsMap: boolean; + mapKeyWarned: boolean; + maxAliasCount: number; + onCreate?: (res: unknown) => void; } declare namespace Scalar { - interface Parsed extends Scalar { - range: Range; - source: string; - srcToken?: FlowScalar | BlockScalar; - } - type BLOCK_FOLDED = "BLOCK_FOLDED"; - type BLOCK_LITERAL = "BLOCK_LITERAL"; - type PLAIN = "PLAIN"; - type QUOTE_DOUBLE = "QUOTE_DOUBLE"; - type QUOTE_SINGLE = "QUOTE_SINGLE"; - type Type = - | BLOCK_FOLDED - | BLOCK_LITERAL - | PLAIN - | QUOTE_DOUBLE - | QUOTE_SINGLE; + interface Parsed extends Scalar { + range: Range; + source: string; + srcToken?: FlowScalar | BlockScalar; + } + type BLOCK_FOLDED = 'BLOCK_FOLDED'; + type BLOCK_LITERAL = 'BLOCK_LITERAL'; + type PLAIN = 'PLAIN'; + type QUOTE_DOUBLE = 'QUOTE_DOUBLE'; + type QUOTE_SINGLE = 'QUOTE_SINGLE'; + type Type = BLOCK_FOLDED | BLOCK_LITERAL | PLAIN | QUOTE_DOUBLE | QUOTE_SINGLE; } declare class Scalar extends NodeBase { - static readonly BLOCK_FOLDED = "BLOCK_FOLDED"; - static readonly BLOCK_LITERAL = "BLOCK_LITERAL"; - static readonly PLAIN = "PLAIN"; - static readonly QUOTE_DOUBLE = "QUOTE_DOUBLE"; - static readonly QUOTE_SINGLE = "QUOTE_SINGLE"; - value: T; + static readonly BLOCK_FOLDED = 'BLOCK_FOLDED'; + static readonly BLOCK_LITERAL = 'BLOCK_LITERAL'; + static readonly PLAIN = 'PLAIN'; + static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE'; + static readonly QUOTE_SINGLE = 'QUOTE_SINGLE'; + value: T; - anchor?: string; + anchor?: string; - format?: string; + format?: string; - minFractionDigits?: number; + minFractionDigits?: number; - source?: string; + source?: string; - type?: Scalar.Type; - constructor(value: T); - toJSON(arg?: any, ctx?: ToJSContext): any; - toString(): string; + type?: Scalar.Type; + constructor(value: T); + toJSON(arg?: any, ctx?: ToJSContext): any; + toString(): string; } type StringifyContext = { - actualString?: boolean; - allNullValues?: boolean; - anchors: Set; - doc: Document; - forceBlockIndent?: boolean; - implicitKey?: boolean; - indent: string; - indentStep: string; - indentAtStart?: number; - inFlow: boolean | null; - inStringifyKey?: boolean; - flowCollectionPadding: string; - options: Readonly< - Required> - >; - resolvedAliases?: Set; + actualString?: boolean; + allNullValues?: boolean; + anchors: Set; + doc: Document; + forceBlockIndent?: boolean; + implicitKey?: boolean; + indent: string; + indentStep: string; + indentAtStart?: number; + inFlow: boolean | null; + inStringifyKey?: boolean; + flowCollectionPadding: string; + options: Readonly>>; + resolvedAliases?: Set; }; declare abstract class Collection extends NodeBase { - schema: Schema | undefined; - [NODE_TYPE]: symbol; - items: unknown[]; + schema: Schema | undefined; + [NODE_TYPE]: symbol; + items: unknown[]; - anchor?: string; + anchor?: string; - flow?: boolean; - constructor(type: symbol, schema?: Schema); + flow?: boolean; + constructor(type: symbol, schema?: Schema); - clone(schema?: Schema): Collection; + clone(schema?: Schema): Collection; - abstract add(value: unknown): void; + abstract add(value: unknown): void; - abstract delete(key: unknown): boolean; + abstract delete(key: unknown): boolean; - abstract get(key: unknown, keepScalar?: boolean): unknown; + abstract get(key: unknown, keepScalar?: boolean): unknown; - abstract has(key: unknown): boolean; + abstract has(key: unknown): boolean; - abstract set(key: unknown, value: unknown): void; + abstract set(key: unknown, value: unknown): void; - addIn(path: Iterable, value: unknown): void; + addIn(path: Iterable, value: unknown): void; - deleteIn(path: Iterable): boolean; + deleteIn(path: Iterable): boolean; - getIn(path: Iterable, keepScalar?: boolean): unknown; - hasAllNullValues(allowScalar?: boolean): boolean; + getIn(path: Iterable, keepScalar?: boolean): unknown; + hasAllNullValues(allowScalar?: boolean): boolean; - hasIn(path: Iterable): boolean; + hasIn(path: Iterable): boolean; - setIn(path: Iterable, value: unknown): void; + setIn(path: Iterable, value: unknown): void; } declare namespace YAMLSeq { - interface Parsed< - T extends ParsedNode | Pair = ParsedNode, - > extends YAMLSeq { - items: T[]; - range: Range; - srcToken?: BlockSequence | FlowCollection; - } + interface Parsed< + T extends ParsedNode | Pair = ParsedNode + > extends YAMLSeq { + items: T[]; + range: Range; + srcToken?: BlockSequence | FlowCollection; + } } declare class YAMLSeq extends Collection { - static get tagName(): "tag:yaml.org,2002:seq"; - items: T[]; - constructor(schema?: Schema); - add(value: T): void; - - delete(key: unknown): boolean; - - get(key: unknown, keepScalar: true): Scalar | undefined; - get(key: unknown, keepScalar?: false): T | undefined; - get(key: unknown, keepScalar?: boolean): T | Scalar | undefined; - - has(key: unknown): boolean; - - set(key: unknown, value: T): void; - toJSON(_?: unknown, ctx?: ToJSContext): unknown[]; - toString( - ctx?: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ): string; - static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq; + static get tagName(): 'tag:yaml.org,2002:seq'; + items: T[]; + constructor(schema?: Schema); + add(value: T): void; + + delete(key: unknown): boolean; + + get(key: unknown, keepScalar: true): Scalar | undefined; + get(key: unknown, keepScalar?: false): T | undefined; + get(key: unknown, keepScalar?: boolean): T | Scalar | undefined; + + has(key: unknown): boolean; + + set(key: unknown, value: T): void; + toJSON(_?: unknown, ctx?: ToJSContext): unknown[]; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq; } interface TagBase { - createNode?: (schema: Schema, value: unknown, ctx: CreateNodeContext) => Node; + createNode?: (schema: Schema, value: unknown, ctx: CreateNodeContext) => Node; - default?: boolean | "key"; + default?: boolean | 'key'; - format?: string; + format?: string; - identify?: (value: unknown) => boolean; + identify?: (value: unknown) => boolean; - tag: string; + tag: string; } interface ScalarTag extends TagBase { - collection?: never; - nodeClass?: never; - - resolve( - value: string, - onError: (message: string) => void, - options: ParseOptions, - ): unknown; - - stringify?: ( - item: Scalar, - ctx: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ) => string; - - test?: RegExp; + collection?: never; + nodeClass?: never; + + resolve(value: string, onError: (message: string) => void, options: ParseOptions): unknown; + + stringify?: ( + item: Scalar, + ctx: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void + ) => string; + + test?: RegExp; } interface CollectionTag extends TagBase { - stringify?: never; - test?: never; + stringify?: never; + test?: never; - collection: "map" | "seq"; + collection: 'map' | 'seq'; - nodeClass?: { - new (schema?: Schema): Node; - from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node; - }; + nodeClass?: { + new (schema?: Schema): Node; + from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node; + }; - resolve?: ( - value: YAMLMap.Parsed | YAMLSeq.Parsed, - onError: (message: string) => void, - options: ParseOptions, - ) => unknown; + resolve?: ( + value: YAMLMap.Parsed | YAMLSeq.Parsed, + onError: (message: string) => void, + options: ParseOptions + ) => unknown; } -type MapLike = - | Map - | Set - | Record; +type MapLike = Map | Set | Record; declare namespace YAMLMap { - interface Parsed< - K extends ParsedNode = ParsedNode, - V extends ParsedNode | null = ParsedNode | null, - > extends YAMLMap { - items: Pair[]; - range: Range; - srcToken?: BlockMap | FlowCollection; - } + interface Parsed< + K extends ParsedNode = ParsedNode, + V extends ParsedNode | null = ParsedNode | null + > extends YAMLMap { + items: Pair[]; + range: Range; + srcToken?: BlockMap | FlowCollection; + } } declare class YAMLMap extends Collection { - static get tagName(): "tag:yaml.org,2002:map"; - items: Pair[]; - constructor(schema?: Schema); - - static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap; - - add( - pair: - | Pair - | { - key: K; - value: V; - }, - overwrite?: boolean, - ): void; - delete(key: unknown): boolean; - get(key: unknown, keepScalar: true): Scalar | undefined; - get(key: unknown, keepScalar?: false): V | undefined; - get(key: unknown, keepScalar?: boolean): V | Scalar | undefined; - has(key: unknown): boolean; - set(key: K, value: V): void; - - toJSON>( - _?: unknown, - ctx?: ToJSContext, - Type?: { - new (): T; - }, - ): any; - toString( - ctx?: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ): string; + static get tagName(): 'tag:yaml.org,2002:map'; + items: Pair[]; + constructor(schema?: Schema); + + static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap; + + add( + pair: + | Pair + | { + key: K; + value: V; + }, + overwrite?: boolean + ): void; + delete(key: unknown): boolean; + get(key: unknown, keepScalar: true): Scalar | undefined; + get(key: unknown, keepScalar?: false): V | undefined; + get(key: unknown, keepScalar?: boolean): V | Scalar | undefined; + has(key: unknown): boolean; + set(key: K, value: V): void; + + toJSON>( + _?: unknown, + ctx?: ToJSContext, + Type?: { + new (): T; + } + ): any; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; } declare const MAP: unique symbol; declare const SCALAR: unique symbol; declare const SEQ: unique symbol; declare const NODE_TYPE: unique symbol; declare class Schema { - compat: Array | null; - knownTags: Record; - name: string; - sortMapEntries: ((a: Pair, b: Pair) => number) | null; - tags: Array; - toStringOptions: Readonly | null; - readonly [MAP]: CollectionTag; - readonly [SCALAR]: ScalarTag; - readonly [SEQ]: CollectionTag; - constructor({ - compat, - customTags, - merge, - resolveKnownTags, - schema, - sortMapEntries, - toStringDefaults, - }: SchemaOptions); - clone(): Schema; + compat: Array | null; + knownTags: Record; + name: string; + sortMapEntries: ((a: Pair, b: Pair) => number) | null; + tags: Array; + toStringOptions: Readonly | null; + readonly [MAP]: CollectionTag; + readonly [SCALAR]: ScalarTag; + readonly [SEQ]: CollectionTag; + constructor({ + compat, + customTags, + merge, + resolveKnownTags, + schema, + sortMapEntries, + toStringDefaults + }: SchemaOptions); + clone(): Schema; } interface CreateNodeContext { - aliasDuplicateObjects: boolean; - keepUndefined: boolean; - onAnchor: (source: unknown) => string; - onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; - sourceObjects: Map< - unknown, - { - anchor: string | null; - node: Node | null; - } - >; - replacer?: Replacer; - schema: Schema; + aliasDuplicateObjects: boolean; + keepUndefined: boolean; + onAnchor: (source: unknown) => string; + onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; + sourceObjects: Map< + unknown, + { + anchor: string | null; + node: Node | null; + } + >; + replacer?: Replacer; + schema: Schema; } declare function addPairToJSMap( - ctx: ToJSContext | undefined, - map: MapLike, - { key, value }: Pair, + ctx: ToJSContext | undefined, + map: MapLike, + { key, value }: Pair ): MapLike; declare class Pair { - readonly [NODE_TYPE]: symbol; + readonly [NODE_TYPE]: symbol; - key: K; + key: K; - value: V | null; + value: V | null; - srcToken?: CollectionItem; - constructor(key: K, value?: V | null); - clone(schema?: Schema): Pair; - toJSON(_?: unknown, ctx?: ToJSContext): ReturnType; - toString( - ctx?: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ): string; + srcToken?: CollectionItem; + constructor(key: K, value?: V | null); + clone(schema?: Schema): Pair; + toJSON(_?: unknown, ctx?: ToJSContext): ReturnType; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; } declare const tagsByName: { - binary: ScalarTag; - bool: ScalarTag & { - test: RegExp; - }; - float: ScalarTag; - floatExp: ScalarTag; - floatNaN: ScalarTag; - floatTime: ScalarTag; - int: ScalarTag; - intHex: ScalarTag; - intOct: ScalarTag; - intTime: ScalarTag; - map: CollectionTag; - merge: ScalarTag & { - identify(value: unknown): boolean; - test: RegExp; - }; - null: ScalarTag & { - test: RegExp; - }; - omap: CollectionTag; - pairs: CollectionTag; - seq: CollectionTag; - set: CollectionTag; - timestamp: ScalarTag & { - test: RegExp; - }; + binary: ScalarTag; + bool: ScalarTag & { + test: RegExp; + }; + float: ScalarTag; + floatExp: ScalarTag; + floatNaN: ScalarTag; + floatTime: ScalarTag; + int: ScalarTag; + intHex: ScalarTag; + intOct: ScalarTag; + intTime: ScalarTag; + map: CollectionTag; + merge: ScalarTag & { + identify(value: unknown): boolean; + test: RegExp; + }; + null: ScalarTag & { + test: RegExp; + }; + omap: CollectionTag; + pairs: CollectionTag; + seq: CollectionTag; + set: CollectionTag; + timestamp: ScalarTag & { + test: RegExp; + }; }; type TagId = keyof typeof tagsByName; type Tags = Array; type ParseOptions = { - intAsBigInt?: boolean; + intAsBigInt?: boolean; - keepSourceTokens?: boolean; + keepSourceTokens?: boolean; - lineCounter?: LineCounter; + lineCounter?: LineCounter; - prettyErrors?: boolean; + prettyErrors?: boolean; - strict?: boolean; + strict?: boolean; - stringKeys?: boolean; + stringKeys?: boolean; - uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean); + uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean); }; type DocumentOptions = { - _directives?: Directives; + _directives?: Directives; - logLevel?: LogLevelId; + logLevel?: LogLevelId; - version?: "1.1" | "1.2" | "next"; + version?: '1.1' | '1.2' | 'next'; }; type SchemaOptions = { - compat?: string | Tags | null; + compat?: string | Tags | null; - customTags?: Tags | ((tags: Tags) => Tags) | null; + customTags?: Tags | ((tags: Tags) => Tags) | null; - merge?: boolean; + merge?: boolean; - resolveKnownTags?: boolean; + resolveKnownTags?: boolean; - schema?: string | Schema; + schema?: string | Schema; - sortMapEntries?: boolean | ((a: Pair, b: Pair) => number); + sortMapEntries?: boolean | ((a: Pair, b: Pair) => number); - toStringDefaults?: ToStringOptions; + toStringDefaults?: ToStringOptions; }; type CreateNodeOptions = { - aliasDuplicateObjects?: boolean; + aliasDuplicateObjects?: boolean; - anchorPrefix?: string; - flow?: boolean; + anchorPrefix?: string; + flow?: boolean; - keepUndefined?: boolean | null; - onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; + keepUndefined?: boolean | null; + onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; - tag?: string; + tag?: string; }; type ToJSOptions = { - mapAsMap?: boolean; + mapAsMap?: boolean; - maxAliasCount?: number; + maxAliasCount?: number; - onAnchor?: (value: unknown, count: number) => void; + onAnchor?: (value: unknown, count: number) => void; - reviver?: Reviver; + reviver?: Reviver; }; type ToStringOptions = { - blockQuote?: boolean | "folded" | "literal"; + blockQuote?: boolean | 'folded' | 'literal'; - collectionStyle?: "any" | "block" | "flow"; + collectionStyle?: 'any' | 'block' | 'flow'; - commentString?: (comment: string) => string; + commentString?: (comment: string) => string; - defaultKeyType?: Scalar.Type | null; + defaultKeyType?: Scalar.Type | null; - defaultStringType?: Scalar.Type; + defaultStringType?: Scalar.Type; - directives?: boolean | null; + directives?: boolean | null; - doubleQuotedAsJSON?: boolean; + doubleQuotedAsJSON?: boolean; - doubleQuotedMinMultiLineLength?: number; + doubleQuotedMinMultiLineLength?: number; - falseStr?: string; + falseStr?: string; - flowCollectionPadding?: boolean; + flowCollectionPadding?: boolean; - indent?: number; + indent?: number; - indentSeq?: boolean; + indentSeq?: boolean; - lineWidth?: number; + lineWidth?: number; - minContentWidth?: number; + minContentWidth?: number; - nullStr?: string; + nullStr?: string; - simpleKeys?: boolean; + simpleKeys?: boolean; - singleQuote?: boolean | null; + singleQuote?: boolean | null; - trueStr?: string; + trueStr?: string; - verifyAliasOrder?: boolean; + verifyAliasOrder?: boolean; }; type Node = Alias | Scalar | YAMLMap | YAMLSeq; -type NodeType = T extends - | string - | number - | bigint - | boolean - | null - | undefined - ? Scalar - : T extends Date - ? Scalar - : T extends Array - ? YAMLSeq> - : T extends { - [key: string]: any; - } - ? YAMLMap, NodeType> - : T extends { - [key: number]: any; - } - ? YAMLMap, NodeType> - : Node; -type ParsedNode = - | Alias.Parsed - | Scalar.Parsed - | YAMLMap.Parsed - | YAMLSeq.Parsed; +type NodeType = T extends string | number | bigint | boolean | null | undefined + ? Scalar + : T extends Date + ? Scalar + : T extends Array + ? YAMLSeq> + : T extends { + [key: string]: any; + } + ? YAMLMap, NodeType> + : T extends { + [key: number]: any; + } + ? YAMLMap, NodeType> + : Node; +type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed; type Range = [number, number, number]; declare abstract class NodeBase { - readonly [NODE_TYPE]: symbol; + readonly [NODE_TYPE]: symbol; - comment?: string | null; + comment?: string | null; - commentBefore?: string | null; + commentBefore?: string | null; - range?: Range | null; + range?: Range | null; - spaceBefore?: boolean; + spaceBefore?: boolean; - srcToken?: Token; + srcToken?: Token; - tag?: string; + tag?: string; - addToJSMap?: ( - ctx: ToJSContext | undefined, - map: MapLike, - value: unknown, - ) => void; + addToJSMap?: (ctx: ToJSContext | undefined, map: MapLike, value: unknown) => void; - abstract toJSON(): any; - abstract toString( - ctx?: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ): string; - constructor(type: symbol); + abstract toJSON(): any; + abstract toString( + ctx?: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void + ): string; + constructor(type: symbol); - clone(): NodeBase; + clone(): NodeBase; - toJS( - doc: Document, - { mapAsMap, maxAliasCount, onAnchor, reviver }?: ToJSOptions, - ): any; + toJS( + doc: Document, + { mapAsMap, maxAliasCount, onAnchor, reviver }?: ToJSOptions + ): any; } interface SourceToken { - type: - | "byte-order-mark" - | "doc-mode" - | "doc-start" - | "space" - | "comment" - | "newline" - | "directive-line" - | "anchor" - | "tag" - | "seq-item-ind" - | "explicit-key-ind" - | "map-value-ind" - | "flow-map-start" - | "flow-map-end" - | "flow-seq-start" - | "flow-seq-end" - | "flow-error-end" - | "comma" - | "block-scalar-header"; - offset: number; - indent: number; - source: string; + type: + | 'byte-order-mark' + | 'doc-mode' + | 'doc-start' + | 'space' + | 'comment' + | 'newline' + | 'directive-line' + | 'anchor' + | 'tag' + | 'seq-item-ind' + | 'explicit-key-ind' + | 'map-value-ind' + | 'flow-map-start' + | 'flow-map-end' + | 'flow-seq-start' + | 'flow-seq-end' + | 'flow-error-end' + | 'comma' + | 'block-scalar-header'; + offset: number; + indent: number; + source: string; } interface ErrorToken { - type: "error"; - offset: number; - source: string; - message: string; + type: 'error'; + offset: number; + source: string; + message: string; } interface Directive$1 { - type: "directive"; - offset: number; - source: string; + type: 'directive'; + offset: number; + source: string; } interface Document$1 { - type: "document"; - offset: number; - start: SourceToken[]; - value?: Token; - end?: SourceToken[]; + type: 'document'; + offset: number; + start: SourceToken[]; + value?: Token; + end?: SourceToken[]; } interface DocumentEnd { - type: "doc-end"; - offset: number; - source: string; - end?: SourceToken[]; + type: 'doc-end'; + offset: number; + source: string; + end?: SourceToken[]; } interface FlowScalar { - type: "alias" | "scalar" | "single-quoted-scalar" | "double-quoted-scalar"; - offset: number; - indent: number; - source: string; - end?: SourceToken[]; + type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar'; + offset: number; + indent: number; + source: string; + end?: SourceToken[]; } interface BlockScalar { - type: "block-scalar"; - offset: number; - indent: number; - props: Token[]; - source: string; + type: 'block-scalar'; + offset: number; + indent: number; + props: Token[]; + source: string; } interface BlockMap { - type: "block-map"; - offset: number; - indent: number; - items: Array< - | { - start: SourceToken[]; - explicitKey?: true; - key?: never; - sep?: never; - value?: never; - } - | { - start: SourceToken[]; - explicitKey?: true; - key: Token | null; - sep: SourceToken[]; - value?: Token; - } - >; + type: 'block-map'; + offset: number; + indent: number; + items: Array< + | { + start: SourceToken[]; + explicitKey?: true; + key?: never; + sep?: never; + value?: never; + } + | { + start: SourceToken[]; + explicitKey?: true; + key: Token | null; + sep: SourceToken[]; + value?: Token; + } + >; } interface BlockSequence { - type: "block-seq"; - offset: number; - indent: number; - items: Array<{ - start: SourceToken[]; - key?: never; - sep?: never; - value?: Token; - }>; + type: 'block-seq'; + offset: number; + indent: number; + items: Array<{ + start: SourceToken[]; + key?: never; + sep?: never; + value?: Token; + }>; } type CollectionItem = { - start: SourceToken[]; - key?: Token | null; - sep?: SourceToken[]; - value?: Token; + start: SourceToken[]; + key?: Token | null; + sep?: SourceToken[]; + value?: Token; }; interface FlowCollection { - type: "flow-collection"; - offset: number; - indent: number; - start: SourceToken; - items: CollectionItem[]; - end: SourceToken[]; + type: 'flow-collection'; + offset: number; + indent: number; + start: SourceToken; + items: CollectionItem[]; + end: SourceToken[]; } type Token = - | SourceToken - | ErrorToken - | Directive$1 - | Document$1 - | DocumentEnd - | FlowScalar - | BlockScalar - | BlockMap - | BlockSequence - | FlowCollection; + | SourceToken + | ErrorToken + | Directive$1 + | Document$1 + | DocumentEnd + | FlowScalar + | BlockScalar + | BlockMap + | BlockSequence + | FlowCollection; declare namespace Alias { - interface Parsed extends Alias { - range: Range; - srcToken?: FlowScalar & { - type: "alias"; - }; - } + interface Parsed extends Alias { + range: Range; + srcToken?: FlowScalar & { + type: 'alias'; + }; + } } declare class Alias extends NodeBase { - source: string; - anchor?: never; - constructor(source: string); - - resolve( - doc: Document, - ctx?: ToJSContext, - ): Scalar | YAMLMap | YAMLSeq | undefined; - toJSON(_arg?: unknown, ctx?: ToJSContext): unknown; - toString( - ctx?: StringifyContext, - _onComment?: () => void, - _onChompKeep?: () => void, - ): string; + source: string; + anchor?: never; + constructor(source: string); + + resolve(doc: Document, ctx?: ToJSContext): Scalar | YAMLMap | YAMLSeq | undefined; + toJSON(_arg?: unknown, ctx?: ToJSContext): unknown; + toString(ctx?: StringifyContext, _onComment?: () => void, _onChompKeep?: () => void): string; } type Replacer = any[] | ((key: any, value: any) => unknown); declare namespace Document { - interface Parsed< - Contents extends ParsedNode = ParsedNode, - Strict extends boolean = true, - > extends Document { - directives: Directives; - range: Range; - } + interface Parsed< + Contents extends ParsedNode = ParsedNode, + Strict extends boolean = true + > extends Document { + directives: Directives; + range: Range; + } } -declare class Document< - Contents extends Node = Node, - Strict extends boolean = true, -> { - readonly [NODE_TYPE]: symbol; +declare class Document { + readonly [NODE_TYPE]: symbol; - commentBefore: string | null; + commentBefore: string | null; - comment: string | null; + comment: string | null; - contents: Strict extends true ? Contents | null : Contents; - directives: Strict extends true ? Directives | undefined : Directives; + contents: Strict extends true ? Contents | null : Contents; + directives: Strict extends true ? Directives | undefined : Directives; - errors: YAMLError[]; - options: Required< - Omit< - ParseOptions & DocumentOptions, - "_directives" | "lineCounter" | "version" - > - >; + errors: YAMLError[]; + options: Required< + Omit + >; - range?: Range; + range?: Range; - schema: Schema; + schema: Schema; - warnings: YAMLWarning[]; + warnings: YAMLWarning[]; - constructor( - value?: any, - options?: DocumentOptions & - SchemaOptions & - ParseOptions & - CreateNodeOptions, - ); - constructor( - value: any, - replacer: null | Replacer, - options?: DocumentOptions & - SchemaOptions & - ParseOptions & - CreateNodeOptions, - ); + constructor( + value?: any, + options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions + ); + constructor( + value: any, + replacer: null | Replacer, + options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions + ); - clone(): Document; + clone(): Document; - add(value: any): void; + add(value: any): void; - addIn(path: Iterable, value: unknown): void; + addIn(path: Iterable, value: unknown): void; - createAlias( - node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, - name?: string, - ): Alias; + createAlias(node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, name?: string): Alias; - createNode(value: T, options?: CreateNodeOptions): NodeType; - createNode( - value: T, - replacer: Replacer | CreateNodeOptions | null, - options?: CreateNodeOptions, - ): NodeType; + createNode(value: T, options?: CreateNodeOptions): NodeType; + createNode( + value: T, + replacer: Replacer | CreateNodeOptions | null, + options?: CreateNodeOptions + ): NodeType; - createPair( - key: unknown, - value: unknown, - options?: CreateNodeOptions, - ): Pair; + createPair( + key: unknown, + value: unknown, + options?: CreateNodeOptions + ): Pair; - delete(key: unknown): boolean; + delete(key: unknown): boolean; - deleteIn(path: Iterable | null): boolean; + deleteIn(path: Iterable | null): boolean; - get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any; + get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any; - getIn( - path: Iterable | null, - keepScalar?: boolean, - ): Strict extends true ? unknown : any; + getIn(path: Iterable | null, keepScalar?: boolean): Strict extends true ? unknown : any; - has(key: unknown): boolean; + has(key: unknown): boolean; - hasIn(path: Iterable | null): boolean; + hasIn(path: Iterable | null): boolean; - set(key: any, value: unknown): void; + set(key: any, value: unknown): void; - setIn(path: Iterable | null, value: unknown): void; + setIn(path: Iterable | null, value: unknown): void; - setSchema( - version: "1.1" | "1.2" | "next" | null, - options?: SchemaOptions, - ): void; + setSchema(version: '1.1' | '1.2' | 'next' | null, options?: SchemaOptions): void; - toJS( - opt?: ToJSOptions & { - [ignored: string]: unknown; - }, - ): any; + toJS( + opt?: ToJSOptions & { + [ignored: string]: unknown; + } + ): any; - toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions["onAnchor"]): any; + toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']): any; - toString(options?: ToStringOptions): string; + toString(options?: ToStringOptions): string; } declare class Directives { - static defaultYaml: Directives["yaml"]; - static defaultTags: Directives["tags"]; - yaml: { - version: "1.1" | "1.2" | "next"; - explicit?: boolean; - }; - tags: Record; + static defaultYaml: Directives['yaml']; + static defaultTags: Directives['tags']; + yaml: { + version: '1.1' | '1.2' | 'next'; + explicit?: boolean; + }; + tags: Record; - docStart: true | null; + docStart: true | null; - docEnd: boolean; + docEnd: boolean; - private atNextDocument?; - constructor(yaml?: Directives["yaml"], tags?: Directives["tags"]); - clone(): Directives; + private atNextDocument?; + constructor(yaml?: Directives['yaml'], tags?: Directives['tags']); + clone(): Directives; - atDocument(): Directives; + atDocument(): Directives; - add( - line: string, - onError: (offset: number, message: string, warning?: boolean) => void, - ): boolean; + add(line: string, onError: (offset: number, message: string, warning?: boolean) => void): boolean; - tagName(source: string, onError: (message: string) => void): string | null; + tagName(source: string, onError: (message: string) => void): string | null; - tagString(tag: string): string; - toString(doc?: Document): string; + tagString(tag: string): string; + toString(doc?: Document): string; } -declare function parseDocument< - Contents extends Node = ParsedNode, - Strict extends boolean = true, ->( - source: string, - options?: ParseOptions & DocumentOptions & SchemaOptions, -): Contents extends ParsedNode - ? Document.Parsed - : Document; -declare module "estree" { - interface TSTypeAnnotation { - type: "TSTypeAnnotation"; - typeAnnotation: - | TSStringKeyword - | TSTypeReference - | TSUnionType - | TSIndexedAccessType; - } - interface TSStringKeyword { - type: "TSStringKeyword"; - } - interface TSNullKeyword { - type: "TSNullKeyword"; - } - interface TSTypeReference { - type: "TSTypeReference"; - typeName: Identifier; - } - interface TSAsExpression extends BaseNode { - type: "TSAsExpression"; - expression: Expression; - typeAnnotation: TSTypeAnnotation["typeAnnotation"]; - } - interface TSModuleDeclaration extends BaseNode { - type: "TSModuleDeclaration"; - global: boolean; - declare: boolean; - id: Identifier; - body: TSModuleBlock; - } - interface TSModuleBlock extends BaseNode { - type: "TSModuleBlock"; - body: Array; - } - interface TSInterfaceDeclaration extends BaseNode { - type: "TSInterfaceDeclaration"; - id: Identifier; - body: TSInterfaceBody; - } - interface TSInterfaceBody extends BaseNode { - type: "TSInterfaceBody"; - body: TSPropertySignature[]; - } - interface TSPropertySignature extends BaseNode { - type: "TSPropertySignature"; - computed: boolean; - key: Identifier; - optional?: boolean; - typeAnnotation: TSTypeAnnotation; - } - interface TSProgram extends Omit { - body: Array< - Directive | Statement | ModuleDeclaration | TSModuleDeclaration - >; - } - interface TSUnionType { - type: "TSUnionType"; - types: Array; - } - interface TSImportType { - type: "TSImportType"; - argument: Literal; - qualifier: Identifier; - } - interface TSIndexedAccessType { - type: "TSIndexedAccessType"; - objectType: TSImportType; - indexType: TSLiteralType; - } - interface TSLiteralType { - type: "TSLiteralType"; - literal: Literal; - } - interface TSSatisfiesExpression extends BaseNode { - type: "TSSatisfiesExpression"; - expression: Expression; - typeAnnotation: TSTypeAnnotation["typeAnnotation"]; - } - interface BaseNodeWithoutComments { - type: string; - loc?: SourceLocation | null | undefined; - range?: [number, number] | undefined; - start?: number; - end?: number; - } - interface Identifier { - typeAnnotation?: TSTypeAnnotation; - } - interface ExpressionMap { - TSAsExpression: TSAsExpression; - TSSatisfiesExpression: TSSatisfiesExpression; - } - interface NodeMap { - TSModuleDeclaration: TSModuleDeclaration; - TSInterfaceDeclaration: TSInterfaceDeclaration; - } - interface ImportDeclaration { - importKind: "type" | "value"; - } +declare function parseDocument( + source: string, + options?: ParseOptions & DocumentOptions & SchemaOptions +): Contents extends ParsedNode ? Document.Parsed : Document; +declare module 'estree' { + interface TSTypeAnnotation { + type: 'TSTypeAnnotation'; + typeAnnotation: TSStringKeyword | TSTypeReference | TSUnionType | TSIndexedAccessType; + } + interface TSStringKeyword { + type: 'TSStringKeyword'; + } + interface TSNullKeyword { + type: 'TSNullKeyword'; + } + interface TSTypeReference { + type: 'TSTypeReference'; + typeName: Identifier; + } + interface TSAsExpression extends BaseNode { + type: 'TSAsExpression'; + expression: Expression; + typeAnnotation: TSTypeAnnotation['typeAnnotation']; + } + interface TSModuleDeclaration extends BaseNode { + type: 'TSModuleDeclaration'; + global: boolean; + declare: boolean; + id: Identifier; + body: TSModuleBlock; + } + interface TSModuleBlock extends BaseNode { + type: 'TSModuleBlock'; + body: Array; + } + interface TSInterfaceDeclaration extends BaseNode { + type: 'TSInterfaceDeclaration'; + id: Identifier; + body: TSInterfaceBody; + } + interface TSInterfaceBody extends BaseNode { + type: 'TSInterfaceBody'; + body: TSPropertySignature[]; + } + interface TSPropertySignature extends BaseNode { + type: 'TSPropertySignature'; + computed: boolean; + key: Identifier; + optional?: boolean; + typeAnnotation: TSTypeAnnotation; + } + interface TSProgram extends Omit { + body: Array; + } + interface TSUnionType { + type: 'TSUnionType'; + types: Array; + } + interface TSImportType { + type: 'TSImportType'; + argument: Literal; + qualifier: Identifier; + } + interface TSIndexedAccessType { + type: 'TSIndexedAccessType'; + objectType: TSImportType; + indexType: TSLiteralType; + } + interface TSLiteralType { + type: 'TSLiteralType'; + literal: Literal; + } + interface TSSatisfiesExpression extends BaseNode { + type: 'TSSatisfiesExpression'; + expression: Expression; + typeAnnotation: TSTypeAnnotation['typeAnnotation']; + } + interface BaseNodeWithoutComments { + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; + start?: number; + end?: number; + } + interface Identifier { + typeAnnotation?: TSTypeAnnotation; + } + interface ExpressionMap { + TSAsExpression: TSAsExpression; + TSSatisfiesExpression: TSSatisfiesExpression; + } + interface NodeMap { + TSModuleDeclaration: TSModuleDeclaration; + TSInterfaceDeclaration: TSInterfaceDeclaration; + } + interface ImportDeclaration { + importKind: 'type' | 'value'; + } } declare function parseYaml$1(content: string): ReturnType; type CommentType = { - type: "Line" | "Block"; - value: string; + type: 'Line' | 'Block'; + value: string; }; declare class Comments { - private original; - private leading; - private trailing; - constructor(); - add( - node: BaseNode$1, - comment: CommentType, - options?: { - position?: "leading" | "trailing"; - }, - ): void; - remove( - predicate: (comment: estree.Comment) => boolean | undefined | null, - ): void; + private original; + private leading; + private trailing; + constructor(); + add( + node: BaseNode$1, + comment: CommentType, + options?: { + position?: 'leading' | 'trailing'; + } + ): void; + remove(predicate: (comment: estree.Comment) => boolean | undefined | null): void; } type ParseBase = { - source: string; + source: string; - generateCode(): string; + generateCode(): string; }; declare function parseScript(source: string): { - ast: estree.Program; - comments: Comments; + ast: estree.Program; + comments: Comments; } & ParseBase; declare function parseCss(source: string): { - ast: Omit; + ast: Omit; } & ParseBase; declare function parseHtml(source: string): { - ast: SvelteAst.Fragment; + ast: SvelteAst.Fragment; } & ParseBase; declare function parseJson(source: string): { - data: any; + data: any; } & ParseBase; declare function parseYaml(source: string): { - data: ReturnType; + data: ReturnType; } & ParseBase; declare function parseSvelte(source: string): { - ast: SvelteAst.Root; + ast: SvelteAst.Root; } & ParseBase; declare function parseToml(source: string): { - data: TomlTable; + data: TomlTable; } & ParseBase; interface DedentOptions { - alignValues?: boolean; - escapeSpecialCharacters?: boolean; - trimWhitespace?: boolean; + alignValues?: boolean; + escapeSpecialCharacters?: boolean; + trimWhitespace?: boolean; } interface Dedent { - (literals: string): string; - (strings: TemplateStringsArray, ...values: unknown[]): string; - withOptions: CreateDedent; + (literals: string): string; + (strings: TemplateStringsArray, ...values: unknown[]): string; + withOptions: CreateDedent; } type CreateDedent = (options: DedentOptions) => Dedent; declare const dedent: Dedent; -declare module "zimmerframe" { - export function walk< - T extends { - type: string; - }, - U extends Record | null, - >(node: T, state: U, visitors: Visitors): T; - type BaseNode = { - type: string; - }; - type NodeOf = X extends { - type: T; - } - ? X - : never; - type SpecialisedVisitors = { - [K in T["type"]]?: Visitor, U, T>; - }; - export type Visitor = (node: T, context: Context) => V | void; - export type Visitors = T["type"] extends "_" - ? never - : SpecialisedVisitors & { - _?: Visitor; - }; - export interface Context { - next: (state?: U) => T | void; - path: T[]; - state: U; - stop: () => void; - visit: (node: T, state?: U) => T; - } - export {}; +declare module 'zimmerframe' { + export function walk< + T extends { + type: string; + }, + U extends Record | null + >(node: T, state: U, visitors: Visitors): T; + type BaseNode = { + type: string; + }; + type NodeOf = X extends { + type: T; + } + ? X + : never; + type SpecialisedVisitors = { + [K in T['type']]?: Visitor, U, T>; + }; + export type Visitor = (node: T, context: Context) => V | void; + export type Visitors = T['type'] extends '_' + ? never + : SpecialisedVisitors & { + _?: Visitor; + }; + export interface Context { + next: (state?: U) => T | void; + path: T[]; + state: U; + stop: () => void; + visit: (node: T, state?: U) => T; + } + export {}; } //# sourceMappingURL=index.d.ts.map declare namespace index_d_exports$1 { - export { addAtRule, addDeclaration, addImports, addRule }; + export { addAtRule, addDeclaration, addImports, addRule }; } declare function addRule( - node: SvelteAst.CSS.StyleSheetBase, - options: { - selector: string; - }, + node: SvelteAst.CSS.StyleSheetBase, + options: { + selector: string; + } ): SvelteAst.CSS.Rule; declare function addDeclaration( - node: SvelteAst.CSS.Rule, - options: { - property: string; - value: string; - }, + node: SvelteAst.CSS.Rule, + options: { + property: string; + value: string; + } ): void; declare function addImports( - node: SvelteAst.CSS.StyleSheetBase, - options: { - imports: string[]; - }, + node: SvelteAst.CSS.StyleSheetBase, + options: { + imports: string[]; + } ): void; declare function addAtRule( - node: SvelteAst.CSS.StyleSheetBase, - options: { - name: string; - params: string; - append: boolean; - }, + node: SvelteAst.CSS.StyleSheetBase, + options: { + name: string; + params: string; + append: boolean; + } ): SvelteAst.CSS.Atrule; declare namespace array_d_exports { - export { append, create$1 as create, prepend }; + export { append, create$1 as create, prepend }; } declare function create$1(): estree.ArrayExpression; declare function append( - node: estree.ArrayExpression, - element: string | estree.Expression | estree.SpreadElement, + node: estree.ArrayExpression, + element: string | estree.Expression | estree.SpreadElement ): void; declare function prepend( - node: estree.ArrayExpression, - element: string | estree.Expression | estree.SpreadElement, + node: estree.ArrayExpression, + element: string | estree.Expression | estree.SpreadElement ): void; declare namespace object_d_exports { - export { create, overrideProperties, property, propertyNode }; + export { create, overrideProperties, property, propertyNode }; } type ObjectPrimitiveValues = string | number | boolean | undefined | null; -type ObjectValues = - | ObjectPrimitiveValues - | Record - | ObjectValues[]; +type ObjectValues = ObjectPrimitiveValues | Record | ObjectValues[]; type ObjectMap = Record; declare function property( - node: estree.ObjectExpression, - options: { - name: string; - fallback: T; - }, + node: estree.ObjectExpression, + options: { + name: string; + fallback: T; + } ): T; declare function propertyNode( - node: estree.ObjectExpression, - options: { - name: string; - fallback: T; - }, + node: estree.ObjectExpression, + options: { + name: string; + fallback: T; + } ): estree.Property; declare function create(properties: ObjectMap): estree.ObjectExpression; declare function overrideProperties( - objectExpression: estree.ObjectExpression, - properties: ObjectMap, + objectExpression: estree.ObjectExpression, + properties: ObjectMap ): void; declare namespace common_d_exports { - export { - addJsDocComment, - addJsDocTypeComment, - appendFromString, - appendStatement, - areNodesEqual, - contains, - createBlockStatement, - createExpressionStatement, - createLiteral, - createSatisfies, - createSpread, - createTypeProperty, - hasTypeProperty, - parseExpression, - parseFromString, - parseStatement, - typeAnnotate, - }; + export { + addJsDocComment, + addJsDocTypeComment, + appendFromString, + appendStatement, + areNodesEqual, + contains, + createBlockStatement, + createExpressionStatement, + createLiteral, + createSatisfies, + createSpread, + createTypeProperty, + hasTypeProperty, + parseExpression, + parseFromString, + parseStatement, + typeAnnotate + }; } declare function addJsDocTypeComment( - node: estree.Node, - comments: Comments, - options: { - type: string; - }, + node: estree.Node, + comments: Comments, + options: { + type: string; + } ): void; declare function addJsDocComment( - node: estree.Node, - comments: Comments, - options: { - params: Record; - }, + node: estree.Node, + comments: Comments, + options: { + params: Record; + } ): void; declare function typeAnnotate( - node: estree.Expression, - options: { - type: string; - }, + node: estree.Expression, + options: { + type: string; + } ): estree.TSAsExpression; declare function createSatisfies( - node: estree.Expression, - options: { - type: string; - }, + node: estree.Expression, + options: { + type: string; + } ): estree.TSSatisfiesExpression; -declare function createSpread( - argument: estree.Expression, -): estree.SpreadElement; -declare function createLiteral( - value: string | number | boolean | null, -): estree.Literal; -declare function areNodesEqual( - node: estree.Node, - otherNode: estree.Node, -): boolean; +declare function createSpread(argument: estree.Expression): estree.SpreadElement; +declare function createLiteral(value: string | number | boolean | null): estree.Literal; +declare function areNodesEqual(node: estree.Node, otherNode: estree.Node): boolean; declare function createBlockStatement(): estree.BlockStatement; declare function createExpressionStatement(options: { - expression: estree.Expression; + expression: estree.Expression; }): estree.ExpressionStatement; declare function appendFromString( - node: estree.BlockStatement | estree.Program, - options: { - code: string; - comments?: Comments; - }, + node: estree.BlockStatement | estree.Program, + options: { + code: string; + comments?: Comments; + } ): void; declare function parseExpression(code: string): estree.Expression; declare function parseStatement(code: string): estree.Statement; declare function parseFromString(code: string): T; declare function appendStatement( - node: estree.BlockStatement | estree.Program, - options: { - statement: estree.Statement; - }, + node: estree.BlockStatement | estree.Program, + options: { + statement: estree.Statement; + } ): void; declare function contains(node: estree.Node, targetNode: estree.Node): boolean; declare function hasTypeProperty( - node: estree.TSInterfaceDeclaration["body"]["body"][number], - options: { - name: string; - }, + node: estree.TSInterfaceDeclaration['body']['body'][number], + options: { + name: string; + } ): boolean; declare function createTypeProperty( - name: string, - value: string, - optional?: boolean, -): estree.TSInterfaceBody["body"][number]; + name: string, + value: string, + optional?: boolean +): estree.TSInterfaceBody['body'][number]; declare namespace function_d_exports { - export { createArrow, createCall, getArgument }; + export { createArrow, createCall, getArgument }; } declare function createCall(options: { - name: string; - args: string[]; - useIdentifiers?: boolean; + name: string; + args: string[]; + useIdentifiers?: boolean; }): estree.CallExpression; declare function createArrow(options: { - body: estree.Expression | estree.BlockStatement; - async: boolean; + body: estree.Expression | estree.BlockStatement; + async: boolean; }): estree.ArrowFunctionExpression; declare function getArgument( - node: estree.CallExpression, - options: { - index: number; - fallback: T; - }, + node: estree.CallExpression, + options: { + index: number; + fallback: T; + } ): T; declare namespace imports_d_exports { - export { - addDefault, - addEmpty, - addNamed, - addNamespace$1 as addNamespace, - find, - remove, - }; + export { addDefault, addEmpty, addNamed, addNamespace$1 as addNamespace, find, remove }; } declare function addEmpty( - node: estree.Program, - options: { - from: string; - }, + node: estree.Program, + options: { + from: string; + } ): void; declare function addNamespace$1( - node: estree.Program, - options: { - from: string; - as: string; - }, + node: estree.Program, + options: { + from: string; + as: string; + } ): void; declare function addDefault( - node: estree.Program, - options: { - from: string; - as: string; - }, + node: estree.Program, + options: { + from: string; + as: string; + } ): void; declare function addNamed( - node: estree.Program, - options: { - imports: Record | string[]; - from: string; - isType?: boolean; - }, + node: estree.Program, + options: { + imports: Record | string[]; + from: string; + isType?: boolean; + } ): void; declare function find( - ast: estree.Program, - options: { - name: string; - from: string; - }, + ast: estree.Program, + options: { + name: string; + from: string; + } ): - | { - statement: estree.ImportDeclaration; - alias: string; - } - | { - statement: undefined; - alias: undefined; - }; + | { + statement: estree.ImportDeclaration; + alias: string; + } + | { + statement: undefined; + alias: undefined; + }; declare function remove( - ast: estree.Program, - options: { - name: string; - from: string; - statement?: estree.ImportDeclaration; - }, + ast: estree.Program, + options: { + name: string; + from: string; + statement?: estree.ImportDeclaration; + } ): void; declare namespace variables_d_exports { - export { createIdentifier, declaration, typeAnnotateDeclarator }; + export { createIdentifier, declaration, typeAnnotateDeclarator }; } declare function declaration( - node: estree.Program | estree.Declaration, - options: { - kind: "const" | "let" | "var"; - name: string; - value: estree.Expression; - }, + node: estree.Program | estree.Declaration, + options: { + kind: 'const' | 'let' | 'var'; + name: string; + value: estree.Expression; + } ): estree.VariableDeclaration; declare function createIdentifier(name: string): estree.Identifier; declare function typeAnnotateDeclarator( - node: estree.VariableDeclarator, - options: { - typeName: string; - }, + node: estree.VariableDeclarator, + options: { + typeName: string; + } ): estree.VariableDeclarator; declare namespace exports_d_exports { - export { ExportDefaultResult, addNamespace, createDefault, createNamed }; + export { ExportDefaultResult, addNamespace, createDefault, createNamed }; } type ExportDefaultResult = { - astNode: estree.ExportDefaultDeclaration; - value: T; - isFallback: boolean; + astNode: estree.ExportDefaultDeclaration; + value: T; + isFallback: boolean; }; declare function createDefault( - node: estree.Program, - options: { - fallback: T; - }, + node: estree.Program, + options: { + fallback: T; + } ): ExportDefaultResult; declare function createNamed( - node: estree.Program, - options: { - name: string; - fallback: estree.VariableDeclaration; - }, + node: estree.Program, + options: { + name: string; + fallback: estree.VariableDeclaration; + } ): estree.ExportNamedDeclaration; declare function addNamespace( - node: estree.Program, - options: { - from: string; - as?: string; - }, + node: estree.Program, + options: { + from: string; + as?: string; + } ): void; declare namespace kit_d_exports { - export { addGlobalAppInterface, addHooksHandle }; + export { addGlobalAppInterface, addHooksHandle }; } declare function addGlobalAppInterface( - node: estree.TSProgram, - options: { - name: "Error" | "Locals" | "PageData" | "PageState" | "Platform"; - }, + node: estree.TSProgram, + options: { + name: 'Error' | 'Locals' | 'PageData' | 'PageState' | 'Platform'; + } ): estree.TSInterfaceDeclaration; declare function addHooksHandle( - node: estree.Program, - options: { - language: "ts" | "js"; - newHandleName: string; - handleContent: string; - comments: Comments; - }, + node: estree.Program, + options: { + language: 'ts' | 'js'; + newHandleName: string; + handleContent: string; + comments: Comments; + } ): void; declare namespace vite_d_exports { - export { addPlugin, configProperty, getConfig }; + export { addPlugin, configProperty, getConfig }; } declare const addPlugin: ( - ast: estree.Program, - options: { - code: string; - mode?: "append" | "prepend"; - }, + ast: estree.Program, + options: { + code: string; + mode?: 'append' | 'prepend'; + } ) => void; -declare function configProperty< - T extends estree.Expression | estree.Identifier, ->( - ast: estree.Program, - config: estree.ObjectExpression, - options: { - name: string; - fallback: T; - }, +declare function configProperty( + ast: estree.Program, + config: estree.ObjectExpression, + options: { + name: string; + fallback: T; + } ): T; declare const getConfig: (ast: estree.Program) => estree.ObjectExpression; declare namespace index_d_exports$3 { - export { - array_d_exports as array, - common_d_exports as common, - exports_d_exports as exports, - function_d_exports as functions, - imports_d_exports as imports, - kit_d_exports as kit, - object_d_exports as object, - variables_d_exports as variables, - vite_d_exports as vite, - }; + export { + array_d_exports as array, + common_d_exports as common, + exports_d_exports as exports, + function_d_exports as functions, + imports_d_exports as imports, + kit_d_exports as kit, + object_d_exports as object, + variables_d_exports as variables, + vite_d_exports as vite + }; } declare namespace index_d_exports$2 { - export { - addAttribute, - addFromRawHtml, - appendElement, - createElement, - insertElement, - }; + export { addAttribute, addFromRawHtml, appendElement, createElement, insertElement }; } declare function createElement( - tagName: string, - attributes?: Record, + tagName: string, + attributes?: Record ): SvelteAst.RegularElement; -declare function addAttribute( - element: SvelteAst.RegularElement, - name: string, - value: string, -): void; +declare function addAttribute(element: SvelteAst.RegularElement, name: string, value: string): void; declare function insertElement( - fragment: SvelteAst.Fragment, - elementToInsert: SvelteAst.Fragment["nodes"][0], + fragment: SvelteAst.Fragment, + elementToInsert: SvelteAst.Fragment['nodes'][0] ): void; declare function appendElement( - fragment: SvelteAst.Fragment, - elementToAppend: SvelteAst.Fragment["nodes"][0], -): void; -declare function addFromRawHtml( - fragment: SvelteAst.Fragment, - html: string, + fragment: SvelteAst.Fragment, + elementToAppend: SvelteAst.Fragment['nodes'][0] ): void; +declare function addFromRawHtml(fragment: SvelteAst.Fragment, html: string): void; declare namespace text_d_exports { - export { upsert }; + export { upsert }; } type CommentEntry = { - text: string; - mode: "append" | "prepend"; + text: string; + mode: 'append' | 'prepend'; }; type CommentOption = string | Array; declare function upsert( - content: string, - key: string, - options?: { - value?: string; - comment?: CommentOption; - separator?: boolean; - }, + content: string, + key: string, + options?: { + value?: string; + comment?: CommentOption; + separator?: boolean; + } ): string; declare namespace json_d_exports { - export { arrayUpsert, packageScriptsUpsert }; + export { arrayUpsert, packageScriptsUpsert }; } declare function arrayUpsert( - data: any, - key: string, - value: any, - options?: { - mode?: "append" | "prepend"; - }, + data: any, + key: string, + value: any, + options?: { + mode?: 'append' | 'prepend'; + } ): void; declare function packageScriptsUpsert( - data: any, - key: string, - value: string, - options?: { - mode?: "append" | "prepend"; - }, + data: any, + key: string, + value: string, + options?: { + mode?: 'append' | 'prepend'; + } ): void; declare namespace index_d_exports$4 { - export { RootWithInstance, addFragment, addSlot, ensureScript }; + export { RootWithInstance, addFragment, addSlot, ensureScript }; } type RootWithInstance = SvelteAst.Root & { - instance: SvelteAst.Script; + instance: SvelteAst.Script; }; declare function ensureScript( - ast: SvelteAst.Root, - options?: { - language?: "ts" | "js"; - }, + ast: SvelteAst.Root, + options?: { + language?: 'ts' | 'js'; + } ): asserts ast is RootWithInstance; declare function addSlot( - ast: SvelteAst.Root, - options: { - svelteVersion: string; - language?: "ts" | "js"; - }, + ast: SvelteAst.Root, + options: { + svelteVersion: string; + language?: 'ts' | 'js'; + } ): void; declare function addFragment( - ast: SvelteAst.Root, - content: string, - options?: { - mode?: "append" | "prepend"; - }, + ast: SvelteAst.Root, + content: string, + options?: { + mode?: 'append' | 'prepend'; + } ): void; type TransformFn = (content: string) => string; type TransformOptions = { - onError?: (error: unknown) => void; + onError?: (error: unknown) => void; }; declare const transforms: { - script( - cb: (file: { - ast: estree.Program; - comments: Comments; - content: string; - js: typeof index_d_exports$3; - }) => void | false, - options?: TransformOptions, - ): (content: string) => string; - - svelte( - cb: (file: { - ast: SvelteAst.Root; - content: string; - svelte: typeof index_d_exports$4; - js: typeof index_d_exports$3; - }) => void | false, - options?: TransformOptions, - ): (content: string) => string; - - svelteScript( - scriptOptions: { - language: "ts" | "js"; - }, - cb: (file: { - ast: RootWithInstance; - content: string; - svelte: typeof index_d_exports$4; - js: typeof index_d_exports$3; - }) => void | false, - options?: TransformOptions, - ): TransformFn; - - css( - cb: (file: { - ast: Omit; - content: string; - css: typeof index_d_exports$1; - }) => void | false, - options?: TransformOptions, - ): TransformFn; - - json( - cb: (file: { - data: T; - content: string; - json: typeof json_d_exports; - }) => void | false, - options?: TransformOptions, - ): TransformFn; - - yaml( - cb: (file: { - data: ReturnType["data"]; - content: string; - }) => void | false, - options?: TransformOptions, - ): TransformFn; - - toml( - cb: (file: { data: TomlTable; content: string }) => void | false, - options?: TransformOptions, - ): TransformFn; - - html( - cb: (file: { - ast: SvelteAst.Fragment; - content: string; - html: typeof index_d_exports$2; - }) => void | false, - options?: TransformOptions, - ): TransformFn; - - text( - cb: (file: { - content: string; - text: typeof text_d_exports; - }) => string | false, - ): TransformFn; + script( + cb: (file: { + ast: estree.Program; + comments: Comments; + content: string; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions + ): (content: string) => string; + + svelte( + cb: (file: { + ast: SvelteAst.Root; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions + ): (content: string) => string; + + svelteScript( + scriptOptions: { + language: 'ts' | 'js'; + }, + cb: (file: { + ast: RootWithInstance; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions + ): TransformFn; + + css( + cb: (file: { + ast: Omit; + content: string; + css: typeof index_d_exports$1; + }) => void | false, + options?: TransformOptions + ): TransformFn; + + json( + cb: (file: { data: T; content: string; json: typeof json_d_exports }) => void | false, + options?: TransformOptions + ): TransformFn; + + yaml( + cb: (file: { data: ReturnType['data']; content: string }) => void | false, + options?: TransformOptions + ): TransformFn; + + toml( + cb: (file: { data: TomlTable; content: string }) => void | false, + options?: TransformOptions + ): TransformFn; + + html( + cb: (file: { + ast: SvelteAst.Fragment; + content: string; + html: typeof index_d_exports$2; + }) => void | false, + options?: TransformOptions + ): TransformFn; + + text(cb: (file: { content: string; text: typeof text_d_exports }) => string | false): TransformFn; }; type Version = { - major?: number; - minor?: number; - patch?: number; + major?: number; + minor?: number; + patch?: number; }; declare function splitVersion(str: string): Version; declare function isVersionUnsupportedBelow( - versionStr: string, - belowStr: string, + versionStr: string, + belowStr: string ): boolean | undefined; type Printer = (content: string, alt?: string) => string; declare function createPrinter(...conditions: boolean[]): Printer[]; -declare function sanitizeName( - name: string, - style: "package" | "wrangler", -): string; +declare function sanitizeName(name: string, style: 'package' | 'wrangler'): string; declare const downloadJson: (url: string) => Promise; type Package = { - name: string; - version: string; - dependencies?: Record; - devDependencies?: Record; - bugs?: string; - repository?: { - type: string; - url: string; - }; - keywords?: string[]; - workspaces?: string[]; + name: string; + version: string; + dependencies?: Record; + devDependencies?: Record; + bugs?: string; + repository?: { + type: string; + url: string; + }; + keywords?: string[]; + workspaces?: string[]; }; declare function getPackageJson(cwd: string): { - source: string; - data: Package; - generateCode: () => string; + source: string; + data: Package; + generateCode: () => string; }; declare function readFile(cwd: string, filePath: string): string; declare function fileExists(cwd: string, filePath: string): boolean; -declare function writeFile( - cwd: string, - filePath: string, - content: string, -): void; +declare function writeFile(cwd: string, filePath: string, content: string): void; declare function installPackages( - dependencies: Array<{ - pkg: string; - version: string; - dev: boolean; - }>, - cwd: string, + dependencies: Array<{ + pkg: string; + version: string; + dev: boolean; + }>, + cwd: string ): string; declare const commonFilePaths: { - readonly packageJson: "package.json"; - readonly svelteConfig: "svelte.config.js"; - readonly svelteConfigTS: "svelte.config.ts"; - readonly jsconfig: "jsconfig.json"; - readonly tsconfig: "tsconfig.json"; - readonly viteConfig: "vite.config.js"; - readonly viteConfigTS: "vite.config.ts"; + readonly packageJson: 'package.json'; + readonly svelteConfig: 'svelte.config.js'; + readonly svelteConfigTS: 'svelte.config.ts'; + readonly jsconfig: 'jsconfig.json'; + readonly tsconfig: 'tsconfig.json'; + readonly viteConfig: 'vite.config.js'; + readonly viteConfigTS: 'vite.config.ts'; }; type ColorInput = string | string[]; declare const color: { - addon: (str: ColorInput) => string; - command: (str: ColorInput) => string; - env: (str: ColorInput) => string; - path: (str: ColorInput) => string; - route: (str: ColorInput) => string; - website: (str: ColorInput) => string; - optional: (str: ColorInput) => string; - dim: (str: ColorInput) => string; - success: (str: ColorInput) => string; - warning: (str: ColorInput) => string; - error: (str: ColorInput) => string; - hidden: (str: ColorInput) => string; + addon: (str: ColorInput) => string; + command: (str: ColorInput) => string; + env: (str: ColorInput) => string; + path: (str: ColorInput) => string; + route: (str: ColorInput) => string; + website: (str: ColorInput) => string; + optional: (str: ColorInput) => string; + dim: (str: ColorInput) => string; + success: (str: ColorInput) => string; + warning: (str: ColorInput) => string; + error: (str: ColorInput) => string; + hidden: (str: ColorInput) => string; }; -declare function resolveCommandArray( - agent: Agent, - command: Command, - args: string[], -): string[]; +declare function resolveCommandArray(agent: Agent, command: Command, args: string[]): string[]; declare const parse: { - css: typeof parseCss; - html: typeof parseHtml; - json: typeof parseJson; - script: typeof parseScript; - svelte: typeof parseSvelte; - toml: typeof parseToml; - yaml: typeof parseYaml; + css: typeof parseCss; + html: typeof parseHtml; + json: typeof parseJson; + script: typeof parseScript; + svelte: typeof parseSvelte; + toml: typeof parseToml; + yaml: typeof parseYaml; }; export { - AGENTS, - type AgentName, - type estree as AstTypes, - COMMANDS, - type Comments, - type Package, - type SvelteAst, - type TransformFn, - index_d_exports as Walker, - color, - commonFilePaths, - constructCommand, - createPrinter, - index_d_exports$1 as css, - dedent, - detect, - downloadJson, - fileExists, - getPackageJson, - index_d_exports$2 as html, - installPackages, - isVersionUnsupportedBelow, - index_d_exports$3 as js, - json_d_exports as json, - parse, - readFile, - resolveCommand, - resolveCommandArray, - sanitizeName, - splitVersion, - index_d_exports$4 as svelte, - text_d_exports as text, - transforms, - writeFile, + AGENTS, + type AgentName, + type estree as AstTypes, + COMMANDS, + type Comments, + type Package, + type SvelteAst, + type TransformFn, + index_d_exports as Walker, + color, + commonFilePaths, + constructCommand, + createPrinter, + index_d_exports$1 as css, + dedent, + detect, + downloadJson, + fileExists, + getPackageJson, + index_d_exports$2 as html, + installPackages, + isVersionUnsupportedBelow, + index_d_exports$3 as js, + json_d_exports as json, + parse, + readFile, + resolveCommand, + resolveCommandArray, + sanitizeName, + splitVersion, + index_d_exports$4 as svelte, + text_d_exports as text, + transforms, + writeFile }; ``` diff --git a/packages/sv/api-surface-testing.md b/packages/sv/api-surface-testing.md index c5f6824c2..3b545bd2b 100644 --- a/packages/sv/api-surface-testing.md +++ b/packages/sv/api-surface-testing.md @@ -4,128 +4,118 @@ ```ts declare function addPnpmBuildDependencies( - cwd: string, - packageManager: AgentName | null | undefined, - allowedPackages: string[], + cwd: string, + packageManager: AgentName | null | undefined, + allowedPackages: string[] ): Promise; -type ProjectVariant = "kit-js" | "kit-ts" | "vite-js" | "vite-ts"; +type ProjectVariant = 'kit-js' | 'kit-ts' | 'vite-js' | 'vite-ts'; declare const variants: ProjectVariant[]; type CreateProject = (options: { - testId: string; - variant: ProjectVariant; - clean?: boolean; + testId: string; + variant: ProjectVariant; + clean?: boolean; }) => string; type SetupOptions = { - cwd: string; - variants: readonly ProjectVariant[]; - clean?: boolean; + cwd: string; + variants: readonly ProjectVariant[]; + clean?: boolean; }; declare function setup({ cwd, clean, variants }: SetupOptions): { - templatesDir: string; + templatesDir: string; }; type CreateOptions = { - cwd: string; - testName: string; - templatesDir: string; + cwd: string; + testName: string; + templatesDir: string; }; -declare function createProject({ - cwd, - testName, - templatesDir, -}: CreateOptions): CreateProject; +declare function createProject({ cwd, testName, templatesDir }: CreateOptions): CreateProject; type PreviewOptions = { - cwd: string; - command?: string; + cwd: string; + command?: string; }; declare function startPreview({ cwd, command }: PreviewOptions): Promise<{ - url: string; - close: () => Promise; + url: string; + close: () => Promise; }>; -declare module "vitest" { - interface ProvidedContext { - testDir: string; - templatesDir: string; - variants: ProjectVariant[]; - } +declare module 'vitest' { + interface ProvidedContext { + testDir: string; + templatesDir: string; + variants: ProjectVariant[]; + } } declare function setupGlobal({ - TEST_DIR, - pre, - post, + TEST_DIR, + pre, + post }: { - TEST_DIR: string; - pre?: () => Promise; - post?: () => Promise; + TEST_DIR: string; + pre?: () => Promise; + post?: () => Promise; }): ({ provide }: TestProject) => Promise<() => Promise>; type Fixtures = { - page: Page; - cwd(addonTestCase: AddonTestCase): string; + page: Page; + cwd(addonTestCase: AddonTestCase): string; }; type AddonTestCase = { - variant: ProjectVariant; - kind: { - type: string; - options: OptionMap; - }; + variant: ProjectVariant; + kind: { + type: string; + options: OptionMap; + }; }; type SetupTestOptions = { - kinds: Array["kind"]>; - filter?: (addonTestCase: AddonTestCase) => boolean; - browser?: boolean; - preAdd?: (o: { - addonTestCase: AddonTestCase; - cwd: string; - }) => Promise | void; + kinds: Array['kind']>; + filter?: (addonTestCase: AddonTestCase) => boolean; + browser?: boolean; + preAdd?: (o: { addonTestCase: AddonTestCase; cwd: string }) => Promise | void; }; type PrepareServerOptions = { - cwd: string; - page: Page; - buildCommand?: string; - previewCommand?: string; + cwd: string; + page: Page; + buildCommand?: string; + previewCommand?: string; }; type PrepareServerReturn = { - url: string; - close: () => Promise; + url: string; + close: () => Promise; }; declare function prepareServer({ - cwd, - page, - buildCommand, - previewCommand, + cwd, + page, + buildCommand, + previewCommand }: PrepareServerOptions): Promise; -type PlaywrightContext = Pick; -type VitestContext = Pick< - typeof vitest, - "inject" | "test" | "beforeAll" | "beforeEach" ->; +type PlaywrightContext = Pick; +type VitestContext = Pick; declare function createSetupTest( - vitest: VitestContext, - playwright?: PlaywrightContext, + vitest: VitestContext, + playwright?: PlaywrightContext ): ( - addons: Addons, - options?: SetupTestOptions, + addons: Addons, + options?: SetupTestOptions ) => { - test: vitest.TestAPI; - testCases: Array>; - prepareServer: typeof prepareServer; + test: vitest.TestAPI; + testCases: Array>; + prepareServer: typeof prepareServer; }; export { - AddonTestCase, - CreateProject, - Fixtures, - PlaywrightContext, - PrepareServerOptions, - PrepareServerReturn, - ProjectVariant, - SetupTestOptions, - VitestContext, - addPnpmBuildDependencies, - createProject, - createSetupTest, - prepareServer, - setup, - setupGlobal, - startPreview, - variants, + AddonTestCase, + CreateProject, + Fixtures, + PlaywrightContext, + PrepareServerOptions, + PrepareServerReturn, + ProjectVariant, + SetupTestOptions, + VitestContext, + addPnpmBuildDependencies, + createProject, + createSetupTest, + prepareServer, + setup, + setupGlobal, + startPreview, + variants }; ``` diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md index 0a10015f7..3efb6b89c 100644 --- a/packages/sv/api-surface.md +++ b/packages/sv/api-surface.md @@ -5,71 +5,65 @@ ```ts type TemplateType = (typeof templateTypes)[number]; type LanguageType = (typeof languageTypes)[number]; -declare const templateTypes: readonly [ - "minimal", - "demo", - "library", - "addon", - "svelte", -]; -declare const languageTypes: readonly ["typescript", "checkjs", "none"]; +declare const templateTypes: readonly ['minimal', 'demo', 'library', 'addon', 'svelte']; +declare const languageTypes: readonly ['typescript', 'checkjs', 'none']; type Options = { - name: string; - template: TemplateType; - types: LanguageType; + name: string; + template: TemplateType; + types: LanguageType; }; declare function create(cwd: string, options: Options): void; type FileEditor = Workspace & { - content: string; + content: string; }; type FileType = { - name: (options: Workspace) => string; - condition?: ConditionDefinition; - content: (editor: FileEditor) => string; + name: (options: Workspace) => string; + condition?: ConditionDefinition; + content: (editor: FileEditor) => string; }; export { - Addon, - AddonDefinition, - AddonInput, - type AddonMap, - AddonReference, - AddonResult, - AddonSource, - BaseQuestion, - BooleanQuestion, - ConditionDefinition, - ConfiguredAddon, - FileEditor, - FileType, - type InstallOptions, - type LanguageType, - LoadedAddon, - MultiSelectQuestion, - NumberQuestion, - OptionBuilder, - OptionDefinition, - type OptionMap, - OptionValues, - PackageDefinition, - PreparedAddon, - Question, - Scripts, - SelectQuestion, - SetupResult, - StringQuestion, - SvApi, - type TemplateType, - TestDefinition, - Tests, - Verification, - Workspace, - WorkspaceOptions, - add, - create, - createWorkspace, - defineAddon, - defineAddonOptions, - getErrorHint, - officialAddons, + Addon, + AddonDefinition, + AddonInput, + type AddonMap, + AddonReference, + AddonResult, + AddonSource, + BaseQuestion, + BooleanQuestion, + ConditionDefinition, + ConfiguredAddon, + FileEditor, + FileType, + type InstallOptions, + type LanguageType, + LoadedAddon, + MultiSelectQuestion, + NumberQuestion, + OptionBuilder, + OptionDefinition, + type OptionMap, + OptionValues, + PackageDefinition, + PreparedAddon, + Question, + Scripts, + SelectQuestion, + SetupResult, + StringQuestion, + SvApi, + type TemplateType, + TestDefinition, + Tests, + Verification, + Workspace, + WorkspaceOptions, + add, + create, + createWorkspace, + defineAddon, + defineAddonOptions, + getErrorHint, + officialAddons }; ``` diff --git a/scripts/generate-api-surface.js b/scripts/generate-api-surface.js index bc7a5deaf..811c44d7e 100644 --- a/scripts/generate-api-surface.js +++ b/scripts/generate-api-surface.js @@ -14,6 +14,7 @@ import fs from 'node:fs'; import path from 'node:path'; +import process from 'node:process'; import { fileURLToPath } from 'node:url'; import * as prettier from 'prettier'; From db5a2dfc3248b1c2da7dc2157ee99e49f2a08bcd Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 23:58:34 +0200 Subject: [PATCH 10/31] chore: regenerate api-surface snapshots on PR #1037 base Made-with: Cursor --- packages/sv-utils/api-surface.md | 6 ++++++ packages/sv/api-surface-testing.md | 13 +------------ 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index 6c4e01448..7f8a9a8ba 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -1532,6 +1532,11 @@ declare const transforms: { text(cb: (file: { content: string; text: typeof text_d_exports }) => string | false): TransformFn; }; +declare namespace pnpm_d_exports { + export { onlyBuiltDependencies }; +} + +declare function onlyBuiltDependencies(...packages: string[]): TransformFn; type Version = { major?: number; minor?: number; @@ -1638,6 +1643,7 @@ export { index_d_exports$3 as js, json_d_exports as json, parse, + pnpm_d_exports as pnpm, readFile, resolveCommand, resolveCommandArray, diff --git a/packages/sv/api-surface-testing.md b/packages/sv/api-surface-testing.md index 3b545bd2b..8d87dae41 100644 --- a/packages/sv/api-surface-testing.md +++ b/packages/sv/api-surface-testing.md @@ -3,11 +3,6 @@ ```ts -declare function addPnpmBuildDependencies( - cwd: string, - packageManager: AgentName | null | undefined, - allowedPackages: string[] -): Promise; type ProjectVariant = 'kit-js' | 'kit-ts' | 'vite-js' | 'vite-ts'; declare const variants: ProjectVariant[]; type CreateProject = (options: { @@ -86,12 +81,8 @@ declare function prepareServer({ buildCommand, previewCommand }: PrepareServerOptions): Promise; -type PlaywrightContext = Pick; type VitestContext = Pick; -declare function createSetupTest( - vitest: VitestContext, - playwright?: PlaywrightContext -): ( +declare function createSetupTest(vitest: VitestContext): ( addons: Addons, options?: SetupTestOptions ) => { @@ -103,13 +94,11 @@ export { AddonTestCase, CreateProject, Fixtures, - PlaywrightContext, PrepareServerOptions, PrepareServerReturn, ProjectVariant, SetupTestOptions, VitestContext, - addPnpmBuildDependencies, createProject, createSetupTest, prepareServer, From bceae430af1b323d2edaa9e5ab093eac7c410902 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 12:38:18 +0200 Subject: [PATCH 11/31] align Made-with: Cursor --- packages/sv-utils/api-surface.md | 2495 +++++++++++--------- packages/sv-utils/src/files.ts | 3 + packages/sv-utils/src/index.ts | 4 +- packages/sv/api-surface-testing.md | 157 +- packages/sv/api-surface.md | 109 +- packages/sv/src/cli/create.ts | 3 +- packages/sv/src/core/engine.ts | 4 +- packages/sv/src/core/processors.ts | 2 + packages/sv/src/core/workspace.ts | 5 + packages/sv/src/create/index.ts | 23 +- packages/sv/src/create/tests/check.ts | 2 +- packages/sv/src/create/tests/playground.ts | 6 +- packages/sv/src/index.ts | 40 +- packages/sv/src/testing.ts | 11 +- 14 files changed, 1553 insertions(+), 1311 deletions(-) diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index 7f8a9a8ba..92f5bbc85 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -3,66 +3,76 @@ ```ts -type Agent = 'npm' | 'yarn' | 'yarn@berry' | 'pnpm' | 'pnpm@6' | 'bun' | 'deno'; -type AgentName = 'npm' | 'yarn' | 'pnpm' | 'bun' | 'deno'; -type AgentCommandValue = (string | number)[] | ((args: string[]) => string[]) | null; +type Agent = "npm" | "yarn" | "yarn@berry" | "pnpm" | "pnpm@6" | "bun" | "deno"; +type AgentName = "npm" | "yarn" | "pnpm" | "bun" | "deno"; +type AgentCommandValue = + | (string | number)[] + | ((args: string[]) => string[]) + | null; interface AgentCommands { - agent: AgentCommandValue; - run: AgentCommandValue; - install: AgentCommandValue; - frozen: AgentCommandValue; - global: AgentCommandValue; - add: AgentCommandValue; - upgrade: AgentCommandValue; - 'upgrade-interactive': AgentCommandValue; - dedupe: AgentCommandValue; - execute: AgentCommandValue; - 'execute-local': AgentCommandValue; - uninstall: AgentCommandValue; - global_uninstall: AgentCommandValue; + agent: AgentCommandValue; + run: AgentCommandValue; + install: AgentCommandValue; + frozen: AgentCommandValue; + global: AgentCommandValue; + add: AgentCommandValue; + upgrade: AgentCommandValue; + "upgrade-interactive": AgentCommandValue; + dedupe: AgentCommandValue; + execute: AgentCommandValue; + "execute-local": AgentCommandValue; + uninstall: AgentCommandValue; + global_uninstall: AgentCommandValue; } type Command = keyof AgentCommands; interface ResolvedCommand { - command: string; + command: string; - args: string[]; + args: string[]; } -type DetectStrategy = 'lockfile' | 'packageManager-field' | 'devEngines-field' | 'install-metadata'; +type DetectStrategy = + | "lockfile" + | "packageManager-field" + | "devEngines-field" + | "install-metadata"; interface DetectOptions { - cwd?: string; + cwd?: string; - strategies?: DetectStrategy[]; + strategies?: DetectStrategy[]; - onUnknown?: (packageManager: string) => DetectResult | null | undefined; + onUnknown?: (packageManager: string) => DetectResult | null | undefined; - stopDir?: string | ((currentDir: string) => boolean); + stopDir?: string | ((currentDir: string) => boolean); - packageJsonParser?: (content: string, filepath: string) => any | Promise; + packageJsonParser?: (content: string, filepath: string) => any | Promise; } interface DetectResult { - name: AgentName; + name: AgentName; - agent: Agent; + agent: Agent; - version?: string; + version?: string; } declare const COMMANDS: { - npm: AgentCommands; - yarn: AgentCommands; - 'yarn@berry': AgentCommands; - pnpm: AgentCommands; - 'pnpm@6': AgentCommands; - bun: AgentCommands; - deno: AgentCommands; + npm: AgentCommands; + yarn: AgentCommands; + "yarn@berry": AgentCommands; + pnpm: AgentCommands; + "pnpm@6": AgentCommands; + bun: AgentCommands; + deno: AgentCommands; }; declare function resolveCommand( - agent: Agent, - command: Command, - args: string[] + agent: Agent, + command: Command, + args: string[], ): ResolvedCommand | null; -declare function constructCommand(value: AgentCommandValue, args: string[]): ResolvedCommand | null; +declare function constructCommand( + value: AgentCommandValue, + args: string[], +): ResolvedCommand | null; declare const AGENTS: Agent[]; declare function detect(options?: DetectOptions): Promise; @@ -94,1564 +104,1711 @@ declare function detect(options?: DetectOptions): Promise; * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare class TomlDate extends Date { - #private; - constructor(date: string | Date); - isDateTime(): boolean; - isLocal(): boolean; - isDate(): boolean; - isTime(): boolean; - isValid(): boolean; - toISOString(): string; - static wrapAsOffsetDateTime(jsDate: Date, offset?: string): TomlDate; - static wrapAsLocalDateTime(jsDate: Date): TomlDate; - static wrapAsLocalDate(jsDate: Date): TomlDate; - static wrapAsLocalTime(jsDate: Date): TomlDate; + #private; + constructor(date: string | Date); + isDateTime(): boolean; + isLocal(): boolean; + isDate(): boolean; + isTime(): boolean; + isValid(): boolean; + toISOString(): string; + static wrapAsOffsetDateTime(jsDate: Date, offset?: string): TomlDate; + static wrapAsLocalDateTime(jsDate: Date): TomlDate; + static wrapAsLocalDate(jsDate: Date): TomlDate; + static wrapAsLocalTime(jsDate: Date): TomlDate; } type TomlPrimitive = string | number | bigint | boolean | TomlDate; type TomlTable = { - [key: string]: TomlValue; + [key: string]: TomlValue; }; type TomlValue = TomlPrimitive | TomlValue[] | TomlTable; declare class LineCounter { - lineStarts: number[]; + lineStarts: number[]; - addNewLine: (offset: number) => number; + addNewLine: (offset: number) => number; - linePos: (offset: number) => { - line: number; - col: number; - }; + linePos: (offset: number) => { + line: number; + col: number; + }; } type ErrorCode = - | 'ALIAS_PROPS' - | 'BAD_ALIAS' - | 'BAD_DIRECTIVE' - | 'BAD_DQ_ESCAPE' - | 'BAD_INDENT' - | 'BAD_PROP_ORDER' - | 'BAD_SCALAR_START' - | 'BLOCK_AS_IMPLICIT_KEY' - | 'BLOCK_IN_FLOW' - | 'DUPLICATE_KEY' - | 'IMPOSSIBLE' - | 'KEY_OVER_1024_CHARS' - | 'MISSING_CHAR' - | 'MULTILINE_IMPLICIT_KEY' - | 'MULTIPLE_ANCHORS' - | 'MULTIPLE_DOCS' - | 'MULTIPLE_TAGS' - | 'NON_STRING_KEY' - | 'TAB_AS_INDENT' - | 'TAG_RESOLVE_FAILED' - | 'UNEXPECTED_TOKEN' - | 'BAD_COLLECTION_TYPE'; + | "ALIAS_PROPS" + | "BAD_ALIAS" + | "BAD_DIRECTIVE" + | "BAD_DQ_ESCAPE" + | "BAD_INDENT" + | "BAD_PROP_ORDER" + | "BAD_SCALAR_START" + | "BLOCK_AS_IMPLICIT_KEY" + | "BLOCK_IN_FLOW" + | "DUPLICATE_KEY" + | "IMPOSSIBLE" + | "KEY_OVER_1024_CHARS" + | "MISSING_CHAR" + | "MULTILINE_IMPLICIT_KEY" + | "MULTIPLE_ANCHORS" + | "MULTIPLE_DOCS" + | "MULTIPLE_TAGS" + | "NON_STRING_KEY" + | "TAB_AS_INDENT" + | "TAG_RESOLVE_FAILED" + | "UNEXPECTED_TOKEN" + | "BAD_COLLECTION_TYPE"; type LinePos = { - line: number; - col: number; + line: number; + col: number; }; declare class YAMLError extends Error { - name: 'YAMLParseError' | 'YAMLWarning'; - code: ErrorCode; - message: string; - pos: [number, number]; - linePos?: [LinePos] | [LinePos, LinePos]; - constructor(name: YAMLError['name'], pos: [number, number], code: ErrorCode, message: string); + name: "YAMLParseError" | "YAMLWarning"; + code: ErrorCode; + message: string; + pos: [number, number]; + linePos?: [LinePos] | [LinePos, LinePos]; + constructor( + name: YAMLError["name"], + pos: [number, number], + code: ErrorCode, + message: string, + ); } declare class YAMLWarning extends YAMLError { - constructor(pos: [number, number], code: ErrorCode, message: string); + constructor(pos: [number, number], code: ErrorCode, message: string); } type Reviver = (key: unknown, value: unknown) => unknown; -type LogLevelId = 'silent' | 'error' | 'warn' | 'debug'; +type LogLevelId = "silent" | "error" | "warn" | "debug"; interface AnchorData { - aliasCount: number; - count: number; - res: unknown; + aliasCount: number; + count: number; + res: unknown; } interface ToJSContext { - anchors: Map; - - aliasResolveCache?: Node[]; - doc: Document; - keep: boolean; - mapAsMap: boolean; - mapKeyWarned: boolean; - maxAliasCount: number; - onCreate?: (res: unknown) => void; + anchors: Map; + + aliasResolveCache?: Node[]; + doc: Document; + keep: boolean; + mapAsMap: boolean; + mapKeyWarned: boolean; + maxAliasCount: number; + onCreate?: (res: unknown) => void; } declare namespace Scalar { - interface Parsed extends Scalar { - range: Range; - source: string; - srcToken?: FlowScalar | BlockScalar; - } - type BLOCK_FOLDED = 'BLOCK_FOLDED'; - type BLOCK_LITERAL = 'BLOCK_LITERAL'; - type PLAIN = 'PLAIN'; - type QUOTE_DOUBLE = 'QUOTE_DOUBLE'; - type QUOTE_SINGLE = 'QUOTE_SINGLE'; - type Type = BLOCK_FOLDED | BLOCK_LITERAL | PLAIN | QUOTE_DOUBLE | QUOTE_SINGLE; + interface Parsed extends Scalar { + range: Range; + source: string; + srcToken?: FlowScalar | BlockScalar; + } + type BLOCK_FOLDED = "BLOCK_FOLDED"; + type BLOCK_LITERAL = "BLOCK_LITERAL"; + type PLAIN = "PLAIN"; + type QUOTE_DOUBLE = "QUOTE_DOUBLE"; + type QUOTE_SINGLE = "QUOTE_SINGLE"; + type Type = + | BLOCK_FOLDED + | BLOCK_LITERAL + | PLAIN + | QUOTE_DOUBLE + | QUOTE_SINGLE; } declare class Scalar extends NodeBase { - static readonly BLOCK_FOLDED = 'BLOCK_FOLDED'; - static readonly BLOCK_LITERAL = 'BLOCK_LITERAL'; - static readonly PLAIN = 'PLAIN'; - static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE'; - static readonly QUOTE_SINGLE = 'QUOTE_SINGLE'; - value: T; + static readonly BLOCK_FOLDED = "BLOCK_FOLDED"; + static readonly BLOCK_LITERAL = "BLOCK_LITERAL"; + static readonly PLAIN = "PLAIN"; + static readonly QUOTE_DOUBLE = "QUOTE_DOUBLE"; + static readonly QUOTE_SINGLE = "QUOTE_SINGLE"; + value: T; - anchor?: string; + anchor?: string; - format?: string; + format?: string; - minFractionDigits?: number; + minFractionDigits?: number; - source?: string; + source?: string; - type?: Scalar.Type; - constructor(value: T); - toJSON(arg?: any, ctx?: ToJSContext): any; - toString(): string; + type?: Scalar.Type; + constructor(value: T); + toJSON(arg?: any, ctx?: ToJSContext): any; + toString(): string; } type StringifyContext = { - actualString?: boolean; - allNullValues?: boolean; - anchors: Set; - doc: Document; - forceBlockIndent?: boolean; - implicitKey?: boolean; - indent: string; - indentStep: string; - indentAtStart?: number; - inFlow: boolean | null; - inStringifyKey?: boolean; - flowCollectionPadding: string; - options: Readonly>>; - resolvedAliases?: Set; + actualString?: boolean; + allNullValues?: boolean; + anchors: Set; + doc: Document; + forceBlockIndent?: boolean; + implicitKey?: boolean; + indent: string; + indentStep: string; + indentAtStart?: number; + inFlow: boolean | null; + inStringifyKey?: boolean; + flowCollectionPadding: string; + options: Readonly< + Required> + >; + resolvedAliases?: Set; }; declare abstract class Collection extends NodeBase { - schema: Schema | undefined; - [NODE_TYPE]: symbol; - items: unknown[]; + schema: Schema | undefined; + [NODE_TYPE]: symbol; + items: unknown[]; - anchor?: string; + anchor?: string; - flow?: boolean; - constructor(type: symbol, schema?: Schema); + flow?: boolean; + constructor(type: symbol, schema?: Schema); - clone(schema?: Schema): Collection; + clone(schema?: Schema): Collection; - abstract add(value: unknown): void; + abstract add(value: unknown): void; - abstract delete(key: unknown): boolean; + abstract delete(key: unknown): boolean; - abstract get(key: unknown, keepScalar?: boolean): unknown; + abstract get(key: unknown, keepScalar?: boolean): unknown; - abstract has(key: unknown): boolean; + abstract has(key: unknown): boolean; - abstract set(key: unknown, value: unknown): void; + abstract set(key: unknown, value: unknown): void; - addIn(path: Iterable, value: unknown): void; + addIn(path: Iterable, value: unknown): void; - deleteIn(path: Iterable): boolean; + deleteIn(path: Iterable): boolean; - getIn(path: Iterable, keepScalar?: boolean): unknown; - hasAllNullValues(allowScalar?: boolean): boolean; + getIn(path: Iterable, keepScalar?: boolean): unknown; + hasAllNullValues(allowScalar?: boolean): boolean; - hasIn(path: Iterable): boolean; + hasIn(path: Iterable): boolean; - setIn(path: Iterable, value: unknown): void; + setIn(path: Iterable, value: unknown): void; } declare namespace YAMLSeq { - interface Parsed< - T extends ParsedNode | Pair = ParsedNode - > extends YAMLSeq { - items: T[]; - range: Range; - srcToken?: BlockSequence | FlowCollection; - } + interface Parsed< + T extends ParsedNode | Pair = ParsedNode, + > extends YAMLSeq { + items: T[]; + range: Range; + srcToken?: BlockSequence | FlowCollection; + } } declare class YAMLSeq extends Collection { - static get tagName(): 'tag:yaml.org,2002:seq'; - items: T[]; - constructor(schema?: Schema); - add(value: T): void; - - delete(key: unknown): boolean; - - get(key: unknown, keepScalar: true): Scalar | undefined; - get(key: unknown, keepScalar?: false): T | undefined; - get(key: unknown, keepScalar?: boolean): T | Scalar | undefined; - - has(key: unknown): boolean; - - set(key: unknown, value: T): void; - toJSON(_?: unknown, ctx?: ToJSContext): unknown[]; - toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; - static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq; + static get tagName(): "tag:yaml.org,2002:seq"; + items: T[]; + constructor(schema?: Schema); + add(value: T): void; + + delete(key: unknown): boolean; + + get(key: unknown, keepScalar: true): Scalar | undefined; + get(key: unknown, keepScalar?: false): T | undefined; + get(key: unknown, keepScalar?: boolean): T | Scalar | undefined; + + has(key: unknown): boolean; + + set(key: unknown, value: T): void; + toJSON(_?: unknown, ctx?: ToJSContext): unknown[]; + toString( + ctx?: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ): string; + static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq; } interface TagBase { - createNode?: (schema: Schema, value: unknown, ctx: CreateNodeContext) => Node; + createNode?: (schema: Schema, value: unknown, ctx: CreateNodeContext) => Node; - default?: boolean | 'key'; + default?: boolean | "key"; - format?: string; + format?: string; - identify?: (value: unknown) => boolean; + identify?: (value: unknown) => boolean; - tag: string; + tag: string; } interface ScalarTag extends TagBase { - collection?: never; - nodeClass?: never; - - resolve(value: string, onError: (message: string) => void, options: ParseOptions): unknown; - - stringify?: ( - item: Scalar, - ctx: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void - ) => string; - - test?: RegExp; + collection?: never; + nodeClass?: never; + + resolve( + value: string, + onError: (message: string) => void, + options: ParseOptions, + ): unknown; + + stringify?: ( + item: Scalar, + ctx: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ) => string; + + test?: RegExp; } interface CollectionTag extends TagBase { - stringify?: never; - test?: never; + stringify?: never; + test?: never; - collection: 'map' | 'seq'; + collection: "map" | "seq"; - nodeClass?: { - new (schema?: Schema): Node; - from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node; - }; + nodeClass?: { + new (schema?: Schema): Node; + from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node; + }; - resolve?: ( - value: YAMLMap.Parsed | YAMLSeq.Parsed, - onError: (message: string) => void, - options: ParseOptions - ) => unknown; + resolve?: ( + value: YAMLMap.Parsed | YAMLSeq.Parsed, + onError: (message: string) => void, + options: ParseOptions, + ) => unknown; } -type MapLike = Map | Set | Record; +type MapLike = + | Map + | Set + | Record; declare namespace YAMLMap { - interface Parsed< - K extends ParsedNode = ParsedNode, - V extends ParsedNode | null = ParsedNode | null - > extends YAMLMap { - items: Pair[]; - range: Range; - srcToken?: BlockMap | FlowCollection; - } + interface Parsed< + K extends ParsedNode = ParsedNode, + V extends ParsedNode | null = ParsedNode | null, + > extends YAMLMap { + items: Pair[]; + range: Range; + srcToken?: BlockMap | FlowCollection; + } } declare class YAMLMap extends Collection { - static get tagName(): 'tag:yaml.org,2002:map'; - items: Pair[]; - constructor(schema?: Schema); - - static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap; - - add( - pair: - | Pair - | { - key: K; - value: V; - }, - overwrite?: boolean - ): void; - delete(key: unknown): boolean; - get(key: unknown, keepScalar: true): Scalar | undefined; - get(key: unknown, keepScalar?: false): V | undefined; - get(key: unknown, keepScalar?: boolean): V | Scalar | undefined; - has(key: unknown): boolean; - set(key: K, value: V): void; - - toJSON>( - _?: unknown, - ctx?: ToJSContext, - Type?: { - new (): T; - } - ): any; - toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + static get tagName(): "tag:yaml.org,2002:map"; + items: Pair[]; + constructor(schema?: Schema); + + static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap; + + add( + pair: + | Pair + | { + key: K; + value: V; + }, + overwrite?: boolean, + ): void; + delete(key: unknown): boolean; + get(key: unknown, keepScalar: true): Scalar | undefined; + get(key: unknown, keepScalar?: false): V | undefined; + get(key: unknown, keepScalar?: boolean): V | Scalar | undefined; + has(key: unknown): boolean; + set(key: K, value: V): void; + + toJSON>( + _?: unknown, + ctx?: ToJSContext, + Type?: { + new (): T; + }, + ): any; + toString( + ctx?: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ): string; } declare const MAP: unique symbol; declare const SCALAR: unique symbol; declare const SEQ: unique symbol; declare const NODE_TYPE: unique symbol; declare class Schema { - compat: Array | null; - knownTags: Record; - name: string; - sortMapEntries: ((a: Pair, b: Pair) => number) | null; - tags: Array; - toStringOptions: Readonly | null; - readonly [MAP]: CollectionTag; - readonly [SCALAR]: ScalarTag; - readonly [SEQ]: CollectionTag; - constructor({ - compat, - customTags, - merge, - resolveKnownTags, - schema, - sortMapEntries, - toStringDefaults - }: SchemaOptions); - clone(): Schema; + compat: Array | null; + knownTags: Record; + name: string; + sortMapEntries: ((a: Pair, b: Pair) => number) | null; + tags: Array; + toStringOptions: Readonly | null; + readonly [MAP]: CollectionTag; + readonly [SCALAR]: ScalarTag; + readonly [SEQ]: CollectionTag; + constructor({ + compat, + customTags, + merge, + resolveKnownTags, + schema, + sortMapEntries, + toStringDefaults, + }: SchemaOptions); + clone(): Schema; } interface CreateNodeContext { - aliasDuplicateObjects: boolean; - keepUndefined: boolean; - onAnchor: (source: unknown) => string; - onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; - sourceObjects: Map< - unknown, - { - anchor: string | null; - node: Node | null; - } - >; - replacer?: Replacer; - schema: Schema; + aliasDuplicateObjects: boolean; + keepUndefined: boolean; + onAnchor: (source: unknown) => string; + onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; + sourceObjects: Map< + unknown, + { + anchor: string | null; + node: Node | null; + } + >; + replacer?: Replacer; + schema: Schema; } declare function addPairToJSMap( - ctx: ToJSContext | undefined, - map: MapLike, - { key, value }: Pair + ctx: ToJSContext | undefined, + map: MapLike, + { key, value }: Pair, ): MapLike; declare class Pair { - readonly [NODE_TYPE]: symbol; + readonly [NODE_TYPE]: symbol; - key: K; + key: K; - value: V | null; + value: V | null; - srcToken?: CollectionItem; - constructor(key: K, value?: V | null); - clone(schema?: Schema): Pair; - toJSON(_?: unknown, ctx?: ToJSContext): ReturnType; - toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + srcToken?: CollectionItem; + constructor(key: K, value?: V | null); + clone(schema?: Schema): Pair; + toJSON(_?: unknown, ctx?: ToJSContext): ReturnType; + toString( + ctx?: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ): string; } declare const tagsByName: { - binary: ScalarTag; - bool: ScalarTag & { - test: RegExp; - }; - float: ScalarTag; - floatExp: ScalarTag; - floatNaN: ScalarTag; - floatTime: ScalarTag; - int: ScalarTag; - intHex: ScalarTag; - intOct: ScalarTag; - intTime: ScalarTag; - map: CollectionTag; - merge: ScalarTag & { - identify(value: unknown): boolean; - test: RegExp; - }; - null: ScalarTag & { - test: RegExp; - }; - omap: CollectionTag; - pairs: CollectionTag; - seq: CollectionTag; - set: CollectionTag; - timestamp: ScalarTag & { - test: RegExp; - }; + binary: ScalarTag; + bool: ScalarTag & { + test: RegExp; + }; + float: ScalarTag; + floatExp: ScalarTag; + floatNaN: ScalarTag; + floatTime: ScalarTag; + int: ScalarTag; + intHex: ScalarTag; + intOct: ScalarTag; + intTime: ScalarTag; + map: CollectionTag; + merge: ScalarTag & { + identify(value: unknown): boolean; + test: RegExp; + }; + null: ScalarTag & { + test: RegExp; + }; + omap: CollectionTag; + pairs: CollectionTag; + seq: CollectionTag; + set: CollectionTag; + timestamp: ScalarTag & { + test: RegExp; + }; }; type TagId = keyof typeof tagsByName; type Tags = Array; type ParseOptions = { - intAsBigInt?: boolean; + intAsBigInt?: boolean; - keepSourceTokens?: boolean; + keepSourceTokens?: boolean; - lineCounter?: LineCounter; + lineCounter?: LineCounter; - prettyErrors?: boolean; + prettyErrors?: boolean; - strict?: boolean; + strict?: boolean; - stringKeys?: boolean; + stringKeys?: boolean; - uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean); + uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean); }; type DocumentOptions = { - _directives?: Directives; + _directives?: Directives; - logLevel?: LogLevelId; + logLevel?: LogLevelId; - version?: '1.1' | '1.2' | 'next'; + version?: "1.1" | "1.2" | "next"; }; type SchemaOptions = { - compat?: string | Tags | null; + compat?: string | Tags | null; - customTags?: Tags | ((tags: Tags) => Tags) | null; + customTags?: Tags | ((tags: Tags) => Tags) | null; - merge?: boolean; + merge?: boolean; - resolveKnownTags?: boolean; + resolveKnownTags?: boolean; - schema?: string | Schema; + schema?: string | Schema; - sortMapEntries?: boolean | ((a: Pair, b: Pair) => number); + sortMapEntries?: boolean | ((a: Pair, b: Pair) => number); - toStringDefaults?: ToStringOptions; + toStringDefaults?: ToStringOptions; }; type CreateNodeOptions = { - aliasDuplicateObjects?: boolean; + aliasDuplicateObjects?: boolean; - anchorPrefix?: string; - flow?: boolean; + anchorPrefix?: string; + flow?: boolean; - keepUndefined?: boolean | null; - onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; + keepUndefined?: boolean | null; + onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; - tag?: string; + tag?: string; }; type ToJSOptions = { - mapAsMap?: boolean; + mapAsMap?: boolean; - maxAliasCount?: number; + maxAliasCount?: number; - onAnchor?: (value: unknown, count: number) => void; + onAnchor?: (value: unknown, count: number) => void; - reviver?: Reviver; + reviver?: Reviver; }; type ToStringOptions = { - blockQuote?: boolean | 'folded' | 'literal'; + blockQuote?: boolean | "folded" | "literal"; - collectionStyle?: 'any' | 'block' | 'flow'; + collectionStyle?: "any" | "block" | "flow"; - commentString?: (comment: string) => string; + commentString?: (comment: string) => string; - defaultKeyType?: Scalar.Type | null; + defaultKeyType?: Scalar.Type | null; - defaultStringType?: Scalar.Type; + defaultStringType?: Scalar.Type; - directives?: boolean | null; + directives?: boolean | null; - doubleQuotedAsJSON?: boolean; + doubleQuotedAsJSON?: boolean; - doubleQuotedMinMultiLineLength?: number; + doubleQuotedMinMultiLineLength?: number; - falseStr?: string; + falseStr?: string; - flowCollectionPadding?: boolean; + flowCollectionPadding?: boolean; - indent?: number; + indent?: number; - indentSeq?: boolean; + indentSeq?: boolean; - lineWidth?: number; + lineWidth?: number; - minContentWidth?: number; + minContentWidth?: number; - nullStr?: string; + nullStr?: string; - simpleKeys?: boolean; + simpleKeys?: boolean; - singleQuote?: boolean | null; + singleQuote?: boolean | null; - trueStr?: string; + trueStr?: string; - verifyAliasOrder?: boolean; + verifyAliasOrder?: boolean; }; type Node = Alias | Scalar | YAMLMap | YAMLSeq; -type NodeType = T extends string | number | bigint | boolean | null | undefined - ? Scalar - : T extends Date - ? Scalar - : T extends Array - ? YAMLSeq> - : T extends { - [key: string]: any; - } - ? YAMLMap, NodeType> - : T extends { - [key: number]: any; - } - ? YAMLMap, NodeType> - : Node; -type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed; +type NodeType = T extends + | string + | number + | bigint + | boolean + | null + | undefined + ? Scalar + : T extends Date + ? Scalar + : T extends Array + ? YAMLSeq> + : T extends { + [key: string]: any; + } + ? YAMLMap, NodeType> + : T extends { + [key: number]: any; + } + ? YAMLMap, NodeType> + : Node; +type ParsedNode = + | Alias.Parsed + | Scalar.Parsed + | YAMLMap.Parsed + | YAMLSeq.Parsed; type Range = [number, number, number]; declare abstract class NodeBase { - readonly [NODE_TYPE]: symbol; + readonly [NODE_TYPE]: symbol; - comment?: string | null; + comment?: string | null; - commentBefore?: string | null; + commentBefore?: string | null; - range?: Range | null; + range?: Range | null; - spaceBefore?: boolean; + spaceBefore?: boolean; - srcToken?: Token; + srcToken?: Token; - tag?: string; + tag?: string; - addToJSMap?: (ctx: ToJSContext | undefined, map: MapLike, value: unknown) => void; + addToJSMap?: ( + ctx: ToJSContext | undefined, + map: MapLike, + value: unknown, + ) => void; - abstract toJSON(): any; - abstract toString( - ctx?: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void - ): string; - constructor(type: symbol); + abstract toJSON(): any; + abstract toString( + ctx?: StringifyContext, + onComment?: () => void, + onChompKeep?: () => void, + ): string; + constructor(type: symbol); - clone(): NodeBase; + clone(): NodeBase; - toJS( - doc: Document, - { mapAsMap, maxAliasCount, onAnchor, reviver }?: ToJSOptions - ): any; + toJS( + doc: Document, + { mapAsMap, maxAliasCount, onAnchor, reviver }?: ToJSOptions, + ): any; } interface SourceToken { - type: - | 'byte-order-mark' - | 'doc-mode' - | 'doc-start' - | 'space' - | 'comment' - | 'newline' - | 'directive-line' - | 'anchor' - | 'tag' - | 'seq-item-ind' - | 'explicit-key-ind' - | 'map-value-ind' - | 'flow-map-start' - | 'flow-map-end' - | 'flow-seq-start' - | 'flow-seq-end' - | 'flow-error-end' - | 'comma' - | 'block-scalar-header'; - offset: number; - indent: number; - source: string; + type: + | "byte-order-mark" + | "doc-mode" + | "doc-start" + | "space" + | "comment" + | "newline" + | "directive-line" + | "anchor" + | "tag" + | "seq-item-ind" + | "explicit-key-ind" + | "map-value-ind" + | "flow-map-start" + | "flow-map-end" + | "flow-seq-start" + | "flow-seq-end" + | "flow-error-end" + | "comma" + | "block-scalar-header"; + offset: number; + indent: number; + source: string; } interface ErrorToken { - type: 'error'; - offset: number; - source: string; - message: string; + type: "error"; + offset: number; + source: string; + message: string; } interface Directive$1 { - type: 'directive'; - offset: number; - source: string; + type: "directive"; + offset: number; + source: string; } interface Document$1 { - type: 'document'; - offset: number; - start: SourceToken[]; - value?: Token; - end?: SourceToken[]; + type: "document"; + offset: number; + start: SourceToken[]; + value?: Token; + end?: SourceToken[]; } interface DocumentEnd { - type: 'doc-end'; - offset: number; - source: string; - end?: SourceToken[]; + type: "doc-end"; + offset: number; + source: string; + end?: SourceToken[]; } interface FlowScalar { - type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar'; - offset: number; - indent: number; - source: string; - end?: SourceToken[]; + type: "alias" | "scalar" | "single-quoted-scalar" | "double-quoted-scalar"; + offset: number; + indent: number; + source: string; + end?: SourceToken[]; } interface BlockScalar { - type: 'block-scalar'; - offset: number; - indent: number; - props: Token[]; - source: string; + type: "block-scalar"; + offset: number; + indent: number; + props: Token[]; + source: string; } interface BlockMap { - type: 'block-map'; - offset: number; - indent: number; - items: Array< - | { - start: SourceToken[]; - explicitKey?: true; - key?: never; - sep?: never; - value?: never; - } - | { - start: SourceToken[]; - explicitKey?: true; - key: Token | null; - sep: SourceToken[]; - value?: Token; - } - >; + type: "block-map"; + offset: number; + indent: number; + items: Array< + | { + start: SourceToken[]; + explicitKey?: true; + key?: never; + sep?: never; + value?: never; + } + | { + start: SourceToken[]; + explicitKey?: true; + key: Token | null; + sep: SourceToken[]; + value?: Token; + } + >; } interface BlockSequence { - type: 'block-seq'; - offset: number; - indent: number; - items: Array<{ - start: SourceToken[]; - key?: never; - sep?: never; - value?: Token; - }>; + type: "block-seq"; + offset: number; + indent: number; + items: Array<{ + start: SourceToken[]; + key?: never; + sep?: never; + value?: Token; + }>; } type CollectionItem = { - start: SourceToken[]; - key?: Token | null; - sep?: SourceToken[]; - value?: Token; + start: SourceToken[]; + key?: Token | null; + sep?: SourceToken[]; + value?: Token; }; interface FlowCollection { - type: 'flow-collection'; - offset: number; - indent: number; - start: SourceToken; - items: CollectionItem[]; - end: SourceToken[]; + type: "flow-collection"; + offset: number; + indent: number; + start: SourceToken; + items: CollectionItem[]; + end: SourceToken[]; } type Token = - | SourceToken - | ErrorToken - | Directive$1 - | Document$1 - | DocumentEnd - | FlowScalar - | BlockScalar - | BlockMap - | BlockSequence - | FlowCollection; + | SourceToken + | ErrorToken + | Directive$1 + | Document$1 + | DocumentEnd + | FlowScalar + | BlockScalar + | BlockMap + | BlockSequence + | FlowCollection; declare namespace Alias { - interface Parsed extends Alias { - range: Range; - srcToken?: FlowScalar & { - type: 'alias'; - }; - } + interface Parsed extends Alias { + range: Range; + srcToken?: FlowScalar & { + type: "alias"; + }; + } } declare class Alias extends NodeBase { - source: string; - anchor?: never; - constructor(source: string); - - resolve(doc: Document, ctx?: ToJSContext): Scalar | YAMLMap | YAMLSeq | undefined; - toJSON(_arg?: unknown, ctx?: ToJSContext): unknown; - toString(ctx?: StringifyContext, _onComment?: () => void, _onChompKeep?: () => void): string; + source: string; + anchor?: never; + constructor(source: string); + + resolve( + doc: Document, + ctx?: ToJSContext, + ): Scalar | YAMLMap | YAMLSeq | undefined; + toJSON(_arg?: unknown, ctx?: ToJSContext): unknown; + toString( + ctx?: StringifyContext, + _onComment?: () => void, + _onChompKeep?: () => void, + ): string; } type Replacer = any[] | ((key: any, value: any) => unknown); declare namespace Document { - interface Parsed< - Contents extends ParsedNode = ParsedNode, - Strict extends boolean = true - > extends Document { - directives: Directives; - range: Range; - } + interface Parsed< + Contents extends ParsedNode = ParsedNode, + Strict extends boolean = true, + > extends Document { + directives: Directives; + range: Range; + } } -declare class Document { - readonly [NODE_TYPE]: symbol; +declare class Document< + Contents extends Node = Node, + Strict extends boolean = true, +> { + readonly [NODE_TYPE]: symbol; - commentBefore: string | null; + commentBefore: string | null; - comment: string | null; + comment: string | null; - contents: Strict extends true ? Contents | null : Contents; - directives: Strict extends true ? Directives | undefined : Directives; + contents: Strict extends true ? Contents | null : Contents; + directives: Strict extends true ? Directives | undefined : Directives; - errors: YAMLError[]; - options: Required< - Omit - >; + errors: YAMLError[]; + options: Required< + Omit< + ParseOptions & DocumentOptions, + "_directives" | "lineCounter" | "version" + > + >; - range?: Range; + range?: Range; - schema: Schema; + schema: Schema; - warnings: YAMLWarning[]; + warnings: YAMLWarning[]; - constructor( - value?: any, - options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions - ); - constructor( - value: any, - replacer: null | Replacer, - options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions - ); + constructor( + value?: any, + options?: DocumentOptions & + SchemaOptions & + ParseOptions & + CreateNodeOptions, + ); + constructor( + value: any, + replacer: null | Replacer, + options?: DocumentOptions & + SchemaOptions & + ParseOptions & + CreateNodeOptions, + ); - clone(): Document; + clone(): Document; - add(value: any): void; + add(value: any): void; - addIn(path: Iterable, value: unknown): void; + addIn(path: Iterable, value: unknown): void; - createAlias(node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, name?: string): Alias; + createAlias( + node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, + name?: string, + ): Alias; - createNode(value: T, options?: CreateNodeOptions): NodeType; - createNode( - value: T, - replacer: Replacer | CreateNodeOptions | null, - options?: CreateNodeOptions - ): NodeType; + createNode(value: T, options?: CreateNodeOptions): NodeType; + createNode( + value: T, + replacer: Replacer | CreateNodeOptions | null, + options?: CreateNodeOptions, + ): NodeType; - createPair( - key: unknown, - value: unknown, - options?: CreateNodeOptions - ): Pair; + createPair( + key: unknown, + value: unknown, + options?: CreateNodeOptions, + ): Pair; - delete(key: unknown): boolean; + delete(key: unknown): boolean; - deleteIn(path: Iterable | null): boolean; + deleteIn(path: Iterable | null): boolean; - get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any; + get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any; - getIn(path: Iterable | null, keepScalar?: boolean): Strict extends true ? unknown : any; + getIn( + path: Iterable | null, + keepScalar?: boolean, + ): Strict extends true ? unknown : any; - has(key: unknown): boolean; + has(key: unknown): boolean; - hasIn(path: Iterable | null): boolean; + hasIn(path: Iterable | null): boolean; - set(key: any, value: unknown): void; + set(key: any, value: unknown): void; - setIn(path: Iterable | null, value: unknown): void; + setIn(path: Iterable | null, value: unknown): void; - setSchema(version: '1.1' | '1.2' | 'next' | null, options?: SchemaOptions): void; + setSchema( + version: "1.1" | "1.2" | "next" | null, + options?: SchemaOptions, + ): void; - toJS( - opt?: ToJSOptions & { - [ignored: string]: unknown; - } - ): any; + toJS( + opt?: ToJSOptions & { + [ignored: string]: unknown; + }, + ): any; - toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']): any; + toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions["onAnchor"]): any; - toString(options?: ToStringOptions): string; + toString(options?: ToStringOptions): string; } declare class Directives { - static defaultYaml: Directives['yaml']; - static defaultTags: Directives['tags']; - yaml: { - version: '1.1' | '1.2' | 'next'; - explicit?: boolean; - }; - tags: Record; + static defaultYaml: Directives["yaml"]; + static defaultTags: Directives["tags"]; + yaml: { + version: "1.1" | "1.2" | "next"; + explicit?: boolean; + }; + tags: Record; - docStart: true | null; + docStart: true | null; - docEnd: boolean; + docEnd: boolean; - private atNextDocument?; - constructor(yaml?: Directives['yaml'], tags?: Directives['tags']); - clone(): Directives; + private atNextDocument?; + constructor(yaml?: Directives["yaml"], tags?: Directives["tags"]); + clone(): Directives; - atDocument(): Directives; + atDocument(): Directives; - add(line: string, onError: (offset: number, message: string, warning?: boolean) => void): boolean; + add( + line: string, + onError: (offset: number, message: string, warning?: boolean) => void, + ): boolean; - tagName(source: string, onError: (message: string) => void): string | null; + tagName(source: string, onError: (message: string) => void): string | null; - tagString(tag: string): string; - toString(doc?: Document): string; + tagString(tag: string): string; + toString(doc?: Document): string; } -declare function parseDocument( - source: string, - options?: ParseOptions & DocumentOptions & SchemaOptions -): Contents extends ParsedNode ? Document.Parsed : Document; -declare module 'estree' { - interface TSTypeAnnotation { - type: 'TSTypeAnnotation'; - typeAnnotation: TSStringKeyword | TSTypeReference | TSUnionType | TSIndexedAccessType; - } - interface TSStringKeyword { - type: 'TSStringKeyword'; - } - interface TSNullKeyword { - type: 'TSNullKeyword'; - } - interface TSTypeReference { - type: 'TSTypeReference'; - typeName: Identifier; - } - interface TSAsExpression extends BaseNode { - type: 'TSAsExpression'; - expression: Expression; - typeAnnotation: TSTypeAnnotation['typeAnnotation']; - } - interface TSModuleDeclaration extends BaseNode { - type: 'TSModuleDeclaration'; - global: boolean; - declare: boolean; - id: Identifier; - body: TSModuleBlock; - } - interface TSModuleBlock extends BaseNode { - type: 'TSModuleBlock'; - body: Array; - } - interface TSInterfaceDeclaration extends BaseNode { - type: 'TSInterfaceDeclaration'; - id: Identifier; - body: TSInterfaceBody; - } - interface TSInterfaceBody extends BaseNode { - type: 'TSInterfaceBody'; - body: TSPropertySignature[]; - } - interface TSPropertySignature extends BaseNode { - type: 'TSPropertySignature'; - computed: boolean; - key: Identifier; - optional?: boolean; - typeAnnotation: TSTypeAnnotation; - } - interface TSProgram extends Omit { - body: Array; - } - interface TSUnionType { - type: 'TSUnionType'; - types: Array; - } - interface TSImportType { - type: 'TSImportType'; - argument: Literal; - qualifier: Identifier; - } - interface TSIndexedAccessType { - type: 'TSIndexedAccessType'; - objectType: TSImportType; - indexType: TSLiteralType; - } - interface TSLiteralType { - type: 'TSLiteralType'; - literal: Literal; - } - interface TSSatisfiesExpression extends BaseNode { - type: 'TSSatisfiesExpression'; - expression: Expression; - typeAnnotation: TSTypeAnnotation['typeAnnotation']; - } - interface BaseNodeWithoutComments { - type: string; - loc?: SourceLocation | null | undefined; - range?: [number, number] | undefined; - start?: number; - end?: number; - } - interface Identifier { - typeAnnotation?: TSTypeAnnotation; - } - interface ExpressionMap { - TSAsExpression: TSAsExpression; - TSSatisfiesExpression: TSSatisfiesExpression; - } - interface NodeMap { - TSModuleDeclaration: TSModuleDeclaration; - TSInterfaceDeclaration: TSInterfaceDeclaration; - } - interface ImportDeclaration { - importKind: 'type' | 'value'; - } +declare function parseDocument< + Contents extends Node = ParsedNode, + Strict extends boolean = true, +>( + source: string, + options?: ParseOptions & DocumentOptions & SchemaOptions, +): Contents extends ParsedNode + ? Document.Parsed + : Document; +declare module "estree" { + interface TSTypeAnnotation { + type: "TSTypeAnnotation"; + typeAnnotation: + | TSStringKeyword + | TSTypeReference + | TSUnionType + | TSIndexedAccessType; + } + interface TSStringKeyword { + type: "TSStringKeyword"; + } + interface TSNullKeyword { + type: "TSNullKeyword"; + } + interface TSTypeReference { + type: "TSTypeReference"; + typeName: Identifier; + } + interface TSAsExpression extends BaseNode { + type: "TSAsExpression"; + expression: Expression; + typeAnnotation: TSTypeAnnotation["typeAnnotation"]; + } + interface TSModuleDeclaration extends BaseNode { + type: "TSModuleDeclaration"; + global: boolean; + declare: boolean; + id: Identifier; + body: TSModuleBlock; + } + interface TSModuleBlock extends BaseNode { + type: "TSModuleBlock"; + body: Array; + } + interface TSInterfaceDeclaration extends BaseNode { + type: "TSInterfaceDeclaration"; + id: Identifier; + body: TSInterfaceBody; + } + interface TSInterfaceBody extends BaseNode { + type: "TSInterfaceBody"; + body: TSPropertySignature[]; + } + interface TSPropertySignature extends BaseNode { + type: "TSPropertySignature"; + computed: boolean; + key: Identifier; + optional?: boolean; + typeAnnotation: TSTypeAnnotation; + } + interface TSProgram extends Omit { + body: Array< + Directive | Statement | ModuleDeclaration | TSModuleDeclaration + >; + } + interface TSUnionType { + type: "TSUnionType"; + types: Array; + } + interface TSImportType { + type: "TSImportType"; + argument: Literal; + qualifier: Identifier; + } + interface TSIndexedAccessType { + type: "TSIndexedAccessType"; + objectType: TSImportType; + indexType: TSLiteralType; + } + interface TSLiteralType { + type: "TSLiteralType"; + literal: Literal; + } + interface TSSatisfiesExpression extends BaseNode { + type: "TSSatisfiesExpression"; + expression: Expression; + typeAnnotation: TSTypeAnnotation["typeAnnotation"]; + } + interface BaseNodeWithoutComments { + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; + start?: number; + end?: number; + } + interface Identifier { + typeAnnotation?: TSTypeAnnotation; + } + interface ExpressionMap { + TSAsExpression: TSAsExpression; + TSSatisfiesExpression: TSSatisfiesExpression; + } + interface NodeMap { + TSModuleDeclaration: TSModuleDeclaration; + TSInterfaceDeclaration: TSInterfaceDeclaration; + } + interface ImportDeclaration { + importKind: "type" | "value"; + } } declare function parseYaml$1(content: string): ReturnType; type CommentType = { - type: 'Line' | 'Block'; - value: string; + type: "Line" | "Block"; + value: string; }; declare class Comments { - private original; - private leading; - private trailing; - constructor(); - add( - node: BaseNode$1, - comment: CommentType, - options?: { - position?: 'leading' | 'trailing'; - } - ): void; - remove(predicate: (comment: estree.Comment) => boolean | undefined | null): void; + private original; + private leading; + private trailing; + constructor(); + add( + node: BaseNode$1, + comment: CommentType, + options?: { + position?: "leading" | "trailing"; + }, + ): void; + remove( + predicate: (comment: estree.Comment) => boolean | undefined | null, + ): void; } type ParseBase = { - source: string; + source: string; - generateCode(): string; + generateCode(): string; }; declare function parseScript(source: string): { - ast: estree.Program; - comments: Comments; + ast: estree.Program; + comments: Comments; } & ParseBase; declare function parseCss(source: string): { - ast: Omit; + ast: Omit; } & ParseBase; declare function parseHtml(source: string): { - ast: SvelteAst.Fragment; + ast: SvelteAst.Fragment; } & ParseBase; declare function parseJson(source: string): { - data: any; + data: any; } & ParseBase; declare function parseYaml(source: string): { - data: ReturnType; + data: ReturnType; } & ParseBase; declare function parseSvelte(source: string): { - ast: SvelteAst.Root; + ast: SvelteAst.Root; } & ParseBase; declare function parseToml(source: string): { - data: TomlTable; + data: TomlTable; } & ParseBase; interface DedentOptions { - alignValues?: boolean; - escapeSpecialCharacters?: boolean; - trimWhitespace?: boolean; + alignValues?: boolean; + escapeSpecialCharacters?: boolean; + trimWhitespace?: boolean; } interface Dedent { - (literals: string): string; - (strings: TemplateStringsArray, ...values: unknown[]): string; - withOptions: CreateDedent; + (literals: string): string; + (strings: TemplateStringsArray, ...values: unknown[]): string; + withOptions: CreateDedent; } type CreateDedent = (options: DedentOptions) => Dedent; declare const dedent: Dedent; -declare module 'zimmerframe' { - export function walk< - T extends { - type: string; - }, - U extends Record | null - >(node: T, state: U, visitors: Visitors): T; - type BaseNode = { - type: string; - }; - type NodeOf = X extends { - type: T; - } - ? X - : never; - type SpecialisedVisitors = { - [K in T['type']]?: Visitor, U, T>; - }; - export type Visitor = (node: T, context: Context) => V | void; - export type Visitors = T['type'] extends '_' - ? never - : SpecialisedVisitors & { - _?: Visitor; - }; - export interface Context { - next: (state?: U) => T | void; - path: T[]; - state: U; - stop: () => void; - visit: (node: T, state?: U) => T; - } - export {}; +declare module "zimmerframe" { + export function walk< + T extends { + type: string; + }, + U extends Record | null, + >(node: T, state: U, visitors: Visitors): T; + type BaseNode = { + type: string; + }; + type NodeOf = X extends { + type: T; + } + ? X + : never; + type SpecialisedVisitors = { + [K in T["type"]]?: Visitor, U, T>; + }; + export type Visitor = (node: T, context: Context) => V | void; + export type Visitors = T["type"] extends "_" + ? never + : SpecialisedVisitors & { + _?: Visitor; + }; + export interface Context { + next: (state?: U) => T | void; + path: T[]; + state: U; + stop: () => void; + visit: (node: T, state?: U) => T; + } + export {}; } //# sourceMappingURL=index.d.ts.map declare namespace index_d_exports$1 { - export { addAtRule, addDeclaration, addImports, addRule }; + export { addAtRule, addDeclaration, addImports, addRule }; } declare function addRule( - node: SvelteAst.CSS.StyleSheetBase, - options: { - selector: string; - } + node: SvelteAst.CSS.StyleSheetBase, + options: { + selector: string; + }, ): SvelteAst.CSS.Rule; declare function addDeclaration( - node: SvelteAst.CSS.Rule, - options: { - property: string; - value: string; - } + node: SvelteAst.CSS.Rule, + options: { + property: string; + value: string; + }, ): void; declare function addImports( - node: SvelteAst.CSS.StyleSheetBase, - options: { - imports: string[]; - } + node: SvelteAst.CSS.StyleSheetBase, + options: { + imports: string[]; + }, ): void; declare function addAtRule( - node: SvelteAst.CSS.StyleSheetBase, - options: { - name: string; - params: string; - append: boolean; - } + node: SvelteAst.CSS.StyleSheetBase, + options: { + name: string; + params: string; + append: boolean; + }, ): SvelteAst.CSS.Atrule; declare namespace array_d_exports { - export { append, create$1 as create, prepend }; + export { append, create$1 as create, prepend }; } declare function create$1(): estree.ArrayExpression; declare function append( - node: estree.ArrayExpression, - element: string | estree.Expression | estree.SpreadElement + node: estree.ArrayExpression, + element: string | estree.Expression | estree.SpreadElement, ): void; declare function prepend( - node: estree.ArrayExpression, - element: string | estree.Expression | estree.SpreadElement + node: estree.ArrayExpression, + element: string | estree.Expression | estree.SpreadElement, ): void; declare namespace object_d_exports { - export { create, overrideProperties, property, propertyNode }; + export { create, overrideProperties, property, propertyNode }; } type ObjectPrimitiveValues = string | number | boolean | undefined | null; -type ObjectValues = ObjectPrimitiveValues | Record | ObjectValues[]; +type ObjectValues = + | ObjectPrimitiveValues + | Record + | ObjectValues[]; type ObjectMap = Record; declare function property( - node: estree.ObjectExpression, - options: { - name: string; - fallback: T; - } + node: estree.ObjectExpression, + options: { + name: string; + fallback: T; + }, ): T; declare function propertyNode( - node: estree.ObjectExpression, - options: { - name: string; - fallback: T; - } + node: estree.ObjectExpression, + options: { + name: string; + fallback: T; + }, ): estree.Property; declare function create(properties: ObjectMap): estree.ObjectExpression; declare function overrideProperties( - objectExpression: estree.ObjectExpression, - properties: ObjectMap + objectExpression: estree.ObjectExpression, + properties: ObjectMap, ): void; declare namespace common_d_exports { - export { - addJsDocComment, - addJsDocTypeComment, - appendFromString, - appendStatement, - areNodesEqual, - contains, - createBlockStatement, - createExpressionStatement, - createLiteral, - createSatisfies, - createSpread, - createTypeProperty, - hasTypeProperty, - parseExpression, - parseFromString, - parseStatement, - typeAnnotate - }; + export { + addJsDocComment, + addJsDocTypeComment, + appendFromString, + appendStatement, + areNodesEqual, + contains, + createBlockStatement, + createExpressionStatement, + createLiteral, + createSatisfies, + createSpread, + createTypeProperty, + hasTypeProperty, + parseExpression, + parseFromString, + parseStatement, + typeAnnotate, + }; } declare function addJsDocTypeComment( - node: estree.Node, - comments: Comments, - options: { - type: string; - } + node: estree.Node, + comments: Comments, + options: { + type: string; + }, ): void; declare function addJsDocComment( - node: estree.Node, - comments: Comments, - options: { - params: Record; - } + node: estree.Node, + comments: Comments, + options: { + params: Record; + }, ): void; declare function typeAnnotate( - node: estree.Expression, - options: { - type: string; - } + node: estree.Expression, + options: { + type: string; + }, ): estree.TSAsExpression; declare function createSatisfies( - node: estree.Expression, - options: { - type: string; - } + node: estree.Expression, + options: { + type: string; + }, ): estree.TSSatisfiesExpression; -declare function createSpread(argument: estree.Expression): estree.SpreadElement; -declare function createLiteral(value: string | number | boolean | null): estree.Literal; -declare function areNodesEqual(node: estree.Node, otherNode: estree.Node): boolean; +declare function createSpread( + argument: estree.Expression, +): estree.SpreadElement; +declare function createLiteral( + value: string | number | boolean | null, +): estree.Literal; +declare function areNodesEqual( + node: estree.Node, + otherNode: estree.Node, +): boolean; declare function createBlockStatement(): estree.BlockStatement; declare function createExpressionStatement(options: { - expression: estree.Expression; + expression: estree.Expression; }): estree.ExpressionStatement; declare function appendFromString( - node: estree.BlockStatement | estree.Program, - options: { - code: string; - comments?: Comments; - } + node: estree.BlockStatement | estree.Program, + options: { + code: string; + comments?: Comments; + }, ): void; declare function parseExpression(code: string): estree.Expression; declare function parseStatement(code: string): estree.Statement; declare function parseFromString(code: string): T; declare function appendStatement( - node: estree.BlockStatement | estree.Program, - options: { - statement: estree.Statement; - } + node: estree.BlockStatement | estree.Program, + options: { + statement: estree.Statement; + }, ): void; declare function contains(node: estree.Node, targetNode: estree.Node): boolean; declare function hasTypeProperty( - node: estree.TSInterfaceDeclaration['body']['body'][number], - options: { - name: string; - } + node: estree.TSInterfaceDeclaration["body"]["body"][number], + options: { + name: string; + }, ): boolean; declare function createTypeProperty( - name: string, - value: string, - optional?: boolean -): estree.TSInterfaceBody['body'][number]; + name: string, + value: string, + optional?: boolean, +): estree.TSInterfaceBody["body"][number]; declare namespace function_d_exports { - export { createArrow, createCall, getArgument }; + export { createArrow, createCall, getArgument }; } declare function createCall(options: { - name: string; - args: string[]; - useIdentifiers?: boolean; + name: string; + args: string[]; + useIdentifiers?: boolean; }): estree.CallExpression; declare function createArrow(options: { - body: estree.Expression | estree.BlockStatement; - async: boolean; + body: estree.Expression | estree.BlockStatement; + async: boolean; }): estree.ArrowFunctionExpression; declare function getArgument( - node: estree.CallExpression, - options: { - index: number; - fallback: T; - } + node: estree.CallExpression, + options: { + index: number; + fallback: T; + }, ): T; declare namespace imports_d_exports { - export { addDefault, addEmpty, addNamed, addNamespace$1 as addNamespace, find, remove }; + export { + addDefault, + addEmpty, + addNamed, + addNamespace$1 as addNamespace, + find, + remove, + }; } declare function addEmpty( - node: estree.Program, - options: { - from: string; - } + node: estree.Program, + options: { + from: string; + }, ): void; declare function addNamespace$1( - node: estree.Program, - options: { - from: string; - as: string; - } + node: estree.Program, + options: { + from: string; + as: string; + }, ): void; declare function addDefault( - node: estree.Program, - options: { - from: string; - as: string; - } + node: estree.Program, + options: { + from: string; + as: string; + }, ): void; declare function addNamed( - node: estree.Program, - options: { - imports: Record | string[]; - from: string; - isType?: boolean; - } + node: estree.Program, + options: { + imports: Record | string[]; + from: string; + isType?: boolean; + }, ): void; declare function find( - ast: estree.Program, - options: { - name: string; - from: string; - } + ast: estree.Program, + options: { + name: string; + from: string; + }, ): - | { - statement: estree.ImportDeclaration; - alias: string; - } - | { - statement: undefined; - alias: undefined; - }; + | { + statement: estree.ImportDeclaration; + alias: string; + } + | { + statement: undefined; + alias: undefined; + }; declare function remove( - ast: estree.Program, - options: { - name: string; - from: string; - statement?: estree.ImportDeclaration; - } + ast: estree.Program, + options: { + name: string; + from: string; + statement?: estree.ImportDeclaration; + }, ): void; declare namespace variables_d_exports { - export { createIdentifier, declaration, typeAnnotateDeclarator }; + export { createIdentifier, declaration, typeAnnotateDeclarator }; } declare function declaration( - node: estree.Program | estree.Declaration, - options: { - kind: 'const' | 'let' | 'var'; - name: string; - value: estree.Expression; - } + node: estree.Program | estree.Declaration, + options: { + kind: "const" | "let" | "var"; + name: string; + value: estree.Expression; + }, ): estree.VariableDeclaration; declare function createIdentifier(name: string): estree.Identifier; declare function typeAnnotateDeclarator( - node: estree.VariableDeclarator, - options: { - typeName: string; - } + node: estree.VariableDeclarator, + options: { + typeName: string; + }, ): estree.VariableDeclarator; declare namespace exports_d_exports { - export { ExportDefaultResult, addNamespace, createDefault, createNamed }; + export { ExportDefaultResult, addNamespace, createDefault, createNamed }; } type ExportDefaultResult = { - astNode: estree.ExportDefaultDeclaration; - value: T; - isFallback: boolean; + astNode: estree.ExportDefaultDeclaration; + value: T; + isFallback: boolean; }; declare function createDefault( - node: estree.Program, - options: { - fallback: T; - } + node: estree.Program, + options: { + fallback: T; + }, ): ExportDefaultResult; declare function createNamed( - node: estree.Program, - options: { - name: string; - fallback: estree.VariableDeclaration; - } + node: estree.Program, + options: { + name: string; + fallback: estree.VariableDeclaration; + }, ): estree.ExportNamedDeclaration; declare function addNamespace( - node: estree.Program, - options: { - from: string; - as?: string; - } + node: estree.Program, + options: { + from: string; + as?: string; + }, ): void; declare namespace kit_d_exports { - export { addGlobalAppInterface, addHooksHandle }; + export { addGlobalAppInterface, addHooksHandle }; } declare function addGlobalAppInterface( - node: estree.TSProgram, - options: { - name: 'Error' | 'Locals' | 'PageData' | 'PageState' | 'Platform'; - } + node: estree.TSProgram, + options: { + name: "Error" | "Locals" | "PageData" | "PageState" | "Platform"; + }, ): estree.TSInterfaceDeclaration; declare function addHooksHandle( - node: estree.Program, - options: { - language: 'ts' | 'js'; - newHandleName: string; - handleContent: string; - comments: Comments; - } + node: estree.Program, + options: { + language: "ts" | "js"; + newHandleName: string; + handleContent: string; + comments: Comments; + }, ): void; declare namespace vite_d_exports { - export { addPlugin, configProperty, getConfig }; + export { addPlugin, configProperty, getConfig }; } declare const addPlugin: ( - ast: estree.Program, - options: { - code: string; - mode?: 'append' | 'prepend'; - } + ast: estree.Program, + options: { + code: string; + mode?: "append" | "prepend"; + }, ) => void; -declare function configProperty( - ast: estree.Program, - config: estree.ObjectExpression, - options: { - name: string; - fallback: T; - } +declare function configProperty< + T extends estree.Expression | estree.Identifier, +>( + ast: estree.Program, + config: estree.ObjectExpression, + options: { + name: string; + fallback: T; + }, ): T; declare const getConfig: (ast: estree.Program) => estree.ObjectExpression; declare namespace index_d_exports$3 { - export { - array_d_exports as array, - common_d_exports as common, - exports_d_exports as exports, - function_d_exports as functions, - imports_d_exports as imports, - kit_d_exports as kit, - object_d_exports as object, - variables_d_exports as variables, - vite_d_exports as vite - }; + export { + array_d_exports as array, + common_d_exports as common, + exports_d_exports as exports, + function_d_exports as functions, + imports_d_exports as imports, + kit_d_exports as kit, + object_d_exports as object, + variables_d_exports as variables, + vite_d_exports as vite, + }; } declare namespace index_d_exports$2 { - export { addAttribute, addFromRawHtml, appendElement, createElement, insertElement }; + export { + addAttribute, + addFromRawHtml, + appendElement, + createElement, + insertElement, + }; } declare function createElement( - tagName: string, - attributes?: Record + tagName: string, + attributes?: Record, ): SvelteAst.RegularElement; -declare function addAttribute(element: SvelteAst.RegularElement, name: string, value: string): void; +declare function addAttribute( + element: SvelteAst.RegularElement, + name: string, + value: string, +): void; declare function insertElement( - fragment: SvelteAst.Fragment, - elementToInsert: SvelteAst.Fragment['nodes'][0] + fragment: SvelteAst.Fragment, + elementToInsert: SvelteAst.Fragment["nodes"][0], ): void; declare function appendElement( - fragment: SvelteAst.Fragment, - elementToAppend: SvelteAst.Fragment['nodes'][0] + fragment: SvelteAst.Fragment, + elementToAppend: SvelteAst.Fragment["nodes"][0], +): void; +declare function addFromRawHtml( + fragment: SvelteAst.Fragment, + html: string, ): void; -declare function addFromRawHtml(fragment: SvelteAst.Fragment, html: string): void; declare namespace text_d_exports { - export { upsert }; + export { upsert }; } type CommentEntry = { - text: string; - mode: 'append' | 'prepend'; + text: string; + mode: "append" | "prepend"; }; type CommentOption = string | Array; declare function upsert( - content: string, - key: string, - options?: { - value?: string; - comment?: CommentOption; - separator?: boolean; - } + content: string, + key: string, + options?: { + value?: string; + comment?: CommentOption; + separator?: boolean; + }, ): string; declare namespace json_d_exports { - export { arrayUpsert, packageScriptsUpsert }; + export { arrayUpsert, packageScriptsUpsert }; } declare function arrayUpsert( - data: any, - key: string, - value: any, - options?: { - mode?: 'append' | 'prepend'; - } + data: any, + key: string, + value: any, + options?: { + mode?: "append" | "prepend"; + }, ): void; declare function packageScriptsUpsert( - data: any, - key: string, - value: string, - options?: { - mode?: 'append' | 'prepend'; - } + data: any, + key: string, + value: string, + options?: { + mode?: "append" | "prepend"; + }, ): void; declare namespace index_d_exports$4 { - export { RootWithInstance, addFragment, addSlot, ensureScript }; + export { RootWithInstance, addFragment, addSlot, ensureScript }; } type RootWithInstance = SvelteAst.Root & { - instance: SvelteAst.Script; + instance: SvelteAst.Script; }; declare function ensureScript( - ast: SvelteAst.Root, - options?: { - language?: 'ts' | 'js'; - } + ast: SvelteAst.Root, + options?: { + language?: "ts" | "js"; + }, ): asserts ast is RootWithInstance; declare function addSlot( - ast: SvelteAst.Root, - options: { - svelteVersion: string; - language?: 'ts' | 'js'; - } + ast: SvelteAst.Root, + options: { + svelteVersion: string; + language?: "ts" | "js"; + }, ): void; declare function addFragment( - ast: SvelteAst.Root, - content: string, - options?: { - mode?: 'append' | 'prepend'; - } + ast: SvelteAst.Root, + content: string, + options?: { + mode?: "append" | "prepend"; + }, ): void; type TransformFn = (content: string) => string; type TransformOptions = { - onError?: (error: unknown) => void; + onError?: (error: unknown) => void; }; declare const transforms: { - script( - cb: (file: { - ast: estree.Program; - comments: Comments; - content: string; - js: typeof index_d_exports$3; - }) => void | false, - options?: TransformOptions - ): (content: string) => string; - - svelte( - cb: (file: { - ast: SvelteAst.Root; - content: string; - svelte: typeof index_d_exports$4; - js: typeof index_d_exports$3; - }) => void | false, - options?: TransformOptions - ): (content: string) => string; - - svelteScript( - scriptOptions: { - language: 'ts' | 'js'; - }, - cb: (file: { - ast: RootWithInstance; - content: string; - svelte: typeof index_d_exports$4; - js: typeof index_d_exports$3; - }) => void | false, - options?: TransformOptions - ): TransformFn; - - css( - cb: (file: { - ast: Omit; - content: string; - css: typeof index_d_exports$1; - }) => void | false, - options?: TransformOptions - ): TransformFn; - - json( - cb: (file: { data: T; content: string; json: typeof json_d_exports }) => void | false, - options?: TransformOptions - ): TransformFn; - - yaml( - cb: (file: { data: ReturnType['data']; content: string }) => void | false, - options?: TransformOptions - ): TransformFn; - - toml( - cb: (file: { data: TomlTable; content: string }) => void | false, - options?: TransformOptions - ): TransformFn; - - html( - cb: (file: { - ast: SvelteAst.Fragment; - content: string; - html: typeof index_d_exports$2; - }) => void | false, - options?: TransformOptions - ): TransformFn; - - text(cb: (file: { content: string; text: typeof text_d_exports }) => string | false): TransformFn; + script( + cb: (file: { + ast: estree.Program; + comments: Comments; + content: string; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions, + ): (content: string) => string; + + svelte( + cb: (file: { + ast: SvelteAst.Root; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions, + ): (content: string) => string; + + svelteScript( + scriptOptions: { + language: "ts" | "js"; + }, + cb: (file: { + ast: RootWithInstance; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + css( + cb: (file: { + ast: Omit; + content: string; + css: typeof index_d_exports$1; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + json( + cb: (file: { + data: T; + content: string; + json: typeof json_d_exports; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + yaml( + cb: (file: { + data: ReturnType["data"]; + content: string; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + toml( + cb: (file: { data: TomlTable; content: string }) => void | false, + options?: TransformOptions, + ): TransformFn; + + html( + cb: (file: { + ast: SvelteAst.Fragment; + content: string; + html: typeof index_d_exports$2; + }) => void | false, + options?: TransformOptions, + ): TransformFn; + + text( + cb: (file: { + content: string; + text: typeof text_d_exports; + }) => string | false, + ): TransformFn; }; declare namespace pnpm_d_exports { - export { onlyBuiltDependencies }; + export { onlyBuiltDependencies }; } declare function onlyBuiltDependencies(...packages: string[]): TransformFn; type Version = { - major?: number; - minor?: number; - patch?: number; + major?: number; + minor?: number; + patch?: number; }; declare function splitVersion(str: string): Version; declare function isVersionUnsupportedBelow( - versionStr: string, - belowStr: string + versionStr: string, + belowStr: string, ): boolean | undefined; type Printer = (content: string, alt?: string) => string; declare function createPrinter(...conditions: boolean[]): Printer[]; -declare function sanitizeName(name: string, style: 'package' | 'wrangler'): string; +declare function sanitizeName( + name: string, + style: "package" | "wrangler", +): string; declare const downloadJson: (url: string) => Promise; type Package = { - name: string; - version: string; - dependencies?: Record; - devDependencies?: Record; - bugs?: string; - repository?: { - type: string; - url: string; - }; - keywords?: string[]; - workspaces?: string[]; + name: string; + version: string; + dependencies?: Record; + devDependencies?: Record; + bugs?: string; + repository?: { + type: string; + url: string; + }; + keywords?: string[]; + workspaces?: string[]; }; declare function getPackageJson(cwd: string): { - source: string; - data: Package; - generateCode: () => string; + source: string; + data: Package; + generateCode: () => string; }; declare function readFile(cwd: string, filePath: string): string; declare function fileExists(cwd: string, filePath: string): boolean; -declare function writeFile(cwd: string, filePath: string, content: string): void; +declare function writeFile( + cwd: string, + filePath: string, + content: string, +): void; +/** + * @deprecated Internal to sv — merged into `package.json` by the add-on runner only. Will be removed from the public API in a future version. + */ declare function installPackages( - dependencies: Array<{ - pkg: string; - version: string; - dev: boolean; - }>, - cwd: string + dependencies: Array<{ + pkg: string; + version: string; + dev: boolean; + }>, + cwd: string, ): string; declare const commonFilePaths: { - readonly packageJson: 'package.json'; - readonly svelteConfig: 'svelte.config.js'; - readonly svelteConfigTS: 'svelte.config.ts'; - readonly jsconfig: 'jsconfig.json'; - readonly tsconfig: 'tsconfig.json'; - readonly viteConfig: 'vite.config.js'; - readonly viteConfigTS: 'vite.config.ts'; + readonly packageJson: "package.json"; + readonly svelteConfig: "svelte.config.js"; + readonly svelteConfigTS: "svelte.config.ts"; + readonly jsconfig: "jsconfig.json"; + readonly tsconfig: "tsconfig.json"; + readonly viteConfig: "vite.config.js"; + readonly viteConfigTS: "vite.config.ts"; }; type ColorInput = string | string[]; declare const color: { - addon: (str: ColorInput) => string; - command: (str: ColorInput) => string; - env: (str: ColorInput) => string; - path: (str: ColorInput) => string; - route: (str: ColorInput) => string; - website: (str: ColorInput) => string; - optional: (str: ColorInput) => string; - dim: (str: ColorInput) => string; - success: (str: ColorInput) => string; - warning: (str: ColorInput) => string; - error: (str: ColorInput) => string; - hidden: (str: ColorInput) => string; + addon: (str: ColorInput) => string; + command: (str: ColorInput) => string; + env: (str: ColorInput) => string; + path: (str: ColorInput) => string; + route: (str: ColorInput) => string; + website: (str: ColorInput) => string; + optional: (str: ColorInput) => string; + dim: (str: ColorInput) => string; + success: (str: ColorInput) => string; + warning: (str: ColorInput) => string; + error: (str: ColorInput) => string; + hidden: (str: ColorInput) => string; }; -declare function resolveCommandArray(agent: Agent, command: Command, args: string[]): string[]; +declare function resolveCommandArray( + agent: Agent, + command: Command, + args: string[], +): string[]; declare const parse: { - css: typeof parseCss; - html: typeof parseHtml; - json: typeof parseJson; - script: typeof parseScript; - svelte: typeof parseSvelte; - toml: typeof parseToml; - yaml: typeof parseYaml; + css: typeof parseCss; + html: typeof parseHtml; + json: typeof parseJson; + script: typeof parseScript; + svelte: typeof parseSvelte; + toml: typeof parseToml; + yaml: typeof parseYaml; }; export { - AGENTS, - type AgentName, - type estree as AstTypes, - COMMANDS, - type Comments, - type Package, - type SvelteAst, - type TransformFn, - index_d_exports as Walker, - color, - commonFilePaths, - constructCommand, - createPrinter, - index_d_exports$1 as css, - dedent, - detect, - downloadJson, - fileExists, - getPackageJson, - index_d_exports$2 as html, - installPackages, - isVersionUnsupportedBelow, - index_d_exports$3 as js, - json_d_exports as json, - parse, - pnpm_d_exports as pnpm, - readFile, - resolveCommand, - resolveCommandArray, - sanitizeName, - splitVersion, - index_d_exports$4 as svelte, - text_d_exports as text, - transforms, - writeFile + AGENTS, + type AgentName, + type estree as AstTypes, + COMMANDS, + type Comments, + type Package, + type SvelteAst, + type TransformFn, + index_d_exports as Walker, + color, + commonFilePaths, + constructCommand, + createPrinter, + index_d_exports$1 as css, + dedent, + detect, + downloadJson, + fileExists, + getPackageJson, + index_d_exports$2 as html, + installPackages, + isVersionUnsupportedBelow, + index_d_exports$3 as js, + json_d_exports as json, + parse, + pnpm_d_exports as pnpm, + readFile, + resolveCommand, + resolveCommandArray, + sanitizeName, + splitVersion, + index_d_exports$4 as svelte, + text_d_exports as text, + transforms, + writeFile, }; ``` diff --git a/packages/sv-utils/src/files.ts b/packages/sv-utils/src/files.ts index 4dd22c359..8212a637b 100644 --- a/packages/sv-utils/src/files.ts +++ b/packages/sv-utils/src/files.ts @@ -58,6 +58,9 @@ export function writeFile(cwd: string, filePath: string, content: string): void fs.writeFileSync(fullFilePath, content, 'utf8'); } +/** + * @deprecated Internal to sv — merged into `package.json` by the add-on runner only. Will be removed from the public API in a future version. + */ export function installPackages( dependencies: Array<{ pkg: string; version: string; dev: boolean }>, cwd: string diff --git a/packages/sv-utils/src/index.ts b/packages/sv-utils/src/index.ts index 64c7b21e2..153f2bc05 100644 --- a/packages/sv-utils/src/index.ts +++ b/packages/sv-utils/src/index.ts @@ -85,12 +85,14 @@ export { commonFilePaths, fileExists, getPackageJson, - installPackages, readFile, writeFile, type Package } from './files.ts'; +/** @deprecated Internal to sv — will be removed from the public API in a future version. */ +export { installPackages } from './files.ts'; + // Terminal styling export { color } from './color.ts'; diff --git a/packages/sv/api-surface-testing.md b/packages/sv/api-surface-testing.md index 8d87dae41..f9c1c9a71 100644 --- a/packages/sv/api-surface-testing.md +++ b/packages/sv/api-surface-testing.md @@ -3,108 +3,123 @@ ```ts -type ProjectVariant = 'kit-js' | 'kit-ts' | 'vite-js' | 'vite-ts'; +type ProjectVariant = "kit-js" | "kit-ts" | "vite-js" | "vite-ts"; declare const variants: ProjectVariant[]; type CreateProject = (options: { - testId: string; - variant: ProjectVariant; - clean?: boolean; + testId: string; + variant: ProjectVariant; + clean?: boolean; }) => string; type SetupOptions = { - cwd: string; - variants: readonly ProjectVariant[]; - clean?: boolean; + cwd: string; + variants: readonly ProjectVariant[]; + clean?: boolean; }; +/** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ declare function setup({ cwd, clean, variants }: SetupOptions): { - templatesDir: string; + templatesDir: string; }; type CreateOptions = { - cwd: string; - testName: string; - templatesDir: string; + cwd: string; + testName: string; + templatesDir: string; }; -declare function createProject({ cwd, testName, templatesDir }: CreateOptions): CreateProject; +/** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ +declare function createProject({ + cwd, + testName, + templatesDir, +}: CreateOptions): CreateProject; type PreviewOptions = { - cwd: string; - command?: string; + cwd: string; + command?: string; }; +/** @deprecated Internal helper used by `prepareServer` - will be removed from public API in a future version. */ declare function startPreview({ cwd, command }: PreviewOptions): Promise<{ - url: string; - close: () => Promise; + url: string; + close: () => Promise; }>; -declare module 'vitest' { - interface ProvidedContext { - testDir: string; - templatesDir: string; - variants: ProjectVariant[]; - } +declare module "vitest" { + interface ProvidedContext { + testDir: string; + templatesDir: string; + variants: ProjectVariant[]; + } } declare function setupGlobal({ - TEST_DIR, - pre, - post + TEST_DIR, + pre, + post, }: { - TEST_DIR: string; - pre?: () => Promise; - post?: () => Promise; + TEST_DIR: string; + pre?: () => Promise; + post?: () => Promise; }): ({ provide }: TestProject) => Promise<() => Promise>; type Fixtures = { - page: Page; - cwd(addonTestCase: AddonTestCase): string; + page: Page; + cwd(addonTestCase: AddonTestCase): string; }; type AddonTestCase = { - variant: ProjectVariant; - kind: { - type: string; - options: OptionMap; - }; + variant: ProjectVariant; + kind: { + type: string; + options: OptionMap; + }; }; type SetupTestOptions = { - kinds: Array['kind']>; - filter?: (addonTestCase: AddonTestCase) => boolean; - browser?: boolean; - preAdd?: (o: { addonTestCase: AddonTestCase; cwd: string }) => Promise | void; + kinds: Array["kind"]>; + filter?: (addonTestCase: AddonTestCase) => boolean; + browser?: boolean; + preAdd?: (o: { + addonTestCase: AddonTestCase; + cwd: string; + }) => Promise | void; }; type PrepareServerOptions = { - cwd: string; - page: Page; - buildCommand?: string; - previewCommand?: string; + cwd: string; + page: Page; + buildCommand?: string; + previewCommand?: string; }; type PrepareServerReturn = { - url: string; - close: () => Promise; + url: string; + close: () => Promise; }; declare function prepareServer({ - cwd, - page, - buildCommand, - previewCommand + cwd, + page, + buildCommand, + previewCommand, }: PrepareServerOptions): Promise; -type VitestContext = Pick; -declare function createSetupTest(vitest: VitestContext): ( - addons: Addons, - options?: SetupTestOptions +type VitestContext = Pick< + typeof vitest, + "inject" | "test" | "beforeAll" | "beforeEach" +>; +declare function createSetupTest(vitest: VitestContext): < + Addons extends AddonMap, +>( + addons: Addons, + options?: SetupTestOptions, ) => { - test: vitest.TestAPI; - testCases: Array>; - prepareServer: typeof prepareServer; + test: vitest.TestAPI; + testCases: Array>; + prepareServer: typeof prepareServer; }; export { - AddonTestCase, - CreateProject, - Fixtures, - PrepareServerOptions, - PrepareServerReturn, - ProjectVariant, - SetupTestOptions, - VitestContext, - createProject, - createSetupTest, - prepareServer, - setup, - setupGlobal, - startPreview, - variants + AddonTestCase, + CreateProject, + Fixtures, + PrepareServerOptions, + PrepareServerReturn, + ProjectVariant, + SetupTestOptions, + VitestContext, + createProject, + createSetupTest, + prepareServer, + setup, + setupGlobal, + startPreview, + variants, }; ``` diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md index 3efb6b89c..16427459b 100644 --- a/packages/sv/api-surface.md +++ b/packages/sv/api-surface.md @@ -5,65 +5,68 @@ ```ts type TemplateType = (typeof templateTypes)[number]; type LanguageType = (typeof languageTypes)[number]; -declare const templateTypes: readonly ['minimal', 'demo', 'library', 'addon', 'svelte']; -declare const languageTypes: readonly ['typescript', 'checkjs', 'none']; +declare const templateTypes: readonly [ + "minimal", + "demo", + "library", + "addon", + "svelte", +]; +declare const languageTypes: readonly ["typescript", "checkjs", "none"]; type Options = { - name: string; - template: TemplateType; - types: LanguageType; + cwd: string; + name: string; + template: TemplateType; + types: LanguageType; }; -declare function create(cwd: string, options: Options): void; +/** @deprecated Use `create({ cwd, name, template, types })` instead. */ +declare function create(cwd: string, options: Omit): void; +declare function create(options: Options): void; +/** @deprecated Unused type, will be removed in a future version. */ type FileEditor = Workspace & { - content: string; + content: string; }; +/** @deprecated Unused type, will be removed in a future version. */ type FileType = { - name: (options: Workspace) => string; - condition?: ConditionDefinition; - content: (editor: FileEditor) => string; + name: (options: Workspace) => string; + condition?: ConditionDefinition; + content: (editor: FileEditor) => string; }; export { - Addon, - AddonDefinition, - AddonInput, - type AddonMap, - AddonReference, - AddonResult, - AddonSource, - BaseQuestion, - BooleanQuestion, - ConditionDefinition, - ConfiguredAddon, - FileEditor, - FileType, - type InstallOptions, - type LanguageType, - LoadedAddon, - MultiSelectQuestion, - NumberQuestion, - OptionBuilder, - OptionDefinition, - type OptionMap, - OptionValues, - PackageDefinition, - PreparedAddon, - Question, - Scripts, - SelectQuestion, - SetupResult, - StringQuestion, - SvApi, - type TemplateType, - TestDefinition, - Tests, - Verification, - Workspace, - WorkspaceOptions, - add, - create, - createWorkspace, - defineAddon, - defineAddonOptions, - getErrorHint, - officialAddons + type Addon, + type AddonDefinition, + type AddonInput, + type AddonMap, + type AddonReference, + type AddonResult, + type AddonSource, + type BaseQuestion, + type BooleanQuestion, + type ConfiguredAddon, + type FileEditor, + type FileType, + type InstallOptions, + type LanguageType, + type LoadedAddon, + type MultiSelectQuestion, + type NumberQuestion, + type OptionBuilder, + type OptionDefinition, + type OptionMap, + type OptionValues, + type PreparedAddon, + type Question, + type SelectQuestion, + type SetupResult, + type StringQuestion, + type SvApi, + type TemplateType, + type Workspace, + type WorkspaceOptions, + add, + create, + defineAddon, + defineAddonOptions, + officialAddons, }; ``` diff --git a/packages/sv/src/cli/create.ts b/packages/sv/src/cli/create.ts index a2cf4d388..dfaf86849 100644 --- a/packages/sv/src/cli/create.ts +++ b/packages/sv/src/cli/create.ts @@ -313,7 +313,8 @@ async function createProject(cwd: ProjectPath, options: Options) { answers = result.answers; } - createKit(projectPath, { + createKit({ + cwd: projectPath, name: projectName, template, types: language diff --git a/packages/sv/src/core/engine.ts b/packages/sv/src/core/engine.ts index 8a8be6df1..4e825d36b 100644 --- a/packages/sv/src/core/engine.ts +++ b/packages/sv/src/core/engine.ts @@ -4,7 +4,7 @@ import { resolveCommand, type AgentName, fileExists, - installPackages, + installPackages as updatePackages, readFile, writeFile } from '@sveltejs/sv-utils'; @@ -242,7 +242,7 @@ async function runAddon({ addon, loaded, multiple, workspace, workspaceOptions } } if (cancels.length === 0) { - const pkgPath = installPackages(dependencies, workspace.cwd); + const pkgPath = updatePackages(dependencies, workspace.cwd); files.add(pkgPath); } diff --git a/packages/sv/src/core/processors.ts b/packages/sv/src/core/processors.ts index bde28a7c1..a56240d15 100644 --- a/packages/sv/src/core/processors.ts +++ b/packages/sv/src/core/processors.ts @@ -1,8 +1,10 @@ import type { ConditionDefinition } from './config.ts'; import type { Workspace } from './workspace.ts'; +/** @deprecated Unused type, will be removed in a future version. */ export type FileEditor = Workspace & { content: string }; +/** @deprecated Unused type, will be removed in a future version. */ export type FileType = { name: (options: Workspace) => string; condition?: ConditionDefinition; diff --git a/packages/sv/src/core/workspace.ts b/packages/sv/src/core/workspace.ts index 092d75627..a31c3ddd6 100644 --- a/packages/sv/src/core/workspace.ts +++ b/packages/sv/src/core/workspace.ts @@ -37,11 +37,16 @@ export type Workspace = { package: 'package.json'; gitignore: '.gitignore'; + /** @deprecated Addon-specific path - use the string literal '.prettierignore' directly. Will be removed in a future version. */ prettierignore: '.prettierignore'; + /** @deprecated Addon-specific path - use the string literal '.prettierrc' directly. Will be removed in a future version. */ prettierrc: '.prettierrc'; + /** @deprecated Addon-specific path - use the string literal 'eslint.config.js' directly. Will be removed in a future version. */ eslintConfig: 'eslint.config.js'; + /** @deprecated Addon-specific path - use the string literal '.vscode/settings.json' directly. Will be removed in a future version. */ vscodeSettings: '.vscode/settings.json'; + /** @deprecated Addon-specific path - use the string literal '.vscode/extensions.json' directly. Will be removed in a future version. */ vscodeExtensions: '.vscode/extensions.json'; /** Get the relative path between two files */ diff --git a/packages/sv/src/create/index.ts b/packages/sv/src/create/index.ts index 5a2947cbe..5ee524d0c 100644 --- a/packages/sv/src/create/index.ts +++ b/packages/sv/src/create/index.ts @@ -11,6 +11,7 @@ const templateTypes = ['minimal', 'demo', 'library', 'addon', 'svelte'] as const const languageTypes = ['typescript', 'checkjs', 'none'] as const; export type Options = { + cwd: string; name: string; template: TemplateType; types: LanguageType; @@ -32,7 +33,23 @@ export type Common = { }>; }; -export function create(cwd: string, options: Options): void { +/** @deprecated Use `create({ cwd, name, template, types })` instead. */ +export function create(cwd: string, options: Omit): void; +export function create(options: Options): void; +export function create( + cwdOrOptions: string | Options, + legacyOptions?: Omit +): void { + let cwd: string; + let options: Omit; + if (typeof cwdOrOptions === 'string') { + cwd = cwdOrOptions; + options = legacyOptions!; + } else { + cwd = cwdOrOptions.cwd; + options = cwdOrOptions; + } + mkdirp(cwd); write_template_files(options.template, options.types, options.name, cwd); @@ -76,7 +93,7 @@ function write_template_files(template: string, types: LanguageType, name: strin }); } -function write_common_files(cwd: string, options: Options, name: string) { +function write_common_files(cwd: string, options: Omit, name: string) { const files = getSharedFiles(); const pkg_file = path.join(cwd, commonFilePaths.packageJson); @@ -105,7 +122,7 @@ function write_common_files(cwd: string, options: Options, name: string) { fs.writeFileSync(pkg_file, JSON.stringify(pkg, null, '\t') + '\n'); } -function matches_condition(condition: Condition, options: Options) { +function matches_condition(condition: Condition, options: Omit) { if (templateTypes.includes(condition as TemplateType)) { return options.template === condition; } diff --git a/packages/sv/src/create/tests/check.ts b/packages/sv/src/create/tests/check.ts index e00b3c33f..c214a375b 100644 --- a/packages/sv/src/create/tests/check.ts +++ b/packages/sv/src/create/tests/check.ts @@ -42,7 +42,7 @@ for (const template of templates.filter((t) => t !== 'addon')) { const cwd = path.join(test_workspace_dir, `${template}-${types}`); fs.rmSync(cwd, { recursive: true, force: true }); - create(cwd, { name: `create-svelte-test-${template}-${types}`, template, types }); + create({ cwd, name: `create-svelte-test-${template}-${types}`, template, types }); await add({ cwd, addons: { eslint: officialAddons.eslint }, options: { eslint: {} } }); const pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf-8')); diff --git a/packages/sv/src/create/tests/playground.ts b/packages/sv/src/create/tests/playground.ts index fbc79b5d1..5d7778de0 100644 --- a/packages/sv/src/create/tests/playground.ts +++ b/packages/sv/src/create/tests/playground.ts @@ -153,7 +153,8 @@ test('real world download and convert playground async', async () => { fs.rmSync(directory, { recursive: true }); } - create(directory, { + create({ + cwd: directory, name: 'real-world-playground', template: 'minimal', types: 'typescript' @@ -204,7 +205,8 @@ test('real world download and convert playground without async', async () => { fs.rmSync(directory, { recursive: true }); } - create(directory, { + create({ + cwd: directory, name: 'real-world-playground-old', template: 'minimal', types: 'typescript' diff --git a/packages/sv/src/index.ts b/packages/sv/src/index.ts index 874abb260..6b5c64d4a 100644 --- a/packages/sv/src/index.ts +++ b/packages/sv/src/index.ts @@ -4,7 +4,39 @@ export type { AddonMap, InstallOptions, OptionMap } from './core/engine.ts'; export { officialAddons } from './addons/index.ts'; // Addon authoring API export { defineAddon, defineAddonOptions } from './core/config.ts'; -export type * from './core/processors.ts'; -export type * from './core/options.ts'; -export type * from './core/config.ts'; -export type * from './core/workspace.ts'; + +// options.ts - question types for addon options +export type { + Question, + OptionDefinition, + OptionValues, + BooleanQuestion, + StringQuestion, + NumberQuestion, + SelectQuestion, + MultiSelectQuestion, + BaseQuestion +} from './core/options.ts'; + +// config.ts - addon definition and pipeline types +export type { + Addon, + SvApi, + AddonDefinition, + SetupResult, + OptionBuilder, + AddonInput, + AddonSource, + AddonReference, + LoadedAddon, + PreparedAddon, + ConfiguredAddon, + AddonResult +} from './core/config.ts'; + +// workspace.ts +export type { Workspace, WorkspaceOptions } from './core/workspace.ts'; + +// processors.ts - deprecated, will be removed +/** @deprecated Unused type, will be removed in a future version. */ +export type { FileEditor, FileType } from './core/processors.ts'; diff --git a/packages/sv/src/testing.ts b/packages/sv/src/testing.ts index 35d624cce..02d6c14b2 100644 --- a/packages/sv/src/testing.ts +++ b/packages/sv/src/testing.ts @@ -28,6 +28,7 @@ type SetupOptions = { /** @default false */ clean?: boolean; }; +/** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ export function setup({ cwd, clean = false, variants }: SetupOptions): { templatesDir: string } { const workingDir = path.resolve(cwd); if (clean && fs.existsSync(workingDir)) { @@ -42,13 +43,13 @@ export function setup({ cwd, clean = false, variants }: SetupOptions): { templat if (fs.existsSync(templatePath)) continue; if (variant === 'kit-js') { - create(templatePath, { name: variant, template: 'minimal', types: 'checkjs' }); + create({ cwd: templatePath, name: variant, template: 'minimal', types: 'checkjs' }); } else if (variant === 'kit-ts') { - create(templatePath, { name: variant, template: 'minimal', types: 'typescript' }); + create({ cwd: templatePath, name: variant, template: 'minimal', types: 'typescript' }); } else if (variant === 'vite-js') { - create(templatePath, { name: variant, template: 'svelte', types: 'none' }); + create({ cwd: templatePath, name: variant, template: 'svelte', types: 'none' }); } else if (variant === 'vite-ts') { - create(templatePath, { name: variant, template: 'svelte', types: 'typescript' }); + create({ cwd: templatePath, name: variant, template: 'svelte', types: 'typescript' }); } else { throw new Error(`Unknown project variant: ${variant}`); } @@ -58,6 +59,7 @@ export function setup({ cwd, clean = false, variants }: SetupOptions): { templat } type CreateOptions = { cwd: string; testName: string; templatesDir: string }; +/** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ export function createProject({ cwd, testName, templatesDir }: CreateOptions): CreateProject { // create the reference dir const testDir = path.resolve(cwd, testName); @@ -74,6 +76,7 @@ export function createProject({ cwd, testName, templatesDir }: CreateOptions): C } type PreviewOptions = { cwd: string; command?: string }; +/** @deprecated Internal helper used by `prepareServer` - will be removed from public API in a future version. */ export async function startPreview({ cwd, command = 'npm run preview' From b5adf57149fe77c8e77a267d56c0857edb28dd3c Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 12:47:59 +0200 Subject: [PATCH 12/31] refactor: loadFile/saveFile/loadPackageJson; trim workspace addon paths - sv-utils: add loadFile, saveFile, loadPackageJson; deprecate readFile, writeFile, getPackageJson; remove installPackages (logic lives in sv engine). - sv: inline updatePackages in engine; use new helpers; drop deprecated workspace.file paths; addons use string literals; remove stale @deprecated on processors/create exports. - Regenerate api-surface snapshots. Made-with: Cursor --- packages/sv-utils/api-surface.md | 43 +++++----- packages/sv-utils/src/files.ts | 92 ++++++++------------- packages/sv-utils/src/index.ts | 16 ++-- packages/sv/api-surface.md | 3 - packages/sv/src/addons/drizzle.ts | 2 +- packages/sv/src/addons/eslint.ts | 6 +- packages/sv/src/addons/prettier.ts | 8 +- packages/sv/src/addons/sveltekit-adapter.ts | 4 +- packages/sv/src/addons/tailwindcss.ts | 6 +- packages/sv/src/cli/create.ts | 4 +- packages/sv/src/core/engine.ts | 43 ++++++++-- packages/sv/src/core/processors.ts | 2 - packages/sv/src/core/workspace.ts | 27 ++---- packages/sv/src/create/index.ts | 1 - packages/sv/src/index.ts | 2 - 15 files changed, 121 insertions(+), 138 deletions(-) diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index 92f5bbc85..655615480 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -1711,29 +1711,6 @@ type Package = { keywords?: string[]; workspaces?: string[]; }; -declare function getPackageJson(cwd: string): { - source: string; - data: Package; - generateCode: () => string; -}; -declare function readFile(cwd: string, filePath: string): string; -declare function fileExists(cwd: string, filePath: string): boolean; -declare function writeFile( - cwd: string, - filePath: string, - content: string, -): void; -/** - * @deprecated Internal to sv — merged into `package.json` by the add-on runner only. Will be removed from the public API in a future version. - */ -declare function installPackages( - dependencies: Array<{ - pkg: string; - version: string; - dev: boolean; - }>, - cwd: string, -): string; declare const commonFilePaths: { readonly packageJson: "package.json"; readonly svelteConfig: "svelte.config.js"; @@ -1743,6 +1720,22 @@ declare const commonFilePaths: { readonly viteConfig: "vite.config.js"; readonly viteConfigTS: "vite.config.ts"; }; +declare function fileExists(cwd: string, filePath: string): boolean; + +declare function loadFile(cwd: string, filePath: string): string; + +declare function saveFile(cwd: string, filePath: string, content: string): void; +declare function loadPackageJson(cwd: string): { + source: string; + data: Package; + generateCode: () => string; +}; +/** @deprecated Use {@link loadFile} instead. */ +declare const readFile: typeof loadFile; +/** @deprecated Use {@link saveFile} instead. */ +declare const writeFile: typeof saveFile; +/** @deprecated Use {@link loadPackageJson} instead. */ +declare const getPackageJson: typeof loadPackageJson; type ColorInput = string | string[]; declare const color: { addon: (str: ColorInput) => string; @@ -1795,16 +1788,18 @@ export { fileExists, getPackageJson, index_d_exports$2 as html, - installPackages, isVersionUnsupportedBelow, index_d_exports$3 as js, json_d_exports as json, + loadFile, + loadPackageJson, parse, pnpm_d_exports as pnpm, readFile, resolveCommand, resolveCommandArray, sanitizeName, + saveFile, splitVersion, index_d_exports$4 as svelte, text_d_exports as text, diff --git a/packages/sv-utils/src/files.ts b/packages/sv-utils/src/files.ts index 8212a637b..540e80602 100644 --- a/packages/sv-utils/src/files.ts +++ b/packages/sv-utils/src/files.ts @@ -13,22 +13,23 @@ export type Package = { workspaces?: string[]; }; -export function getPackageJson(cwd: string): { - source: string; - data: Package; - generateCode: () => string; -} { - const packageText = readFile(cwd, commonFilePaths.packageJson); - if (!packageText) { - const pkgPath = path.join(cwd, commonFilePaths.packageJson); - throw new Error(`Invalid workspace: missing '${pkgPath}'`); - } +export const commonFilePaths = { + packageJson: 'package.json', + svelteConfig: 'svelte.config.js', + svelteConfigTS: 'svelte.config.ts', + jsconfig: 'jsconfig.json', + tsconfig: 'tsconfig.json', + viteConfig: 'vite.config.js', + viteConfigTS: 'vite.config.ts' +} as const; - const { data, generateCode } = parseJson(packageText); - return { source: packageText, data: data as Package, generateCode }; +export function fileExists(cwd: string, filePath: string): boolean { + const fullFilePath = path.resolve(cwd, filePath); + return fs.existsSync(fullFilePath); } -export function readFile(cwd: string, filePath: string): string { +/** Synchronous load of a workspace-relative file as UTF-8 text; missing files yield `''`. */ +export function loadFile(cwd: string, filePath: string): string { const fullFilePath = path.resolve(cwd, filePath); if (!fileExists(cwd, filePath)) { @@ -40,12 +41,8 @@ export function readFile(cwd: string, filePath: string): string { return text; } -export function fileExists(cwd: string, filePath: string): boolean { - const fullFilePath = path.resolve(cwd, filePath); - return fs.existsSync(fullFilePath); -} - -export function writeFile(cwd: string, filePath: string, content: string): void { +/** Synchronous write of a workspace-relative file (creates parent dirs). */ +export function saveFile(cwd: string, filePath: string, content: string): void { const fullFilePath = path.resolve(cwd, filePath); const fullDirectoryPath = path.dirname(fullFilePath); @@ -58,47 +55,26 @@ export function writeFile(cwd: string, filePath: string, content: string): void fs.writeFileSync(fullFilePath, content, 'utf8'); } -/** - * @deprecated Internal to sv — merged into `package.json` by the add-on runner only. Will be removed from the public API in a future version. - */ -export function installPackages( - dependencies: Array<{ pkg: string; version: string; dev: boolean }>, - cwd: string -): string { - const { data, generateCode } = getPackageJson(cwd); - - for (const dependency of dependencies) { - if (dependency.dev) { - data.devDependencies ??= {}; - data.devDependencies[dependency.pkg] = dependency.version; - } else { - data.dependencies ??= {}; - data.dependencies[dependency.pkg] = dependency.version; - } +export function loadPackageJson(cwd: string): { + source: string; + data: Package; + generateCode: () => string; +} { + const packageText = loadFile(cwd, commonFilePaths.packageJson); + if (!packageText) { + const pkgPath = path.join(cwd, commonFilePaths.packageJson); + throw new Error(`Invalid workspace: missing '${pkgPath}'`); } - if (data.dependencies) data.dependencies = alphabetizeProperties(data.dependencies); - if (data.devDependencies) data.devDependencies = alphabetizeProperties(data.devDependencies); - - writeFile(cwd, commonFilePaths.packageJson, generateCode()); - return commonFilePaths.packageJson; + const { data, generateCode } = parseJson(packageText); + return { source: packageText, data: data as Package, generateCode }; } -function alphabetizeProperties(obj: Record) { - const orderedObj: Record = {}; - const sortedEntries = Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)); - for (const [key, value] of sortedEntries) { - orderedObj[key] = value; - } - return orderedObj; -} +/** @deprecated Use {@link loadFile} instead. */ +export const readFile: typeof loadFile = loadFile; -export const commonFilePaths = { - packageJson: 'package.json', - svelteConfig: 'svelte.config.js', - svelteConfigTS: 'svelte.config.ts', - jsconfig: 'jsconfig.json', - tsconfig: 'tsconfig.json', - viteConfig: 'vite.config.js', - viteConfigTS: 'vite.config.ts' -} as const; +/** @deprecated Use {@link saveFile} instead. */ +export const writeFile: typeof saveFile = saveFile; + +/** @deprecated Use {@link loadPackageJson} instead. */ +export const getPackageJson: typeof loadPackageJson = loadPackageJson; diff --git a/packages/sv-utils/src/index.ts b/packages/sv-utils/src/index.ts index 153f2bc05..b87fbf029 100644 --- a/packages/sv-utils/src/index.ts +++ b/packages/sv-utils/src/index.ts @@ -80,18 +80,22 @@ export { createPrinter } from './utils.ts'; export { sanitizeName } from './sanitize.ts'; export { downloadJson } from './downloadJson.ts'; -// File system helpers +// File system helpers (sync, workspace-relative paths) export { commonFilePaths, fileExists, - getPackageJson, - readFile, - writeFile, + loadFile, + loadPackageJson, + saveFile, type Package } from './files.ts'; -/** @deprecated Internal to sv — will be removed from the public API in a future version. */ -export { installPackages } from './files.ts'; +/** @deprecated Use {@link loadFile} instead. */ +export { readFile } from './files.ts'; +/** @deprecated Use {@link saveFile} instead. */ +export { writeFile } from './files.ts'; +/** @deprecated Use {@link loadPackageJson} instead. */ +export { getPackageJson } from './files.ts'; // Terminal styling export { color } from './color.ts'; diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md index 16427459b..f9ccdfbd9 100644 --- a/packages/sv/api-surface.md +++ b/packages/sv/api-surface.md @@ -19,14 +19,11 @@ type Options = { template: TemplateType; types: LanguageType; }; -/** @deprecated Use `create({ cwd, name, template, types })` instead. */ declare function create(cwd: string, options: Omit): void; declare function create(options: Options): void; -/** @deprecated Unused type, will be removed in a future version. */ type FileEditor = Workspace & { content: string; }; -/** @deprecated Unused type, will be removed in a future version. */ type FileType = { name: (options: Workspace) => string; condition?: ConditionDefinition; diff --git a/packages/sv/src/addons/drizzle.ts b/packages/sv/src/addons/drizzle.ts index 756a08ba2..b710343b1 100644 --- a/packages/sv/src/addons/drizzle.ts +++ b/packages/sv/src/addons/drizzle.ts @@ -219,7 +219,7 @@ export default defineAddon({ const hasPrettier = Boolean(dependencyVersion('prettier')); if (hasPrettier) { sv.file( - file.prettierignore, + '.prettierignore', transforms.text(({ content, text }) => text.upsert(content, '/drizzle/')) ); } diff --git a/packages/sv/src/addons/eslint.ts b/packages/sv/src/addons/eslint.ts index 58b1d00a4..4d6197676 100644 --- a/packages/sv/src/addons/eslint.ts +++ b/packages/sv/src/addons/eslint.ts @@ -31,7 +31,7 @@ export default defineAddon({ ); sv.file( - file.eslintConfig, + 'eslint.config.js', transforms.script(({ ast, comments, js }) => { const eslintConfigs: Array = []; js.imports.addDefault(ast, { from: './svelte.config.js', as: 'svelteConfig' }); @@ -156,14 +156,14 @@ export default defineAddon({ ); sv.file( - file.vscodeExtensions, + '.vscode/extensions.json', transforms.json(({ data, json }) => { json.arrayUpsert(data, 'recommendations', 'dbaeumer.vscode-eslint'); }) ); if (prettierInstalled) { - sv.file(file.eslintConfig, addEslintConfigPrettier); + sv.file('eslint.config.js', addEslintConfigPrettier); } } }); diff --git a/packages/sv/src/addons/prettier.ts b/packages/sv/src/addons/prettier.ts index eea8f1252..69629f2cc 100644 --- a/packages/sv/src/addons/prettier.ts +++ b/packages/sv/src/addons/prettier.ts @@ -16,7 +16,7 @@ export default defineAddon({ sv.devDependency('prettier-plugin-svelte', '^3.4.1'); sv.file( - file.prettierignore, + '.prettierignore', transforms.text(({ content }) => { if (content) return false; return dedent` @@ -34,7 +34,7 @@ export default defineAddon({ ); sv.file( - file.prettierrc, + '.prettierrc', transforms.json( ({ data, json }) => { if (Object.keys(data).length === 0) { @@ -82,7 +82,7 @@ export default defineAddon({ ); sv.file( - file.vscodeExtensions, + '.vscode/extensions.json', transforms.json(({ data, json }) => { json.arrayUpsert(data, 'recommendations', 'esbenp.prettier-vscode'); }) @@ -98,7 +98,7 @@ export default defineAddon({ if (eslintInstalled) { sv.devDependency('eslint-config-prettier', '^10.1.8'); - sv.file(file.eslintConfig, addEslintConfigPrettier); + sv.file('eslint.config.js', addEslintConfigPrettier); } } }); diff --git a/packages/sv/src/addons/sveltekit-adapter.ts b/packages/sv/src/addons/sveltekit-adapter.ts index dd3f9a3a2..739e89896 100644 --- a/packages/sv/src/addons/sveltekit-adapter.ts +++ b/packages/sv/src/addons/sveltekit-adapter.ts @@ -4,7 +4,7 @@ import { text, transforms, fileExists, - getPackageJson, + loadPackageJson, sanitizeName } from '@sveltejs/sv-utils'; import { defineAddon, defineAddonOptions } from '../core/config.ts'; @@ -140,7 +140,7 @@ export default defineAddon({ } if (!data.name) { - const pkg = getPackageJson(cwd); + const pkg = loadPackageJson(cwd); data.name = sanitizeName(pkg.data.name, 'wrangler'); } diff --git a/packages/sv/src/addons/tailwindcss.ts b/packages/sv/src/addons/tailwindcss.ts index 151d0fe66..2755ea392 100644 --- a/packages/sv/src/addons/tailwindcss.ts +++ b/packages/sv/src/addons/tailwindcss.ts @@ -108,7 +108,7 @@ export default defineAddon({ } sv.file( - file.vscodeSettings, + '.vscode/settings.json', transforms.json(({ data }) => { data['files.associations'] ??= {}; data['files.associations']['*.css'] = 'tailwindcss'; @@ -116,7 +116,7 @@ export default defineAddon({ ); sv.file( - file.vscodeExtensions, + '.vscode/extensions.json', transforms.json(({ data, json }) => { json.arrayUpsert(data, 'recommendations', 'bradlc.vscode-tailwindcss'); }) @@ -124,7 +124,7 @@ export default defineAddon({ if (prettierInstalled) { sv.file( - file.prettierrc, + '.prettierrc', transforms.json(({ data, json }) => { json.arrayUpsert(data, 'plugins', 'prettier-plugin-tailwindcss'); data.tailwindStylesheet ??= file.getRelative({ to: file.stylesheet }); diff --git a/packages/sv/src/cli/create.ts b/packages/sv/src/cli/create.ts index dfaf86849..b3e92da45 100644 --- a/packages/sv/src/cli/create.ts +++ b/packages/sv/src/cli/create.ts @@ -1,5 +1,5 @@ import * as p from '@clack/prompts'; -import { color, resolveCommandArray, commonFilePaths, getPackageJson } from '@sveltejs/sv-utils'; +import { color, resolveCommandArray, commonFilePaths, loadPackageJson } from '@sveltejs/sv-utils'; import { Command, Option } from 'commander'; import fs from 'node:fs'; import path from 'node:path'; @@ -454,7 +454,7 @@ export async function createVirtualWorkspace({ // Let's read the package.json of the template we will use and add the dependencies to the override const templatePackageJsonPath = dist(`templates/${template}`); - const { data: packageJson } = getPackageJson(templatePackageJsonPath); + const { data: packageJson } = loadPackageJson(templatePackageJsonPath); override.dependencies = { ...packageJson.devDependencies, ...packageJson.dependencies, diff --git a/packages/sv/src/core/engine.ts b/packages/sv/src/core/engine.ts index 4e825d36b..407fbdae3 100644 --- a/packages/sv/src/core/engine.ts +++ b/packages/sv/src/core/engine.ts @@ -1,12 +1,13 @@ import * as p from '@clack/prompts'; import { color, + commonFilePaths, resolveCommand, type AgentName, fileExists, - installPackages as updatePackages, - readFile, - writeFile + loadFile, + loadPackageJson, + saveFile } from '@sveltejs/sv-utils'; import { NonZeroExitError, exec } from 'tinyexec'; import { createLoadedAddon } from '../cli/add.ts'; @@ -22,6 +23,38 @@ import { import { TESTING } from './env.ts'; import { createWorkspace, type Workspace } from './workspace.ts'; +function alphabetizePackageJsonDependencies(obj: Record) { + const ordered: Record = {}; + for (const [key, value] of Object.entries(obj).sort(([a], [b]) => a.localeCompare(b))) { + ordered[key] = value; + } + return ordered; +} + +function updatePackages( + dependencies: Array<{ pkg: string; version: string; dev: boolean }>, + cwd: string +): string { + const { data, generateCode } = loadPackageJson(cwd); + + for (const dependency of dependencies) { + if (dependency.dev) { + data.devDependencies ??= {}; + data.devDependencies[dependency.pkg] = dependency.version; + } else { + data.dependencies ??= {}; + data.dependencies[dependency.pkg] = dependency.version; + } + } + + if (data.dependencies) data.dependencies = alphabetizePackageJsonDependencies(data.dependencies); + if (data.devDependencies) + data.devDependencies = alphabetizePackageJsonDependencies(data.devDependencies); + + saveFile(cwd, commonFilePaths.packageJson, generateCode()); + return commonFilePaths.packageJson; +} + export type InstallOptions = { cwd: string; addons: Addons; @@ -175,11 +208,11 @@ async function runAddon({ addon, loaded, multiple, workspace, workspaceOptions } const sv: SvApi = { file: (path, edit) => { try { - const content = fileExists(workspace.cwd, path) ? readFile(workspace.cwd, path) : ''; + const content = fileExists(workspace.cwd, path) ? loadFile(workspace.cwd, path) : ''; const editedContent = edit(content); if (editedContent === '' || editedContent === false) return content; - writeFile(workspace.cwd, path, editedContent); + saveFile(workspace.cwd, path, editedContent); files.add(path); } catch (e) { if (e instanceof Error) { diff --git a/packages/sv/src/core/processors.ts b/packages/sv/src/core/processors.ts index a56240d15..bde28a7c1 100644 --- a/packages/sv/src/core/processors.ts +++ b/packages/sv/src/core/processors.ts @@ -1,10 +1,8 @@ import type { ConditionDefinition } from './config.ts'; import type { Workspace } from './workspace.ts'; -/** @deprecated Unused type, will be removed in a future version. */ export type FileEditor = Workspace & { content: string }; -/** @deprecated Unused type, will be removed in a future version. */ export type FileType = { name: (options: Workspace) => string; condition?: ConditionDefinition; diff --git a/packages/sv/src/core/workspace.ts b/packages/sv/src/core/workspace.ts index a31c3ddd6..cb38bcb9b 100644 --- a/packages/sv/src/core/workspace.ts +++ b/packages/sv/src/core/workspace.ts @@ -4,8 +4,8 @@ import { js, parse, commonFilePaths, - getPackageJson, - readFile + loadFile, + loadPackageJson } from '@sveltejs/sv-utils'; import * as find from 'empathic/find'; import fs from 'node:fs'; @@ -37,18 +37,6 @@ export type Workspace = { package: 'package.json'; gitignore: '.gitignore'; - /** @deprecated Addon-specific path - use the string literal '.prettierignore' directly. Will be removed in a future version. */ - prettierignore: '.prettierignore'; - /** @deprecated Addon-specific path - use the string literal '.prettierrc' directly. Will be removed in a future version. */ - prettierrc: '.prettierrc'; - /** @deprecated Addon-specific path - use the string literal 'eslint.config.js' directly. Will be removed in a future version. */ - eslintConfig: 'eslint.config.js'; - - /** @deprecated Addon-specific path - use the string literal '.vscode/settings.json' directly. Will be removed in a future version. */ - vscodeSettings: '.vscode/settings.json'; - /** @deprecated Addon-specific path - use the string literal '.vscode/extensions.json' directly. Will be removed in a future version. */ - vscodeExtensions: '.vscode/extensions.json'; - /** Get the relative path between two files */ getRelative: ({ from, to }: { from?: string; to: string }) => string; @@ -114,7 +102,7 @@ export async function createWorkspace({ directory.length >= workspaceRoot.length ) { if (fs.existsSync(path.join(directory, commonFilePaths.packageJson))) { - const { data: packageJson } = getPackageJson(directory); + const { data: packageJson } = loadPackageJson(directory); dependencies = { ...packageJson.devDependencies, ...packageJson.dependencies, @@ -153,11 +141,6 @@ export async function createWorkspace({ stylesheet, package: 'package.json', gitignore: '.gitignore', - prettierignore: '.prettierignore', - prettierrc: '.prettierrc', - eslintConfig: 'eslint.config.js', - vscodeSettings: '.vscode/settings.json', - vscodeExtensions: '.vscode/extensions.json', getRelative({ from, to }) { from = from ?? ''; let relativePath = path.posix.relative(path.posix.dirname(from), to); @@ -193,7 +176,7 @@ function findWorkspaceRoot(cwd: string): string { return directory; } // in other package managers it's a workspaces key in the package.json - const { data } = getPackageJson(directory); + const { data } = loadPackageJson(directory); if (data.workspaces) { return directory; } @@ -209,7 +192,7 @@ function findWorkspaceRoot(cwd: string): string { } function parseKitOptions(cwd: string, svelteConfigPath: string) { - const configSource = readFile(cwd, svelteConfigPath); + const configSource = loadFile(cwd, svelteConfigPath); const { ast } = parse.script(configSource); const defaultExport = ast.body.find((s) => s.type === 'ExportDefaultDeclaration'); diff --git a/packages/sv/src/create/index.ts b/packages/sv/src/create/index.ts index 5ee524d0c..1c30c199b 100644 --- a/packages/sv/src/create/index.ts +++ b/packages/sv/src/create/index.ts @@ -33,7 +33,6 @@ export type Common = { }>; }; -/** @deprecated Use `create({ cwd, name, template, types })` instead. */ export function create(cwd: string, options: Omit): void; export function create(options: Options): void; export function create( diff --git a/packages/sv/src/index.ts b/packages/sv/src/index.ts index 6b5c64d4a..3c3fe50b0 100644 --- a/packages/sv/src/index.ts +++ b/packages/sv/src/index.ts @@ -37,6 +37,4 @@ export type { // workspace.ts export type { Workspace, WorkspaceOptions } from './core/workspace.ts'; -// processors.ts - deprecated, will be removed -/** @deprecated Unused type, will be removed in a future version. */ export type { FileEditor, FileType } from './core/processors.ts'; From 4e2bf1bb63773b345a396d52b59c0076ba664d57 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 12:48:29 +0200 Subject: [PATCH 13/31] docs(sv-utils): clarify deprecation on readFile/writeFile/getPackageJson aliases Made-with: Cursor --- packages/sv-utils/api-surface.md | 12 +++++++++--- packages/sv-utils/src/files.ts | 12 +++++++++--- packages/sv-utils/src/index.ts | 12 +++++++++--- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index 655615480..87e9c9336 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -1730,11 +1730,17 @@ declare function loadPackageJson(cwd: string): { data: Package; generateCode: () => string; }; -/** @deprecated Use {@link loadFile} instead. */ +/** + * @deprecated Use {@link loadFile} instead. This alias will be removed in a future version. + */ declare const readFile: typeof loadFile; -/** @deprecated Use {@link saveFile} instead. */ +/** + * @deprecated Use {@link saveFile} instead. This alias will be removed in a future version. + */ declare const writeFile: typeof saveFile; -/** @deprecated Use {@link loadPackageJson} instead. */ +/** + * @deprecated Use {@link loadPackageJson} instead. This alias will be removed in a future version. + */ declare const getPackageJson: typeof loadPackageJson; type ColorInput = string | string[]; declare const color: { diff --git a/packages/sv-utils/src/files.ts b/packages/sv-utils/src/files.ts index 540e80602..8b6dc2488 100644 --- a/packages/sv-utils/src/files.ts +++ b/packages/sv-utils/src/files.ts @@ -70,11 +70,17 @@ export function loadPackageJson(cwd: string): { return { source: packageText, data: data as Package, generateCode }; } -/** @deprecated Use {@link loadFile} instead. */ +/** + * @deprecated Use {@link loadFile} instead. This alias will be removed in a future version. + */ export const readFile: typeof loadFile = loadFile; -/** @deprecated Use {@link saveFile} instead. */ +/** + * @deprecated Use {@link saveFile} instead. This alias will be removed in a future version. + */ export const writeFile: typeof saveFile = saveFile; -/** @deprecated Use {@link loadPackageJson} instead. */ +/** + * @deprecated Use {@link loadPackageJson} instead. This alias will be removed in a future version. + */ export const getPackageJson: typeof loadPackageJson = loadPackageJson; diff --git a/packages/sv-utils/src/index.ts b/packages/sv-utils/src/index.ts index b87fbf029..7c713c32b 100644 --- a/packages/sv-utils/src/index.ts +++ b/packages/sv-utils/src/index.ts @@ -90,11 +90,17 @@ export { type Package } from './files.ts'; -/** @deprecated Use {@link loadFile} instead. */ +/** + * @deprecated Use {@link loadFile} instead. This alias will be removed in a future version. + */ export { readFile } from './files.ts'; -/** @deprecated Use {@link saveFile} instead. */ +/** + * @deprecated Use {@link saveFile} instead. This alias will be removed in a future version. + */ export { writeFile } from './files.ts'; -/** @deprecated Use {@link loadPackageJson} instead. */ +/** + * @deprecated Use {@link loadPackageJson} instead. This alias will be removed in a future version. + */ export { getPackageJson } from './files.ts'; // Terminal styling From 773f8288e67bf10bdd777b1462dbf5055dd83d87 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 16:13:28 +0200 Subject: [PATCH 14/31] cleanup types --- packages/sv-utils/api-surface.md | 952 +------------------- packages/sv-utils/src/dedent.ts | 13 + packages/sv-utils/src/index.ts | 21 +- packages/sv-utils/src/pm.ts | 23 + packages/sv-utils/src/tooling/parsers.ts | 18 +- packages/sv-utils/src/tooling/transforms.ts | 5 +- packages/sv/src/addons/sveltekit-adapter.ts | 2 +- packages/sv/src/cli/create.ts | 2 +- packages/sv/src/core/common.ts | 6 +- packages/sv/src/core/engine.ts | 6 +- tsdown.config.ts | 11 +- 11 files changed, 93 insertions(+), 966 deletions(-) create mode 100644 packages/sv-utils/src/dedent.ts create mode 100644 packages/sv-utils/src/pm.ts diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index 87e9c9336..da1e51b0b 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -3,79 +3,6 @@ ```ts -type Agent = "npm" | "yarn" | "yarn@berry" | "pnpm" | "pnpm@6" | "bun" | "deno"; -type AgentName = "npm" | "yarn" | "pnpm" | "bun" | "deno"; -type AgentCommandValue = - | (string | number)[] - | ((args: string[]) => string[]) - | null; -interface AgentCommands { - agent: AgentCommandValue; - run: AgentCommandValue; - install: AgentCommandValue; - frozen: AgentCommandValue; - global: AgentCommandValue; - add: AgentCommandValue; - upgrade: AgentCommandValue; - "upgrade-interactive": AgentCommandValue; - dedupe: AgentCommandValue; - execute: AgentCommandValue; - "execute-local": AgentCommandValue; - uninstall: AgentCommandValue; - global_uninstall: AgentCommandValue; -} -type Command = keyof AgentCommands; -interface ResolvedCommand { - command: string; - - args: string[]; -} -type DetectStrategy = - | "lockfile" - | "packageManager-field" - | "devEngines-field" - | "install-metadata"; -interface DetectOptions { - cwd?: string; - - strategies?: DetectStrategy[]; - - onUnknown?: (packageManager: string) => DetectResult | null | undefined; - - stopDir?: string | ((currentDir: string) => boolean); - - packageJsonParser?: (content: string, filepath: string) => any | Promise; -} -interface DetectResult { - name: AgentName; - - agent: Agent; - - version?: string; -} -declare const COMMANDS: { - npm: AgentCommands; - yarn: AgentCommands; - "yarn@berry": AgentCommands; - pnpm: AgentCommands; - "pnpm@6": AgentCommands; - bun: AgentCommands; - deno: AgentCommands; -}; - -declare function resolveCommand( - agent: Agent, - command: Command, - args: string[], -): ResolvedCommand | null; - -declare function constructCommand( - value: AgentCommandValue, - args: string[], -): ResolvedCommand | null; -declare const AGENTS: Agent[]; - -declare function detect(options?: DetectOptions): Promise; /*! * Copyright (c) Squirrel Chat et al., All rights reserved. * SPDX-License-Identifier: BSD-3-Clause @@ -122,846 +49,6 @@ type TomlTable = { [key: string]: TomlValue; }; type TomlValue = TomlPrimitive | TomlValue[] | TomlTable; - -declare class LineCounter { - lineStarts: number[]; - - addNewLine: (offset: number) => number; - - linePos: (offset: number) => { - line: number; - col: number; - }; -} -type ErrorCode = - | "ALIAS_PROPS" - | "BAD_ALIAS" - | "BAD_DIRECTIVE" - | "BAD_DQ_ESCAPE" - | "BAD_INDENT" - | "BAD_PROP_ORDER" - | "BAD_SCALAR_START" - | "BLOCK_AS_IMPLICIT_KEY" - | "BLOCK_IN_FLOW" - | "DUPLICATE_KEY" - | "IMPOSSIBLE" - | "KEY_OVER_1024_CHARS" - | "MISSING_CHAR" - | "MULTILINE_IMPLICIT_KEY" - | "MULTIPLE_ANCHORS" - | "MULTIPLE_DOCS" - | "MULTIPLE_TAGS" - | "NON_STRING_KEY" - | "TAB_AS_INDENT" - | "TAG_RESOLVE_FAILED" - | "UNEXPECTED_TOKEN" - | "BAD_COLLECTION_TYPE"; -type LinePos = { - line: number; - col: number; -}; -declare class YAMLError extends Error { - name: "YAMLParseError" | "YAMLWarning"; - code: ErrorCode; - message: string; - pos: [number, number]; - linePos?: [LinePos] | [LinePos, LinePos]; - constructor( - name: YAMLError["name"], - pos: [number, number], - code: ErrorCode, - message: string, - ); -} -declare class YAMLWarning extends YAMLError { - constructor(pos: [number, number], code: ErrorCode, message: string); -} -type Reviver = (key: unknown, value: unknown) => unknown; -type LogLevelId = "silent" | "error" | "warn" | "debug"; -interface AnchorData { - aliasCount: number; - count: number; - res: unknown; -} -interface ToJSContext { - anchors: Map; - - aliasResolveCache?: Node[]; - doc: Document; - keep: boolean; - mapAsMap: boolean; - mapKeyWarned: boolean; - maxAliasCount: number; - onCreate?: (res: unknown) => void; -} -declare namespace Scalar { - interface Parsed extends Scalar { - range: Range; - source: string; - srcToken?: FlowScalar | BlockScalar; - } - type BLOCK_FOLDED = "BLOCK_FOLDED"; - type BLOCK_LITERAL = "BLOCK_LITERAL"; - type PLAIN = "PLAIN"; - type QUOTE_DOUBLE = "QUOTE_DOUBLE"; - type QUOTE_SINGLE = "QUOTE_SINGLE"; - type Type = - | BLOCK_FOLDED - | BLOCK_LITERAL - | PLAIN - | QUOTE_DOUBLE - | QUOTE_SINGLE; -} -declare class Scalar extends NodeBase { - static readonly BLOCK_FOLDED = "BLOCK_FOLDED"; - static readonly BLOCK_LITERAL = "BLOCK_LITERAL"; - static readonly PLAIN = "PLAIN"; - static readonly QUOTE_DOUBLE = "QUOTE_DOUBLE"; - static readonly QUOTE_SINGLE = "QUOTE_SINGLE"; - value: T; - - anchor?: string; - - format?: string; - - minFractionDigits?: number; - - source?: string; - - type?: Scalar.Type; - constructor(value: T); - toJSON(arg?: any, ctx?: ToJSContext): any; - toString(): string; -} -type StringifyContext = { - actualString?: boolean; - allNullValues?: boolean; - anchors: Set; - doc: Document; - forceBlockIndent?: boolean; - implicitKey?: boolean; - indent: string; - indentStep: string; - indentAtStart?: number; - inFlow: boolean | null; - inStringifyKey?: boolean; - flowCollectionPadding: string; - options: Readonly< - Required> - >; - resolvedAliases?: Set; -}; -declare abstract class Collection extends NodeBase { - schema: Schema | undefined; - [NODE_TYPE]: symbol; - items: unknown[]; - - anchor?: string; - - flow?: boolean; - constructor(type: symbol, schema?: Schema); - - clone(schema?: Schema): Collection; - - abstract add(value: unknown): void; - - abstract delete(key: unknown): boolean; - - abstract get(key: unknown, keepScalar?: boolean): unknown; - - abstract has(key: unknown): boolean; - - abstract set(key: unknown, value: unknown): void; - - addIn(path: Iterable, value: unknown): void; - - deleteIn(path: Iterable): boolean; - - getIn(path: Iterable, keepScalar?: boolean): unknown; - hasAllNullValues(allowScalar?: boolean): boolean; - - hasIn(path: Iterable): boolean; - - setIn(path: Iterable, value: unknown): void; -} -declare namespace YAMLSeq { - interface Parsed< - T extends ParsedNode | Pair = ParsedNode, - > extends YAMLSeq { - items: T[]; - range: Range; - srcToken?: BlockSequence | FlowCollection; - } -} -declare class YAMLSeq extends Collection { - static get tagName(): "tag:yaml.org,2002:seq"; - items: T[]; - constructor(schema?: Schema); - add(value: T): void; - - delete(key: unknown): boolean; - - get(key: unknown, keepScalar: true): Scalar | undefined; - get(key: unknown, keepScalar?: false): T | undefined; - get(key: unknown, keepScalar?: boolean): T | Scalar | undefined; - - has(key: unknown): boolean; - - set(key: unknown, value: T): void; - toJSON(_?: unknown, ctx?: ToJSContext): unknown[]; - toString( - ctx?: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ): string; - static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq; -} -interface TagBase { - createNode?: (schema: Schema, value: unknown, ctx: CreateNodeContext) => Node; - - default?: boolean | "key"; - - format?: string; - - identify?: (value: unknown) => boolean; - - tag: string; -} -interface ScalarTag extends TagBase { - collection?: never; - nodeClass?: never; - - resolve( - value: string, - onError: (message: string) => void, - options: ParseOptions, - ): unknown; - - stringify?: ( - item: Scalar, - ctx: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ) => string; - - test?: RegExp; -} -interface CollectionTag extends TagBase { - stringify?: never; - test?: never; - - collection: "map" | "seq"; - - nodeClass?: { - new (schema?: Schema): Node; - from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node; - }; - - resolve?: ( - value: YAMLMap.Parsed | YAMLSeq.Parsed, - onError: (message: string) => void, - options: ParseOptions, - ) => unknown; -} -type MapLike = - | Map - | Set - | Record; -declare namespace YAMLMap { - interface Parsed< - K extends ParsedNode = ParsedNode, - V extends ParsedNode | null = ParsedNode | null, - > extends YAMLMap { - items: Pair[]; - range: Range; - srcToken?: BlockMap | FlowCollection; - } -} -declare class YAMLMap extends Collection { - static get tagName(): "tag:yaml.org,2002:map"; - items: Pair[]; - constructor(schema?: Schema); - - static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap; - - add( - pair: - | Pair - | { - key: K; - value: V; - }, - overwrite?: boolean, - ): void; - delete(key: unknown): boolean; - get(key: unknown, keepScalar: true): Scalar | undefined; - get(key: unknown, keepScalar?: false): V | undefined; - get(key: unknown, keepScalar?: boolean): V | Scalar | undefined; - has(key: unknown): boolean; - set(key: K, value: V): void; - - toJSON>( - _?: unknown, - ctx?: ToJSContext, - Type?: { - new (): T; - }, - ): any; - toString( - ctx?: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ): string; -} -declare const MAP: unique symbol; -declare const SCALAR: unique symbol; -declare const SEQ: unique symbol; -declare const NODE_TYPE: unique symbol; -declare class Schema { - compat: Array | null; - knownTags: Record; - name: string; - sortMapEntries: ((a: Pair, b: Pair) => number) | null; - tags: Array; - toStringOptions: Readonly | null; - readonly [MAP]: CollectionTag; - readonly [SCALAR]: ScalarTag; - readonly [SEQ]: CollectionTag; - constructor({ - compat, - customTags, - merge, - resolveKnownTags, - schema, - sortMapEntries, - toStringDefaults, - }: SchemaOptions); - clone(): Schema; -} -interface CreateNodeContext { - aliasDuplicateObjects: boolean; - keepUndefined: boolean; - onAnchor: (source: unknown) => string; - onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; - sourceObjects: Map< - unknown, - { - anchor: string | null; - node: Node | null; - } - >; - replacer?: Replacer; - schema: Schema; -} -declare function addPairToJSMap( - ctx: ToJSContext | undefined, - map: MapLike, - { key, value }: Pair, -): MapLike; -declare class Pair { - readonly [NODE_TYPE]: symbol; - - key: K; - - value: V | null; - - srcToken?: CollectionItem; - constructor(key: K, value?: V | null); - clone(schema?: Schema): Pair; - toJSON(_?: unknown, ctx?: ToJSContext): ReturnType; - toString( - ctx?: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ): string; -} -declare const tagsByName: { - binary: ScalarTag; - bool: ScalarTag & { - test: RegExp; - }; - float: ScalarTag; - floatExp: ScalarTag; - floatNaN: ScalarTag; - floatTime: ScalarTag; - int: ScalarTag; - intHex: ScalarTag; - intOct: ScalarTag; - intTime: ScalarTag; - map: CollectionTag; - merge: ScalarTag & { - identify(value: unknown): boolean; - test: RegExp; - }; - null: ScalarTag & { - test: RegExp; - }; - omap: CollectionTag; - pairs: CollectionTag; - seq: CollectionTag; - set: CollectionTag; - timestamp: ScalarTag & { - test: RegExp; - }; -}; -type TagId = keyof typeof tagsByName; -type Tags = Array; -type ParseOptions = { - intAsBigInt?: boolean; - - keepSourceTokens?: boolean; - - lineCounter?: LineCounter; - - prettyErrors?: boolean; - - strict?: boolean; - - stringKeys?: boolean; - - uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean); -}; -type DocumentOptions = { - _directives?: Directives; - - logLevel?: LogLevelId; - - version?: "1.1" | "1.2" | "next"; -}; -type SchemaOptions = { - compat?: string | Tags | null; - - customTags?: Tags | ((tags: Tags) => Tags) | null; - - merge?: boolean; - - resolveKnownTags?: boolean; - - schema?: string | Schema; - - sortMapEntries?: boolean | ((a: Pair, b: Pair) => number); - - toStringDefaults?: ToStringOptions; -}; -type CreateNodeOptions = { - aliasDuplicateObjects?: boolean; - - anchorPrefix?: string; - flow?: boolean; - - keepUndefined?: boolean | null; - onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; - - tag?: string; -}; -type ToJSOptions = { - mapAsMap?: boolean; - - maxAliasCount?: number; - - onAnchor?: (value: unknown, count: number) => void; - - reviver?: Reviver; -}; -type ToStringOptions = { - blockQuote?: boolean | "folded" | "literal"; - - collectionStyle?: "any" | "block" | "flow"; - - commentString?: (comment: string) => string; - - defaultKeyType?: Scalar.Type | null; - - defaultStringType?: Scalar.Type; - - directives?: boolean | null; - - doubleQuotedAsJSON?: boolean; - - doubleQuotedMinMultiLineLength?: number; - - falseStr?: string; - - flowCollectionPadding?: boolean; - - indent?: number; - - indentSeq?: boolean; - - lineWidth?: number; - - minContentWidth?: number; - - nullStr?: string; - - simpleKeys?: boolean; - - singleQuote?: boolean | null; - - trueStr?: string; - - verifyAliasOrder?: boolean; -}; -type Node = Alias | Scalar | YAMLMap | YAMLSeq; - -type NodeType = T extends - | string - | number - | bigint - | boolean - | null - | undefined - ? Scalar - : T extends Date - ? Scalar - : T extends Array - ? YAMLSeq> - : T extends { - [key: string]: any; - } - ? YAMLMap, NodeType> - : T extends { - [key: number]: any; - } - ? YAMLMap, NodeType> - : Node; -type ParsedNode = - | Alias.Parsed - | Scalar.Parsed - | YAMLMap.Parsed - | YAMLSeq.Parsed; - -type Range = [number, number, number]; -declare abstract class NodeBase { - readonly [NODE_TYPE]: symbol; - - comment?: string | null; - - commentBefore?: string | null; - - range?: Range | null; - - spaceBefore?: boolean; - - srcToken?: Token; - - tag?: string; - - addToJSMap?: ( - ctx: ToJSContext | undefined, - map: MapLike, - value: unknown, - ) => void; - - abstract toJSON(): any; - abstract toString( - ctx?: StringifyContext, - onComment?: () => void, - onChompKeep?: () => void, - ): string; - constructor(type: symbol); - - clone(): NodeBase; - - toJS( - doc: Document, - { mapAsMap, maxAliasCount, onAnchor, reviver }?: ToJSOptions, - ): any; -} -interface SourceToken { - type: - | "byte-order-mark" - | "doc-mode" - | "doc-start" - | "space" - | "comment" - | "newline" - | "directive-line" - | "anchor" - | "tag" - | "seq-item-ind" - | "explicit-key-ind" - | "map-value-ind" - | "flow-map-start" - | "flow-map-end" - | "flow-seq-start" - | "flow-seq-end" - | "flow-error-end" - | "comma" - | "block-scalar-header"; - offset: number; - indent: number; - source: string; -} -interface ErrorToken { - type: "error"; - offset: number; - source: string; - message: string; -} -interface Directive$1 { - type: "directive"; - offset: number; - source: string; -} -interface Document$1 { - type: "document"; - offset: number; - start: SourceToken[]; - value?: Token; - end?: SourceToken[]; -} -interface DocumentEnd { - type: "doc-end"; - offset: number; - source: string; - end?: SourceToken[]; -} -interface FlowScalar { - type: "alias" | "scalar" | "single-quoted-scalar" | "double-quoted-scalar"; - offset: number; - indent: number; - source: string; - end?: SourceToken[]; -} -interface BlockScalar { - type: "block-scalar"; - offset: number; - indent: number; - props: Token[]; - source: string; -} -interface BlockMap { - type: "block-map"; - offset: number; - indent: number; - items: Array< - | { - start: SourceToken[]; - explicitKey?: true; - key?: never; - sep?: never; - value?: never; - } - | { - start: SourceToken[]; - explicitKey?: true; - key: Token | null; - sep: SourceToken[]; - value?: Token; - } - >; -} -interface BlockSequence { - type: "block-seq"; - offset: number; - indent: number; - items: Array<{ - start: SourceToken[]; - key?: never; - sep?: never; - value?: Token; - }>; -} -type CollectionItem = { - start: SourceToken[]; - key?: Token | null; - sep?: SourceToken[]; - value?: Token; -}; -interface FlowCollection { - type: "flow-collection"; - offset: number; - indent: number; - start: SourceToken; - items: CollectionItem[]; - end: SourceToken[]; -} -type Token = - | SourceToken - | ErrorToken - | Directive$1 - | Document$1 - | DocumentEnd - | FlowScalar - | BlockScalar - | BlockMap - | BlockSequence - | FlowCollection; -declare namespace Alias { - interface Parsed extends Alias { - range: Range; - srcToken?: FlowScalar & { - type: "alias"; - }; - } -} -declare class Alias extends NodeBase { - source: string; - anchor?: never; - constructor(source: string); - - resolve( - doc: Document, - ctx?: ToJSContext, - ): Scalar | YAMLMap | YAMLSeq | undefined; - toJSON(_arg?: unknown, ctx?: ToJSContext): unknown; - toString( - ctx?: StringifyContext, - _onComment?: () => void, - _onChompKeep?: () => void, - ): string; -} -type Replacer = any[] | ((key: any, value: any) => unknown); -declare namespace Document { - interface Parsed< - Contents extends ParsedNode = ParsedNode, - Strict extends boolean = true, - > extends Document { - directives: Directives; - range: Range; - } -} -declare class Document< - Contents extends Node = Node, - Strict extends boolean = true, -> { - readonly [NODE_TYPE]: symbol; - - commentBefore: string | null; - - comment: string | null; - - contents: Strict extends true ? Contents | null : Contents; - directives: Strict extends true ? Directives | undefined : Directives; - - errors: YAMLError[]; - options: Required< - Omit< - ParseOptions & DocumentOptions, - "_directives" | "lineCounter" | "version" - > - >; - - range?: Range; - - schema: Schema; - - warnings: YAMLWarning[]; - - constructor( - value?: any, - options?: DocumentOptions & - SchemaOptions & - ParseOptions & - CreateNodeOptions, - ); - constructor( - value: any, - replacer: null | Replacer, - options?: DocumentOptions & - SchemaOptions & - ParseOptions & - CreateNodeOptions, - ); - - clone(): Document; - - add(value: any): void; - - addIn(path: Iterable, value: unknown): void; - - createAlias( - node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, - name?: string, - ): Alias; - - createNode(value: T, options?: CreateNodeOptions): NodeType; - createNode( - value: T, - replacer: Replacer | CreateNodeOptions | null, - options?: CreateNodeOptions, - ): NodeType; - - createPair( - key: unknown, - value: unknown, - options?: CreateNodeOptions, - ): Pair; - - delete(key: unknown): boolean; - - deleteIn(path: Iterable | null): boolean; - - get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any; - - getIn( - path: Iterable | null, - keepScalar?: boolean, - ): Strict extends true ? unknown : any; - - has(key: unknown): boolean; - - hasIn(path: Iterable | null): boolean; - - set(key: any, value: unknown): void; - - setIn(path: Iterable | null, value: unknown): void; - - setSchema( - version: "1.1" | "1.2" | "next" | null, - options?: SchemaOptions, - ): void; - - toJS( - opt?: ToJSOptions & { - [ignored: string]: unknown; - }, - ): any; - - toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions["onAnchor"]): any; - - toString(options?: ToStringOptions): string; -} -declare class Directives { - static defaultYaml: Directives["yaml"]; - static defaultTags: Directives["tags"]; - yaml: { - version: "1.1" | "1.2" | "next"; - explicit?: boolean; - }; - tags: Record; - - docStart: true | null; - - docEnd: boolean; - - private atNextDocument?; - constructor(yaml?: Directives["yaml"], tags?: Directives["tags"]); - clone(): Directives; - - atDocument(): Directives; - - add( - line: string, - onError: (offset: number, message: string, warning?: boolean) => void, - ): boolean; - - tagName(source: string, onError: (message: string) => void): string | null; - - tagString(tag: string): string; - toString(doc?: Document): string; -} - -declare function parseDocument< - Contents extends Node = ParsedNode, - Strict extends boolean = true, ->( - source: string, - options?: ParseOptions & DocumentOptions & SchemaOptions, -): Contents extends ParsedNode - ? Document.Parsed - : Document; declare module "estree" { interface TSTypeAnnotation { type: "TSTypeAnnotation"; @@ -1063,7 +150,6 @@ declare module "estree" { importKind: "type" | "value"; } } -declare function parseYaml$1(content: string): ReturnType; type CommentType = { type: "Line" | "Block"; value: string; @@ -1084,6 +170,11 @@ declare class Comments { predicate: (comment: estree.Comment) => boolean | undefined | null, ): void; } + +type YamlDocument = { + get(key: string): unknown; + set(key: string, value: unknown): void; +}; type ParseBase = { source: string; @@ -1103,7 +194,7 @@ declare function parseJson(source: string): { data: any; } & ParseBase; declare function parseYaml(source: string): { - data: ReturnType; + data: YamlDocument; } & ParseBase; declare function parseSvelte(source: string): { ast: SvelteAst.Root; @@ -1111,17 +202,11 @@ declare function parseSvelte(source: string): { declare function parseToml(source: string): { data: TomlTable; } & ParseBase; -interface DedentOptions { - alignValues?: boolean; - escapeSpecialCharacters?: boolean; - trimWhitespace?: boolean; -} -interface Dedent { - (literals: string): string; + +type Dedent = { (strings: TemplateStringsArray, ...values: unknown[]): string; - withOptions: CreateDedent; -} -type CreateDedent = (options: DedentOptions) => Dedent; + (source: string): string; +}; declare const dedent: Dedent; declare module "zimmerframe" { export function walk< @@ -1156,6 +241,11 @@ declare module "zimmerframe" { } export {}; } //# sourceMappingURL=index.d.ts.map +declare function resolveCommandArray( + agent: Agent, + command: Command, + args: string[], +): string[]; declare namespace index_d_exports$1 { export { addAtRule, addDeclaration, addImports, addRule }; } @@ -1647,10 +737,7 @@ declare const transforms: { ): TransformFn; yaml( - cb: (file: { - data: ReturnType["data"]; - content: string; - }) => void | false, + cb: (file: { data: YamlDocument; content: string }) => void | false, options?: TransformOptions, ): TransformFn; @@ -1758,12 +845,6 @@ declare const color: { hidden: (str: ColorInput) => string; }; -declare function resolveCommandArray( - agent: Agent, - command: Command, - args: string[], -): string[]; - declare const parse: { css: typeof parseCss; html: typeof parseHtml; @@ -1783,6 +864,7 @@ export { type SvelteAst, type TransformFn, index_d_exports as Walker, + type YamlDocument, color, commonFilePaths, constructCommand, diff --git a/packages/sv-utils/src/dedent.ts b/packages/sv-utils/src/dedent.ts new file mode 100644 index 000000000..1210bdac9 --- /dev/null +++ b/packages/sv-utils/src/dedent.ts @@ -0,0 +1,13 @@ +import dedentImpl from 'dedent'; + +/** + * Template-tag or single-string dedent helper (same behavior as the `dedent` package). + * Types are hand-written so the public `.d.mts` does not inline `dedent`'s full declarations. + */ +export type Dedent = { + (strings: TemplateStringsArray, ...values: unknown[]): string; + (source: string): string; +}; + +const dedent: Dedent = dedentImpl as Dedent; +export default dedent; diff --git a/packages/sv-utils/src/index.ts b/packages/sv-utils/src/index.ts index 7c713c32b..d8615802c 100644 --- a/packages/sv-utils/src/index.ts +++ b/packages/sv-utils/src/index.ts @@ -1,8 +1,3 @@ -import { - resolveCommand as _resolveCommand, - type Agent, - type Command -} from 'package-manager-detector'; import { parseCss, parseHtml, @@ -14,22 +9,19 @@ import { } from './tooling/parsers.ts'; // External re-exports -export { default as dedent } from 'dedent'; +export { default as dedent } from './dedent.ts'; export * as Walker from 'zimmerframe'; + +// Package managers (delegates to `package-manager-detector`; see `pm.ts`) export { AGENTS, type AgentName, COMMANDS, constructCommand, detect, - resolveCommand -} from 'package-manager-detector'; - -/** Resolves a package manager command and returns it as a string array (command + args). */ -export function resolveCommandArray(agent: Agent, command: Command, args: string[]): string[] { - const cmd = _resolveCommand(agent, command, args)!; - return [cmd.command, ...cmd.args]; -} + resolveCommand, + resolveCommandArray +} from './pm.ts'; // Parsing & language namespaces export * as css from './tooling/css/index.ts'; @@ -109,3 +101,4 @@ export { color } from './color.ts'; // Types export type { Comments, AstTypes, SvelteAst } from './tooling/index.ts'; export type { TransformFn } from './tooling/transforms.ts'; +export type { YamlDocument } from './tooling/parsers.ts'; diff --git a/packages/sv-utils/src/pm.ts b/packages/sv-utils/src/pm.ts new file mode 100644 index 000000000..fd01d791c --- /dev/null +++ b/packages/sv-utils/src/pm.ts @@ -0,0 +1,23 @@ +/** + * Thin wrapper around [`package-manager-detector`](https://github.com/antfu/package-manager-detector). + * Only the symbols re-exported from the package root are public — we keep this module small and + * avoid exposing the full upstream surface. + */ +import { + resolveCommand as _resolveCommand, + type Agent, + type Command +} from 'package-manager-detector'; +export { + AGENTS, + type AgentName, + COMMANDS, + constructCommand, + detect, + resolveCommand +} from 'package-manager-detector'; + +export function resolveCommandArray(agent: Agent, command: Command, args: string[]): string[] { + const cmd = _resolveCommand(agent, command, args)!; + return [cmd.command, ...cmd.args]; +} diff --git a/packages/sv-utils/src/tooling/parsers.ts b/packages/sv-utils/src/tooling/parsers.ts index f5661ebc2..a20a93803 100644 --- a/packages/sv-utils/src/tooling/parsers.ts +++ b/packages/sv-utils/src/tooling/parsers.ts @@ -1,6 +1,15 @@ import type { TomlTable } from 'smol-toml'; import * as utils from './index.ts'; +/** + * Minimal shape for YAML document roots from `parse.yaml` — avoids re-exporting the full `yaml` types. + * At runtime this is the library’s document type; only `get` / `set` are part of the public contract. + */ +export type YamlDocument = { + get(key: string): unknown; + set(key: string, value: unknown): void; +}; + type ParseBase = { source: string; /** @@ -52,14 +61,13 @@ export function parseJson(source: string): { data: any } & ParseBase { return { data, source, generateCode }; } -export function parseYaml( - source: string -): { data: ReturnType } & ParseBase { +export function parseYaml(source: string): { data: YamlDocument } & ParseBase { if (!source) source = ''; const data = utils.parseYaml(source); - const generateCode = () => utils.serializeYaml(data); + const generateCode = () => + utils.serializeYaml(data as Parameters[0]); - return { data, source, generateCode }; + return { data: data as YamlDocument, source, generateCode }; } export function parseSvelte(source: string): { ast: utils.SvelteAst.Root } & ParseBase { diff --git a/packages/sv-utils/src/tooling/transforms.ts b/packages/sv-utils/src/tooling/transforms.ts index 5d27c1696..361b5925b 100644 --- a/packages/sv-utils/src/tooling/transforms.ts +++ b/packages/sv-utils/src/tooling/transforms.ts @@ -12,7 +12,8 @@ import { parseScript, parseSvelte, parseToml, - parseYaml + parseYaml, + type YamlDocument } from './parsers.ts'; import { type RootWithInstance, ensureScript } from './svelte/index.ts'; import * as svelteNs from './svelte/index.ts'; @@ -190,7 +191,7 @@ export const transforms = { * Return `false` from the callback to abort - the original content is returned unchanged. */ yaml( - cb: (file: { data: ReturnType['data']; content: string }) => void | false, + cb: (file: { data: YamlDocument; content: string }) => void | false, options?: TransformOptions ): TransformFn { return (content) => { diff --git a/packages/sv/src/addons/sveltekit-adapter.ts b/packages/sv/src/addons/sveltekit-adapter.ts index 739e89896..4f2340da7 100644 --- a/packages/sv/src/addons/sveltekit-adapter.ts +++ b/packages/sv/src/addons/sveltekit-adapter.ts @@ -1,8 +1,8 @@ import { color, - resolveCommandArray, text, transforms, + resolveCommandArray, fileExists, loadPackageJson, sanitizeName diff --git a/packages/sv/src/cli/create.ts b/packages/sv/src/cli/create.ts index b3e92da45..f8793efc2 100644 --- a/packages/sv/src/cli/create.ts +++ b/packages/sv/src/cli/create.ts @@ -1,5 +1,5 @@ import * as p from '@clack/prompts'; -import { color, resolveCommandArray, commonFilePaths, loadPackageJson } from '@sveltejs/sv-utils'; +import { color, commonFilePaths, loadPackageJson, resolveCommandArray } from '@sveltejs/sv-utils'; import { Command, Option } from 'commander'; import fs from 'node:fs'; import path from 'node:path'; diff --git a/packages/sv/src/core/common.ts b/packages/sv/src/core/common.ts index 856b8e0c5..aace74cc8 100644 --- a/packages/sv/src/core/common.ts +++ b/packages/sv/src/core/common.ts @@ -1,9 +1,9 @@ import * as p from '@clack/prompts'; import { - type AgentName, color, - resolveCommandArray, - isVersionUnsupportedBelow + isVersionUnsupportedBelow, + type AgentName, + resolveCommandArray } from '@sveltejs/sv-utils'; import type { Argument, Command, Help, HelpConfiguration, Option } from 'commander'; import fs from 'node:fs'; diff --git a/packages/sv/src/core/engine.ts b/packages/sv/src/core/engine.ts index 407fbdae3..c9bdeb1ff 100644 --- a/packages/sv/src/core/engine.ts +++ b/packages/sv/src/core/engine.ts @@ -2,12 +2,12 @@ import * as p from '@clack/prompts'; import { color, commonFilePaths, - resolveCommand, - type AgentName, fileExists, loadFile, loadPackageJson, - saveFile + saveFile, + resolveCommand, + type AgentName } from '@sveltejs/sv-utils'; import { NonZeroExitError, exec } from 'tinyexec'; import { createLoadedAddon } from '../cli/add.ts'; diff --git a/tsdown.config.ts b/tsdown.config.ts index 7de467cb0..ce4017a73 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -124,8 +124,15 @@ export default defineConfig([ }, failOnWarn: true, deps: { - neverBundle: [/^svelte/, '@types/estree', 'estree'], - onlyBundle: ['dedent', 'package-manager-detector', 'smol-toml', 'yaml', 'zimmerframe'] + neverBundle: [ + /^svelte/, + '@types/estree', + 'estree', + 'yaml', + 'dedent', + 'package-manager-detector' + ], + onlyBundle: ['smol-toml', 'zimmerframe'] }, hooks: { 'build:done': () => hookApiSurfaceBuildDone() From 95ee3227ae123746c5f0e16df6bd211512b4cfa7 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sun, 5 Apr 2026 00:00:59 +0200 Subject: [PATCH 15/31] chore: Prettier on sources (align with post-build output) Made-with: Cursor --- packages/sv-utils/api-surface.md | 1204 +++++++++++----------- packages/sv-utils/src/pm.ts | 1 + packages/sv-utils/src/tooling/parsers.ts | 3 +- packages/sv/api-surface-testing.md | 154 ++- packages/sv/api-surface.md | 98 +- packages/sv/src/create/index.ts | 5 +- 6 files changed, 694 insertions(+), 771 deletions(-) diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index da1e51b0b..1e5050d6e 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -31,781 +31,725 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare class TomlDate extends Date { - #private; - constructor(date: string | Date); - isDateTime(): boolean; - isLocal(): boolean; - isDate(): boolean; - isTime(): boolean; - isValid(): boolean; - toISOString(): string; - static wrapAsOffsetDateTime(jsDate: Date, offset?: string): TomlDate; - static wrapAsLocalDateTime(jsDate: Date): TomlDate; - static wrapAsLocalDate(jsDate: Date): TomlDate; - static wrapAsLocalTime(jsDate: Date): TomlDate; + #private; + constructor(date: string | Date); + isDateTime(): boolean; + isLocal(): boolean; + isDate(): boolean; + isTime(): boolean; + isValid(): boolean; + toISOString(): string; + static wrapAsOffsetDateTime(jsDate: Date, offset?: string): TomlDate; + static wrapAsLocalDateTime(jsDate: Date): TomlDate; + static wrapAsLocalDate(jsDate: Date): TomlDate; + static wrapAsLocalTime(jsDate: Date): TomlDate; } type TomlPrimitive = string | number | bigint | boolean | TomlDate; type TomlTable = { - [key: string]: TomlValue; + [key: string]: TomlValue; }; type TomlValue = TomlPrimitive | TomlValue[] | TomlTable; -declare module "estree" { - interface TSTypeAnnotation { - type: "TSTypeAnnotation"; - typeAnnotation: - | TSStringKeyword - | TSTypeReference - | TSUnionType - | TSIndexedAccessType; - } - interface TSStringKeyword { - type: "TSStringKeyword"; - } - interface TSNullKeyword { - type: "TSNullKeyword"; - } - interface TSTypeReference { - type: "TSTypeReference"; - typeName: Identifier; - } - interface TSAsExpression extends BaseNode { - type: "TSAsExpression"; - expression: Expression; - typeAnnotation: TSTypeAnnotation["typeAnnotation"]; - } - interface TSModuleDeclaration extends BaseNode { - type: "TSModuleDeclaration"; - global: boolean; - declare: boolean; - id: Identifier; - body: TSModuleBlock; - } - interface TSModuleBlock extends BaseNode { - type: "TSModuleBlock"; - body: Array; - } - interface TSInterfaceDeclaration extends BaseNode { - type: "TSInterfaceDeclaration"; - id: Identifier; - body: TSInterfaceBody; - } - interface TSInterfaceBody extends BaseNode { - type: "TSInterfaceBody"; - body: TSPropertySignature[]; - } - interface TSPropertySignature extends BaseNode { - type: "TSPropertySignature"; - computed: boolean; - key: Identifier; - optional?: boolean; - typeAnnotation: TSTypeAnnotation; - } - interface TSProgram extends Omit { - body: Array< - Directive | Statement | ModuleDeclaration | TSModuleDeclaration - >; - } - interface TSUnionType { - type: "TSUnionType"; - types: Array; - } - interface TSImportType { - type: "TSImportType"; - argument: Literal; - qualifier: Identifier; - } - interface TSIndexedAccessType { - type: "TSIndexedAccessType"; - objectType: TSImportType; - indexType: TSLiteralType; - } - interface TSLiteralType { - type: "TSLiteralType"; - literal: Literal; - } - interface TSSatisfiesExpression extends BaseNode { - type: "TSSatisfiesExpression"; - expression: Expression; - typeAnnotation: TSTypeAnnotation["typeAnnotation"]; - } - interface BaseNodeWithoutComments { - type: string; - loc?: SourceLocation | null | undefined; - range?: [number, number] | undefined; - start?: number; - end?: number; - } - interface Identifier { - typeAnnotation?: TSTypeAnnotation; - } - interface ExpressionMap { - TSAsExpression: TSAsExpression; - TSSatisfiesExpression: TSSatisfiesExpression; - } - interface NodeMap { - TSModuleDeclaration: TSModuleDeclaration; - TSInterfaceDeclaration: TSInterfaceDeclaration; - } - interface ImportDeclaration { - importKind: "type" | "value"; - } +declare module 'estree' { + interface TSTypeAnnotation { + type: 'TSTypeAnnotation'; + typeAnnotation: TSStringKeyword | TSTypeReference | TSUnionType | TSIndexedAccessType; + } + interface TSStringKeyword { + type: 'TSStringKeyword'; + } + interface TSNullKeyword { + type: 'TSNullKeyword'; + } + interface TSTypeReference { + type: 'TSTypeReference'; + typeName: Identifier; + } + interface TSAsExpression extends BaseNode { + type: 'TSAsExpression'; + expression: Expression; + typeAnnotation: TSTypeAnnotation['typeAnnotation']; + } + interface TSModuleDeclaration extends BaseNode { + type: 'TSModuleDeclaration'; + global: boolean; + declare: boolean; + id: Identifier; + body: TSModuleBlock; + } + interface TSModuleBlock extends BaseNode { + type: 'TSModuleBlock'; + body: Array; + } + interface TSInterfaceDeclaration extends BaseNode { + type: 'TSInterfaceDeclaration'; + id: Identifier; + body: TSInterfaceBody; + } + interface TSInterfaceBody extends BaseNode { + type: 'TSInterfaceBody'; + body: TSPropertySignature[]; + } + interface TSPropertySignature extends BaseNode { + type: 'TSPropertySignature'; + computed: boolean; + key: Identifier; + optional?: boolean; + typeAnnotation: TSTypeAnnotation; + } + interface TSProgram extends Omit { + body: Array; + } + interface TSUnionType { + type: 'TSUnionType'; + types: Array; + } + interface TSImportType { + type: 'TSImportType'; + argument: Literal; + qualifier: Identifier; + } + interface TSIndexedAccessType { + type: 'TSIndexedAccessType'; + objectType: TSImportType; + indexType: TSLiteralType; + } + interface TSLiteralType { + type: 'TSLiteralType'; + literal: Literal; + } + interface TSSatisfiesExpression extends BaseNode { + type: 'TSSatisfiesExpression'; + expression: Expression; + typeAnnotation: TSTypeAnnotation['typeAnnotation']; + } + interface BaseNodeWithoutComments { + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; + start?: number; + end?: number; + } + interface Identifier { + typeAnnotation?: TSTypeAnnotation; + } + interface ExpressionMap { + TSAsExpression: TSAsExpression; + TSSatisfiesExpression: TSSatisfiesExpression; + } + interface NodeMap { + TSModuleDeclaration: TSModuleDeclaration; + TSInterfaceDeclaration: TSInterfaceDeclaration; + } + interface ImportDeclaration { + importKind: 'type' | 'value'; + } } type CommentType = { - type: "Line" | "Block"; - value: string; + type: 'Line' | 'Block'; + value: string; }; declare class Comments { - private original; - private leading; - private trailing; - constructor(); - add( - node: BaseNode$1, - comment: CommentType, - options?: { - position?: "leading" | "trailing"; - }, - ): void; - remove( - predicate: (comment: estree.Comment) => boolean | undefined | null, - ): void; + private original; + private leading; + private trailing; + constructor(); + add( + node: BaseNode$1, + comment: CommentType, + options?: { + position?: 'leading' | 'trailing'; + } + ): void; + remove(predicate: (comment: estree.Comment) => boolean | undefined | null): void; } type YamlDocument = { - get(key: string): unknown; - set(key: string, value: unknown): void; + get(key: string): unknown; + set(key: string, value: unknown): void; }; type ParseBase = { - source: string; + source: string; - generateCode(): string; + generateCode(): string; }; declare function parseScript(source: string): { - ast: estree.Program; - comments: Comments; + ast: estree.Program; + comments: Comments; } & ParseBase; declare function parseCss(source: string): { - ast: Omit; + ast: Omit; } & ParseBase; declare function parseHtml(source: string): { - ast: SvelteAst.Fragment; + ast: SvelteAst.Fragment; } & ParseBase; declare function parseJson(source: string): { - data: any; + data: any; } & ParseBase; declare function parseYaml(source: string): { - data: YamlDocument; + data: YamlDocument; } & ParseBase; declare function parseSvelte(source: string): { - ast: SvelteAst.Root; + ast: SvelteAst.Root; } & ParseBase; declare function parseToml(source: string): { - data: TomlTable; + data: TomlTable; } & ParseBase; type Dedent = { - (strings: TemplateStringsArray, ...values: unknown[]): string; - (source: string): string; + (strings: TemplateStringsArray, ...values: unknown[]): string; + (source: string): string; }; declare const dedent: Dedent; -declare module "zimmerframe" { - export function walk< - T extends { - type: string; - }, - U extends Record | null, - >(node: T, state: U, visitors: Visitors): T; - type BaseNode = { - type: string; - }; - type NodeOf = X extends { - type: T; - } - ? X - : never; - type SpecialisedVisitors = { - [K in T["type"]]?: Visitor, U, T>; - }; - export type Visitor = (node: T, context: Context) => V | void; - export type Visitors = T["type"] extends "_" - ? never - : SpecialisedVisitors & { - _?: Visitor; - }; - export interface Context { - next: (state?: U) => T | void; - path: T[]; - state: U; - stop: () => void; - visit: (node: T, state?: U) => T; - } - export {}; +declare module 'zimmerframe' { + export function walk< + T extends { + type: string; + }, + U extends Record | null + >(node: T, state: U, visitors: Visitors): T; + type BaseNode = { + type: string; + }; + type NodeOf = X extends { + type: T; + } + ? X + : never; + type SpecialisedVisitors = { + [K in T['type']]?: Visitor, U, T>; + }; + export type Visitor = (node: T, context: Context) => V | void; + export type Visitors = T['type'] extends '_' + ? never + : SpecialisedVisitors & { + _?: Visitor; + }; + export interface Context { + next: (state?: U) => T | void; + path: T[]; + state: U; + stop: () => void; + visit: (node: T, state?: U) => T; + } + export {}; } //# sourceMappingURL=index.d.ts.map -declare function resolveCommandArray( - agent: Agent, - command: Command, - args: string[], -): string[]; +declare function resolveCommandArray(agent: Agent, command: Command, args: string[]): string[]; declare namespace index_d_exports$1 { - export { addAtRule, addDeclaration, addImports, addRule }; + export { addAtRule, addDeclaration, addImports, addRule }; } declare function addRule( - node: SvelteAst.CSS.StyleSheetBase, - options: { - selector: string; - }, + node: SvelteAst.CSS.StyleSheetBase, + options: { + selector: string; + } ): SvelteAst.CSS.Rule; declare function addDeclaration( - node: SvelteAst.CSS.Rule, - options: { - property: string; - value: string; - }, + node: SvelteAst.CSS.Rule, + options: { + property: string; + value: string; + } ): void; declare function addImports( - node: SvelteAst.CSS.StyleSheetBase, - options: { - imports: string[]; - }, + node: SvelteAst.CSS.StyleSheetBase, + options: { + imports: string[]; + } ): void; declare function addAtRule( - node: SvelteAst.CSS.StyleSheetBase, - options: { - name: string; - params: string; - append: boolean; - }, + node: SvelteAst.CSS.StyleSheetBase, + options: { + name: string; + params: string; + append: boolean; + } ): SvelteAst.CSS.Atrule; declare namespace array_d_exports { - export { append, create$1 as create, prepend }; + export { append, create$1 as create, prepend }; } declare function create$1(): estree.ArrayExpression; declare function append( - node: estree.ArrayExpression, - element: string | estree.Expression | estree.SpreadElement, + node: estree.ArrayExpression, + element: string | estree.Expression | estree.SpreadElement ): void; declare function prepend( - node: estree.ArrayExpression, - element: string | estree.Expression | estree.SpreadElement, + node: estree.ArrayExpression, + element: string | estree.Expression | estree.SpreadElement ): void; declare namespace object_d_exports { - export { create, overrideProperties, property, propertyNode }; + export { create, overrideProperties, property, propertyNode }; } type ObjectPrimitiveValues = string | number | boolean | undefined | null; -type ObjectValues = - | ObjectPrimitiveValues - | Record - | ObjectValues[]; +type ObjectValues = ObjectPrimitiveValues | Record | ObjectValues[]; type ObjectMap = Record; declare function property( - node: estree.ObjectExpression, - options: { - name: string; - fallback: T; - }, + node: estree.ObjectExpression, + options: { + name: string; + fallback: T; + } ): T; declare function propertyNode( - node: estree.ObjectExpression, - options: { - name: string; - fallback: T; - }, + node: estree.ObjectExpression, + options: { + name: string; + fallback: T; + } ): estree.Property; declare function create(properties: ObjectMap): estree.ObjectExpression; declare function overrideProperties( - objectExpression: estree.ObjectExpression, - properties: ObjectMap, + objectExpression: estree.ObjectExpression, + properties: ObjectMap ): void; declare namespace common_d_exports { - export { - addJsDocComment, - addJsDocTypeComment, - appendFromString, - appendStatement, - areNodesEqual, - contains, - createBlockStatement, - createExpressionStatement, - createLiteral, - createSatisfies, - createSpread, - createTypeProperty, - hasTypeProperty, - parseExpression, - parseFromString, - parseStatement, - typeAnnotate, - }; + export { + addJsDocComment, + addJsDocTypeComment, + appendFromString, + appendStatement, + areNodesEqual, + contains, + createBlockStatement, + createExpressionStatement, + createLiteral, + createSatisfies, + createSpread, + createTypeProperty, + hasTypeProperty, + parseExpression, + parseFromString, + parseStatement, + typeAnnotate + }; } declare function addJsDocTypeComment( - node: estree.Node, - comments: Comments, - options: { - type: string; - }, + node: estree.Node, + comments: Comments, + options: { + type: string; + } ): void; declare function addJsDocComment( - node: estree.Node, - comments: Comments, - options: { - params: Record; - }, + node: estree.Node, + comments: Comments, + options: { + params: Record; + } ): void; declare function typeAnnotate( - node: estree.Expression, - options: { - type: string; - }, + node: estree.Expression, + options: { + type: string; + } ): estree.TSAsExpression; declare function createSatisfies( - node: estree.Expression, - options: { - type: string; - }, + node: estree.Expression, + options: { + type: string; + } ): estree.TSSatisfiesExpression; -declare function createSpread( - argument: estree.Expression, -): estree.SpreadElement; -declare function createLiteral( - value: string | number | boolean | null, -): estree.Literal; -declare function areNodesEqual( - node: estree.Node, - otherNode: estree.Node, -): boolean; +declare function createSpread(argument: estree.Expression): estree.SpreadElement; +declare function createLiteral(value: string | number | boolean | null): estree.Literal; +declare function areNodesEqual(node: estree.Node, otherNode: estree.Node): boolean; declare function createBlockStatement(): estree.BlockStatement; declare function createExpressionStatement(options: { - expression: estree.Expression; + expression: estree.Expression; }): estree.ExpressionStatement; declare function appendFromString( - node: estree.BlockStatement | estree.Program, - options: { - code: string; - comments?: Comments; - }, + node: estree.BlockStatement | estree.Program, + options: { + code: string; + comments?: Comments; + } ): void; declare function parseExpression(code: string): estree.Expression; declare function parseStatement(code: string): estree.Statement; declare function parseFromString(code: string): T; declare function appendStatement( - node: estree.BlockStatement | estree.Program, - options: { - statement: estree.Statement; - }, + node: estree.BlockStatement | estree.Program, + options: { + statement: estree.Statement; + } ): void; declare function contains(node: estree.Node, targetNode: estree.Node): boolean; declare function hasTypeProperty( - node: estree.TSInterfaceDeclaration["body"]["body"][number], - options: { - name: string; - }, + node: estree.TSInterfaceDeclaration['body']['body'][number], + options: { + name: string; + } ): boolean; declare function createTypeProperty( - name: string, - value: string, - optional?: boolean, -): estree.TSInterfaceBody["body"][number]; + name: string, + value: string, + optional?: boolean +): estree.TSInterfaceBody['body'][number]; declare namespace function_d_exports { - export { createArrow, createCall, getArgument }; + export { createArrow, createCall, getArgument }; } declare function createCall(options: { - name: string; - args: string[]; - useIdentifiers?: boolean; + name: string; + args: string[]; + useIdentifiers?: boolean; }): estree.CallExpression; declare function createArrow(options: { - body: estree.Expression | estree.BlockStatement; - async: boolean; + body: estree.Expression | estree.BlockStatement; + async: boolean; }): estree.ArrowFunctionExpression; declare function getArgument( - node: estree.CallExpression, - options: { - index: number; - fallback: T; - }, + node: estree.CallExpression, + options: { + index: number; + fallback: T; + } ): T; declare namespace imports_d_exports { - export { - addDefault, - addEmpty, - addNamed, - addNamespace$1 as addNamespace, - find, - remove, - }; + export { addDefault, addEmpty, addNamed, addNamespace$1 as addNamespace, find, remove }; } declare function addEmpty( - node: estree.Program, - options: { - from: string; - }, + node: estree.Program, + options: { + from: string; + } ): void; declare function addNamespace$1( - node: estree.Program, - options: { - from: string; - as: string; - }, + node: estree.Program, + options: { + from: string; + as: string; + } ): void; declare function addDefault( - node: estree.Program, - options: { - from: string; - as: string; - }, + node: estree.Program, + options: { + from: string; + as: string; + } ): void; declare function addNamed( - node: estree.Program, - options: { - imports: Record | string[]; - from: string; - isType?: boolean; - }, + node: estree.Program, + options: { + imports: Record | string[]; + from: string; + isType?: boolean; + } ): void; declare function find( - ast: estree.Program, - options: { - name: string; - from: string; - }, + ast: estree.Program, + options: { + name: string; + from: string; + } ): - | { - statement: estree.ImportDeclaration; - alias: string; - } - | { - statement: undefined; - alias: undefined; - }; + | { + statement: estree.ImportDeclaration; + alias: string; + } + | { + statement: undefined; + alias: undefined; + }; declare function remove( - ast: estree.Program, - options: { - name: string; - from: string; - statement?: estree.ImportDeclaration; - }, + ast: estree.Program, + options: { + name: string; + from: string; + statement?: estree.ImportDeclaration; + } ): void; declare namespace variables_d_exports { - export { createIdentifier, declaration, typeAnnotateDeclarator }; + export { createIdentifier, declaration, typeAnnotateDeclarator }; } declare function declaration( - node: estree.Program | estree.Declaration, - options: { - kind: "const" | "let" | "var"; - name: string; - value: estree.Expression; - }, + node: estree.Program | estree.Declaration, + options: { + kind: 'const' | 'let' | 'var'; + name: string; + value: estree.Expression; + } ): estree.VariableDeclaration; declare function createIdentifier(name: string): estree.Identifier; declare function typeAnnotateDeclarator( - node: estree.VariableDeclarator, - options: { - typeName: string; - }, + node: estree.VariableDeclarator, + options: { + typeName: string; + } ): estree.VariableDeclarator; declare namespace exports_d_exports { - export { ExportDefaultResult, addNamespace, createDefault, createNamed }; + export { ExportDefaultResult, addNamespace, createDefault, createNamed }; } type ExportDefaultResult = { - astNode: estree.ExportDefaultDeclaration; - value: T; - isFallback: boolean; + astNode: estree.ExportDefaultDeclaration; + value: T; + isFallback: boolean; }; declare function createDefault( - node: estree.Program, - options: { - fallback: T; - }, + node: estree.Program, + options: { + fallback: T; + } ): ExportDefaultResult; declare function createNamed( - node: estree.Program, - options: { - name: string; - fallback: estree.VariableDeclaration; - }, + node: estree.Program, + options: { + name: string; + fallback: estree.VariableDeclaration; + } ): estree.ExportNamedDeclaration; declare function addNamespace( - node: estree.Program, - options: { - from: string; - as?: string; - }, + node: estree.Program, + options: { + from: string; + as?: string; + } ): void; declare namespace kit_d_exports { - export { addGlobalAppInterface, addHooksHandle }; + export { addGlobalAppInterface, addHooksHandle }; } declare function addGlobalAppInterface( - node: estree.TSProgram, - options: { - name: "Error" | "Locals" | "PageData" | "PageState" | "Platform"; - }, + node: estree.TSProgram, + options: { + name: 'Error' | 'Locals' | 'PageData' | 'PageState' | 'Platform'; + } ): estree.TSInterfaceDeclaration; declare function addHooksHandle( - node: estree.Program, - options: { - language: "ts" | "js"; - newHandleName: string; - handleContent: string; - comments: Comments; - }, + node: estree.Program, + options: { + language: 'ts' | 'js'; + newHandleName: string; + handleContent: string; + comments: Comments; + } ): void; declare namespace vite_d_exports { - export { addPlugin, configProperty, getConfig }; + export { addPlugin, configProperty, getConfig }; } declare const addPlugin: ( - ast: estree.Program, - options: { - code: string; - mode?: "append" | "prepend"; - }, + ast: estree.Program, + options: { + code: string; + mode?: 'append' | 'prepend'; + } ) => void; -declare function configProperty< - T extends estree.Expression | estree.Identifier, ->( - ast: estree.Program, - config: estree.ObjectExpression, - options: { - name: string; - fallback: T; - }, +declare function configProperty( + ast: estree.Program, + config: estree.ObjectExpression, + options: { + name: string; + fallback: T; + } ): T; declare const getConfig: (ast: estree.Program) => estree.ObjectExpression; declare namespace index_d_exports$3 { - export { - array_d_exports as array, - common_d_exports as common, - exports_d_exports as exports, - function_d_exports as functions, - imports_d_exports as imports, - kit_d_exports as kit, - object_d_exports as object, - variables_d_exports as variables, - vite_d_exports as vite, - }; + export { + array_d_exports as array, + common_d_exports as common, + exports_d_exports as exports, + function_d_exports as functions, + imports_d_exports as imports, + kit_d_exports as kit, + object_d_exports as object, + variables_d_exports as variables, + vite_d_exports as vite + }; } declare namespace index_d_exports$2 { - export { - addAttribute, - addFromRawHtml, - appendElement, - createElement, - insertElement, - }; + export { addAttribute, addFromRawHtml, appendElement, createElement, insertElement }; } declare function createElement( - tagName: string, - attributes?: Record, + tagName: string, + attributes?: Record ): SvelteAst.RegularElement; -declare function addAttribute( - element: SvelteAst.RegularElement, - name: string, - value: string, -): void; +declare function addAttribute(element: SvelteAst.RegularElement, name: string, value: string): void; declare function insertElement( - fragment: SvelteAst.Fragment, - elementToInsert: SvelteAst.Fragment["nodes"][0], + fragment: SvelteAst.Fragment, + elementToInsert: SvelteAst.Fragment['nodes'][0] ): void; declare function appendElement( - fragment: SvelteAst.Fragment, - elementToAppend: SvelteAst.Fragment["nodes"][0], -): void; -declare function addFromRawHtml( - fragment: SvelteAst.Fragment, - html: string, + fragment: SvelteAst.Fragment, + elementToAppend: SvelteAst.Fragment['nodes'][0] ): void; +declare function addFromRawHtml(fragment: SvelteAst.Fragment, html: string): void; declare namespace text_d_exports { - export { upsert }; + export { upsert }; } type CommentEntry = { - text: string; - mode: "append" | "prepend"; + text: string; + mode: 'append' | 'prepend'; }; type CommentOption = string | Array; declare function upsert( - content: string, - key: string, - options?: { - value?: string; - comment?: CommentOption; - separator?: boolean; - }, + content: string, + key: string, + options?: { + value?: string; + comment?: CommentOption; + separator?: boolean; + } ): string; declare namespace json_d_exports { - export { arrayUpsert, packageScriptsUpsert }; + export { arrayUpsert, packageScriptsUpsert }; } declare function arrayUpsert( - data: any, - key: string, - value: any, - options?: { - mode?: "append" | "prepend"; - }, + data: any, + key: string, + value: any, + options?: { + mode?: 'append' | 'prepend'; + } ): void; declare function packageScriptsUpsert( - data: any, - key: string, - value: string, - options?: { - mode?: "append" | "prepend"; - }, + data: any, + key: string, + value: string, + options?: { + mode?: 'append' | 'prepend'; + } ): void; declare namespace index_d_exports$4 { - export { RootWithInstance, addFragment, addSlot, ensureScript }; + export { RootWithInstance, addFragment, addSlot, ensureScript }; } type RootWithInstance = SvelteAst.Root & { - instance: SvelteAst.Script; + instance: SvelteAst.Script; }; declare function ensureScript( - ast: SvelteAst.Root, - options?: { - language?: "ts" | "js"; - }, + ast: SvelteAst.Root, + options?: { + language?: 'ts' | 'js'; + } ): asserts ast is RootWithInstance; declare function addSlot( - ast: SvelteAst.Root, - options: { - svelteVersion: string; - language?: "ts" | "js"; - }, + ast: SvelteAst.Root, + options: { + svelteVersion: string; + language?: 'ts' | 'js'; + } ): void; declare function addFragment( - ast: SvelteAst.Root, - content: string, - options?: { - mode?: "append" | "prepend"; - }, + ast: SvelteAst.Root, + content: string, + options?: { + mode?: 'append' | 'prepend'; + } ): void; type TransformFn = (content: string) => string; type TransformOptions = { - onError?: (error: unknown) => void; + onError?: (error: unknown) => void; }; declare const transforms: { - script( - cb: (file: { - ast: estree.Program; - comments: Comments; - content: string; - js: typeof index_d_exports$3; - }) => void | false, - options?: TransformOptions, - ): (content: string) => string; + script( + cb: (file: { + ast: estree.Program; + comments: Comments; + content: string; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions + ): (content: string) => string; - svelte( - cb: (file: { - ast: SvelteAst.Root; - content: string; - svelte: typeof index_d_exports$4; - js: typeof index_d_exports$3; - }) => void | false, - options?: TransformOptions, - ): (content: string) => string; + svelte( + cb: (file: { + ast: SvelteAst.Root; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions + ): (content: string) => string; - svelteScript( - scriptOptions: { - language: "ts" | "js"; - }, - cb: (file: { - ast: RootWithInstance; - content: string; - svelte: typeof index_d_exports$4; - js: typeof index_d_exports$3; - }) => void | false, - options?: TransformOptions, - ): TransformFn; + svelteScript( + scriptOptions: { + language: 'ts' | 'js'; + }, + cb: (file: { + ast: RootWithInstance; + content: string; + svelte: typeof index_d_exports$4; + js: typeof index_d_exports$3; + }) => void | false, + options?: TransformOptions + ): TransformFn; - css( - cb: (file: { - ast: Omit; - content: string; - css: typeof index_d_exports$1; - }) => void | false, - options?: TransformOptions, - ): TransformFn; + css( + cb: (file: { + ast: Omit; + content: string; + css: typeof index_d_exports$1; + }) => void | false, + options?: TransformOptions + ): TransformFn; - json( - cb: (file: { - data: T; - content: string; - json: typeof json_d_exports; - }) => void | false, - options?: TransformOptions, - ): TransformFn; + json( + cb: (file: { data: T; content: string; json: typeof json_d_exports }) => void | false, + options?: TransformOptions + ): TransformFn; - yaml( - cb: (file: { data: YamlDocument; content: string }) => void | false, - options?: TransformOptions, - ): TransformFn; + yaml( + cb: (file: { data: YamlDocument; content: string }) => void | false, + options?: TransformOptions + ): TransformFn; - toml( - cb: (file: { data: TomlTable; content: string }) => void | false, - options?: TransformOptions, - ): TransformFn; + toml( + cb: (file: { data: TomlTable; content: string }) => void | false, + options?: TransformOptions + ): TransformFn; - html( - cb: (file: { - ast: SvelteAst.Fragment; - content: string; - html: typeof index_d_exports$2; - }) => void | false, - options?: TransformOptions, - ): TransformFn; + html( + cb: (file: { + ast: SvelteAst.Fragment; + content: string; + html: typeof index_d_exports$2; + }) => void | false, + options?: TransformOptions + ): TransformFn; - text( - cb: (file: { - content: string; - text: typeof text_d_exports; - }) => string | false, - ): TransformFn; + text(cb: (file: { content: string; text: typeof text_d_exports }) => string | false): TransformFn; }; declare namespace pnpm_d_exports { - export { onlyBuiltDependencies }; + export { onlyBuiltDependencies }; } declare function onlyBuiltDependencies(...packages: string[]): TransformFn; type Version = { - major?: number; - minor?: number; - patch?: number; + major?: number; + minor?: number; + patch?: number; }; declare function splitVersion(str: string): Version; declare function isVersionUnsupportedBelow( - versionStr: string, - belowStr: string, + versionStr: string, + belowStr: string ): boolean | undefined; type Printer = (content: string, alt?: string) => string; declare function createPrinter(...conditions: boolean[]): Printer[]; -declare function sanitizeName( - name: string, - style: "package" | "wrangler", -): string; +declare function sanitizeName(name: string, style: 'package' | 'wrangler'): string; declare const downloadJson: (url: string) => Promise; type Package = { - name: string; - version: string; - dependencies?: Record; - devDependencies?: Record; - bugs?: string; - repository?: { - type: string; - url: string; - }; - keywords?: string[]; - workspaces?: string[]; + name: string; + version: string; + dependencies?: Record; + devDependencies?: Record; + bugs?: string; + repository?: { + type: string; + url: string; + }; + keywords?: string[]; + workspaces?: string[]; }; declare const commonFilePaths: { - readonly packageJson: "package.json"; - readonly svelteConfig: "svelte.config.js"; - readonly svelteConfigTS: "svelte.config.ts"; - readonly jsconfig: "jsconfig.json"; - readonly tsconfig: "tsconfig.json"; - readonly viteConfig: "vite.config.js"; - readonly viteConfigTS: "vite.config.ts"; + readonly packageJson: 'package.json'; + readonly svelteConfig: 'svelte.config.js'; + readonly svelteConfigTS: 'svelte.config.ts'; + readonly jsconfig: 'jsconfig.json'; + readonly tsconfig: 'tsconfig.json'; + readonly viteConfig: 'vite.config.js'; + readonly viteConfigTS: 'vite.config.ts'; }; declare function fileExists(cwd: string, filePath: string): boolean; @@ -813,9 +757,9 @@ declare function loadFile(cwd: string, filePath: string): string; declare function saveFile(cwd: string, filePath: string, content: string): void; declare function loadPackageJson(cwd: string): { - source: string; - data: Package; - generateCode: () => string; + source: string; + data: Package; + generateCode: () => string; }; /** * @deprecated Use {@link loadFile} instead. This alias will be removed in a future version. @@ -831,67 +775,67 @@ declare const writeFile: typeof saveFile; declare const getPackageJson: typeof loadPackageJson; type ColorInput = string | string[]; declare const color: { - addon: (str: ColorInput) => string; - command: (str: ColorInput) => string; - env: (str: ColorInput) => string; - path: (str: ColorInput) => string; - route: (str: ColorInput) => string; - website: (str: ColorInput) => string; - optional: (str: ColorInput) => string; - dim: (str: ColorInput) => string; - success: (str: ColorInput) => string; - warning: (str: ColorInput) => string; - error: (str: ColorInput) => string; - hidden: (str: ColorInput) => string; + addon: (str: ColorInput) => string; + command: (str: ColorInput) => string; + env: (str: ColorInput) => string; + path: (str: ColorInput) => string; + route: (str: ColorInput) => string; + website: (str: ColorInput) => string; + optional: (str: ColorInput) => string; + dim: (str: ColorInput) => string; + success: (str: ColorInput) => string; + warning: (str: ColorInput) => string; + error: (str: ColorInput) => string; + hidden: (str: ColorInput) => string; }; declare const parse: { - css: typeof parseCss; - html: typeof parseHtml; - json: typeof parseJson; - script: typeof parseScript; - svelte: typeof parseSvelte; - toml: typeof parseToml; - yaml: typeof parseYaml; + css: typeof parseCss; + html: typeof parseHtml; + json: typeof parseJson; + script: typeof parseScript; + svelte: typeof parseSvelte; + toml: typeof parseToml; + yaml: typeof parseYaml; }; export { - AGENTS, - type AgentName, - type estree as AstTypes, - COMMANDS, - type Comments, - type Package, - type SvelteAst, - type TransformFn, - index_d_exports as Walker, - type YamlDocument, - color, - commonFilePaths, - constructCommand, - createPrinter, - index_d_exports$1 as css, - dedent, - detect, - downloadJson, - fileExists, - getPackageJson, - index_d_exports$2 as html, - isVersionUnsupportedBelow, - index_d_exports$3 as js, - json_d_exports as json, - loadFile, - loadPackageJson, - parse, - pnpm_d_exports as pnpm, - readFile, - resolveCommand, - resolveCommandArray, - sanitizeName, - saveFile, - splitVersion, - index_d_exports$4 as svelte, - text_d_exports as text, - transforms, - writeFile, + AGENTS, + type AgentName, + type estree as AstTypes, + COMMANDS, + type Comments, + type Package, + type SvelteAst, + type TransformFn, + index_d_exports as Walker, + type YamlDocument, + color, + commonFilePaths, + constructCommand, + createPrinter, + index_d_exports$1 as css, + dedent, + detect, + downloadJson, + fileExists, + getPackageJson, + index_d_exports$2 as html, + isVersionUnsupportedBelow, + index_d_exports$3 as js, + json_d_exports as json, + loadFile, + loadPackageJson, + parse, + pnpm_d_exports as pnpm, + readFile, + resolveCommand, + resolveCommandArray, + sanitizeName, + saveFile, + splitVersion, + index_d_exports$4 as svelte, + text_d_exports as text, + transforms, + writeFile }; ``` diff --git a/packages/sv-utils/src/pm.ts b/packages/sv-utils/src/pm.ts index fd01d791c..660b23c6a 100644 --- a/packages/sv-utils/src/pm.ts +++ b/packages/sv-utils/src/pm.ts @@ -8,6 +8,7 @@ import { type Agent, type Command } from 'package-manager-detector'; + export { AGENTS, type AgentName, diff --git a/packages/sv-utils/src/tooling/parsers.ts b/packages/sv-utils/src/tooling/parsers.ts index a20a93803..6ae53f255 100644 --- a/packages/sv-utils/src/tooling/parsers.ts +++ b/packages/sv-utils/src/tooling/parsers.ts @@ -64,8 +64,7 @@ export function parseJson(source: string): { data: any } & ParseBase { export function parseYaml(source: string): { data: YamlDocument } & ParseBase { if (!source) source = ''; const data = utils.parseYaml(source); - const generateCode = () => - utils.serializeYaml(data as Parameters[0]); + const generateCode = () => utils.serializeYaml(data as Parameters[0]); return { data: data as YamlDocument, source, generateCode }; } diff --git a/packages/sv/api-surface-testing.md b/packages/sv/api-surface-testing.md index f9c1c9a71..6295a1d41 100644 --- a/packages/sv/api-surface-testing.md +++ b/packages/sv/api-surface-testing.md @@ -3,123 +3,111 @@ ```ts -type ProjectVariant = "kit-js" | "kit-ts" | "vite-js" | "vite-ts"; +type ProjectVariant = 'kit-js' | 'kit-ts' | 'vite-js' | 'vite-ts'; declare const variants: ProjectVariant[]; type CreateProject = (options: { - testId: string; - variant: ProjectVariant; - clean?: boolean; + testId: string; + variant: ProjectVariant; + clean?: boolean; }) => string; type SetupOptions = { - cwd: string; - variants: readonly ProjectVariant[]; - clean?: boolean; + cwd: string; + variants: readonly ProjectVariant[]; + clean?: boolean; }; /** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ declare function setup({ cwd, clean, variants }: SetupOptions): { - templatesDir: string; + templatesDir: string; }; type CreateOptions = { - cwd: string; - testName: string; - templatesDir: string; + cwd: string; + testName: string; + templatesDir: string; }; /** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ -declare function createProject({ - cwd, - testName, - templatesDir, -}: CreateOptions): CreateProject; +declare function createProject({ cwd, testName, templatesDir }: CreateOptions): CreateProject; type PreviewOptions = { - cwd: string; - command?: string; + cwd: string; + command?: string; }; /** @deprecated Internal helper used by `prepareServer` - will be removed from public API in a future version. */ declare function startPreview({ cwd, command }: PreviewOptions): Promise<{ - url: string; - close: () => Promise; + url: string; + close: () => Promise; }>; -declare module "vitest" { - interface ProvidedContext { - testDir: string; - templatesDir: string; - variants: ProjectVariant[]; - } +declare module 'vitest' { + interface ProvidedContext { + testDir: string; + templatesDir: string; + variants: ProjectVariant[]; + } } declare function setupGlobal({ - TEST_DIR, - pre, - post, + TEST_DIR, + pre, + post }: { - TEST_DIR: string; - pre?: () => Promise; - post?: () => Promise; + TEST_DIR: string; + pre?: () => Promise; + post?: () => Promise; }): ({ provide }: TestProject) => Promise<() => Promise>; type Fixtures = { - page: Page; - cwd(addonTestCase: AddonTestCase): string; + page: Page; + cwd(addonTestCase: AddonTestCase): string; }; type AddonTestCase = { - variant: ProjectVariant; - kind: { - type: string; - options: OptionMap; - }; + variant: ProjectVariant; + kind: { + type: string; + options: OptionMap; + }; }; type SetupTestOptions = { - kinds: Array["kind"]>; - filter?: (addonTestCase: AddonTestCase) => boolean; - browser?: boolean; - preAdd?: (o: { - addonTestCase: AddonTestCase; - cwd: string; - }) => Promise | void; + kinds: Array['kind']>; + filter?: (addonTestCase: AddonTestCase) => boolean; + browser?: boolean; + preAdd?: (o: { addonTestCase: AddonTestCase; cwd: string }) => Promise | void; }; type PrepareServerOptions = { - cwd: string; - page: Page; - buildCommand?: string; - previewCommand?: string; + cwd: string; + page: Page; + buildCommand?: string; + previewCommand?: string; }; type PrepareServerReturn = { - url: string; - close: () => Promise; + url: string; + close: () => Promise; }; declare function prepareServer({ - cwd, - page, - buildCommand, - previewCommand, + cwd, + page, + buildCommand, + previewCommand }: PrepareServerOptions): Promise; -type VitestContext = Pick< - typeof vitest, - "inject" | "test" | "beforeAll" | "beforeEach" ->; -declare function createSetupTest(vitest: VitestContext): < - Addons extends AddonMap, ->( - addons: Addons, - options?: SetupTestOptions, +type VitestContext = Pick; +declare function createSetupTest(vitest: VitestContext): ( + addons: Addons, + options?: SetupTestOptions ) => { - test: vitest.TestAPI; - testCases: Array>; - prepareServer: typeof prepareServer; + test: vitest.TestAPI; + testCases: Array>; + prepareServer: typeof prepareServer; }; export { - AddonTestCase, - CreateProject, - Fixtures, - PrepareServerOptions, - PrepareServerReturn, - ProjectVariant, - SetupTestOptions, - VitestContext, - createProject, - createSetupTest, - prepareServer, - setup, - setupGlobal, - startPreview, - variants, + AddonTestCase, + CreateProject, + Fixtures, + PrepareServerOptions, + PrepareServerReturn, + ProjectVariant, + SetupTestOptions, + VitestContext, + createProject, + createSetupTest, + prepareServer, + setup, + setupGlobal, + startPreview, + variants }; ``` diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md index f9ccdfbd9..7a98dcb58 100644 --- a/packages/sv/api-surface.md +++ b/packages/sv/api-surface.md @@ -5,65 +5,59 @@ ```ts type TemplateType = (typeof templateTypes)[number]; type LanguageType = (typeof languageTypes)[number]; -declare const templateTypes: readonly [ - "minimal", - "demo", - "library", - "addon", - "svelte", -]; -declare const languageTypes: readonly ["typescript", "checkjs", "none"]; +declare const templateTypes: readonly ['minimal', 'demo', 'library', 'addon', 'svelte']; +declare const languageTypes: readonly ['typescript', 'checkjs', 'none']; type Options = { - cwd: string; - name: string; - template: TemplateType; - types: LanguageType; + cwd: string; + name: string; + template: TemplateType; + types: LanguageType; }; -declare function create(cwd: string, options: Omit): void; +declare function create(cwd: string, options: Omit): void; declare function create(options: Options): void; type FileEditor = Workspace & { - content: string; + content: string; }; type FileType = { - name: (options: Workspace) => string; - condition?: ConditionDefinition; - content: (editor: FileEditor) => string; + name: (options: Workspace) => string; + condition?: ConditionDefinition; + content: (editor: FileEditor) => string; }; export { - type Addon, - type AddonDefinition, - type AddonInput, - type AddonMap, - type AddonReference, - type AddonResult, - type AddonSource, - type BaseQuestion, - type BooleanQuestion, - type ConfiguredAddon, - type FileEditor, - type FileType, - type InstallOptions, - type LanguageType, - type LoadedAddon, - type MultiSelectQuestion, - type NumberQuestion, - type OptionBuilder, - type OptionDefinition, - type OptionMap, - type OptionValues, - type PreparedAddon, - type Question, - type SelectQuestion, - type SetupResult, - type StringQuestion, - type SvApi, - type TemplateType, - type Workspace, - type WorkspaceOptions, - add, - create, - defineAddon, - defineAddonOptions, - officialAddons, + type Addon, + type AddonDefinition, + type AddonInput, + type AddonMap, + type AddonReference, + type AddonResult, + type AddonSource, + type BaseQuestion, + type BooleanQuestion, + type ConfiguredAddon, + type FileEditor, + type FileType, + type InstallOptions, + type LanguageType, + type LoadedAddon, + type MultiSelectQuestion, + type NumberQuestion, + type OptionBuilder, + type OptionDefinition, + type OptionMap, + type OptionValues, + type PreparedAddon, + type Question, + type SelectQuestion, + type SetupResult, + type StringQuestion, + type SvApi, + type TemplateType, + type Workspace, + type WorkspaceOptions, + add, + create, + defineAddon, + defineAddonOptions, + officialAddons }; ``` diff --git a/packages/sv/src/create/index.ts b/packages/sv/src/create/index.ts index 1c30c199b..5b78b6c45 100644 --- a/packages/sv/src/create/index.ts +++ b/packages/sv/src/create/index.ts @@ -35,10 +35,7 @@ export type Common = { export function create(cwd: string, options: Omit): void; export function create(options: Options): void; -export function create( - cwdOrOptions: string | Options, - legacyOptions?: Omit -): void { +export function create(cwdOrOptions: string | Options, legacyOptions?: Omit): void { let cwd: string; let options: Omit; if (typeof cwdOrOptions === 'string') { From a294ebb2c4a656a77cd02f4407c1bdd677a2f0bd Mon Sep 17 00:00:00 2001 From: jycouet Date: Sat, 4 Apr 2026 23:30:29 +0200 Subject: [PATCH 16/31] chore(sv-testing): remove deprecated exports from public API; docs use eslint.config.js path Made-with: Cursor --- documentation/docs/50-api/20-sv-utils.md | 2 +- packages/sv/api-surface-testing.md | 28 ------------------------ packages/sv/src/testing.ts | 12 +++++----- 3 files changed, 7 insertions(+), 35 deletions(-) diff --git a/documentation/docs/50-api/20-sv-utils.md b/documentation/docs/50-api/20-sv-utils.md index b8dcccf43..3e5a543cf 100644 --- a/documentation/docs/50-api/20-sv-utils.md +++ b/documentation/docs/50-api/20-sv-utils.md @@ -137,7 +137,7 @@ Return `false` from any transform callback to abort - the original content is re import { transforms } from '@sveltejs/sv-utils'; sv.file( - file.eslintConfig, + 'eslint.config.js', transforms.script(({ ast, js }) => { const { value: existing } = js.exports.createDefault(ast, { fallback: myConfig }); if (existing !== myConfig) { diff --git a/packages/sv/api-surface-testing.md b/packages/sv/api-surface-testing.md index 6295a1d41..5f0ded335 100644 --- a/packages/sv/api-surface-testing.md +++ b/packages/sv/api-surface-testing.md @@ -10,31 +10,6 @@ type CreateProject = (options: { variant: ProjectVariant; clean?: boolean; }) => string; -type SetupOptions = { - cwd: string; - variants: readonly ProjectVariant[]; - clean?: boolean; -}; -/** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ -declare function setup({ cwd, clean, variants }: SetupOptions): { - templatesDir: string; -}; -type CreateOptions = { - cwd: string; - testName: string; - templatesDir: string; -}; -/** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ -declare function createProject({ cwd, testName, templatesDir }: CreateOptions): CreateProject; -type PreviewOptions = { - cwd: string; - command?: string; -}; -/** @deprecated Internal helper used by `prepareServer` - will be removed from public API in a future version. */ -declare function startPreview({ cwd, command }: PreviewOptions): Promise<{ - url: string; - close: () => Promise; -}>; declare module 'vitest' { interface ProvidedContext { testDir: string; @@ -102,12 +77,9 @@ export { ProjectVariant, SetupTestOptions, VitestContext, - createProject, createSetupTest, prepareServer, - setup, setupGlobal, - startPreview, variants }; ``` diff --git a/packages/sv/src/testing.ts b/packages/sv/src/testing.ts index 02d6c14b2..25e0ec874 100644 --- a/packages/sv/src/testing.ts +++ b/packages/sv/src/testing.ts @@ -28,8 +28,8 @@ type SetupOptions = { /** @default false */ clean?: boolean; }; -/** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ -export function setup({ cwd, clean = false, variants }: SetupOptions): { templatesDir: string } { + +function setup({ cwd, clean = false, variants }: SetupOptions): { templatesDir: string } { const workingDir = path.resolve(cwd); if (clean && fs.existsSync(workingDir)) { fs.rmSync(workingDir, { force: true, recursive: true }); @@ -59,8 +59,8 @@ export function setup({ cwd, clean = false, variants }: SetupOptions): { templat } type CreateOptions = { cwd: string; testName: string; templatesDir: string }; -/** @deprecated Internal helper used by `createSetupTest` - will be removed from public API in a future version. */ -export function createProject({ cwd, testName, templatesDir }: CreateOptions): CreateProject { + +function createProject({ cwd, testName, templatesDir }: CreateOptions): CreateProject { // create the reference dir const testDir = path.resolve(cwd, testName); fs.mkdirSync(testDir, { recursive: true }); @@ -76,8 +76,8 @@ export function createProject({ cwd, testName, templatesDir }: CreateOptions): C } type PreviewOptions = { cwd: string; command?: string }; -/** @deprecated Internal helper used by `prepareServer` - will be removed from public API in a future version. */ -export async function startPreview({ + +async function startPreview({ cwd, command = 'npm run preview' }: PreviewOptions): Promise<{ url: string; close: () => Promise }> { From 0bc3d68e62dea3eafbfa95c5be4b652fe24744a3 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sun, 5 Apr 2026 00:12:06 +0200 Subject: [PATCH 17/31] fix(sv-utils): type onlyBuiltDependencies from YamlDocument.get YamlDocument.get returns unknown; assert minimal shape before reading .items so tsgo check passes. Made-with: Cursor --- packages/sv-utils/src/pnpm.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/sv-utils/src/pnpm.ts b/packages/sv-utils/src/pnpm.ts index aa86f928e..c7979e8f3 100644 --- a/packages/sv-utils/src/pnpm.ts +++ b/packages/sv-utils/src/pnpm.ts @@ -12,7 +12,9 @@ import { transforms, type TransformFn } from './tooling/transforms.ts'; */ export function onlyBuiltDependencies(...packages: string[]): TransformFn { return transforms.yaml(({ data }) => { - const existing = data.get('onlyBuiltDependencies'); + const existing = data.get('onlyBuiltDependencies') as + | { items?: Array<{ value: string } | string> } + | undefined; const items: Array<{ value: string } | string> = existing?.items ?? []; for (const pkg of packages) { if (items.includes(pkg)) continue; From dc30d9de7eab2b92f02ec30fa3bed2cc89d88b72 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sun, 5 Apr 2026 00:14:30 +0200 Subject: [PATCH 18/31] chore: consolidate minor changeset for sv and @sveltejs/sv-utils Made-with: Cursor --- .changeset/coupling-sv-and-sv-utils.md | 23 ++++++++++++++++++++++ .changeset/remove-pnpm-build-dependency.md | 6 ------ .changeset/some-rings-appear.md | 6 ------ 3 files changed, 23 insertions(+), 12 deletions(-) create mode 100644 .changeset/coupling-sv-and-sv-utils.md delete mode 100644 .changeset/remove-pnpm-build-dependency.md delete mode 100644 .changeset/some-rings-appear.md diff --git a/.changeset/coupling-sv-and-sv-utils.md b/.changeset/coupling-sv-and-sv-utils.md new file mode 100644 index 000000000..37eec0807 --- /dev/null +++ b/.changeset/coupling-sv-and-sv-utils.md @@ -0,0 +1,23 @@ +--- +'sv': minor +'@sveltejs/sv-utils': minor +--- + +feat: sv / sv-utils coupling, pnpm helpers, experimental add-ons, and API snapshots + +**Highlights** + +- Community add-ons are now **experimental**. +- Replace `sv.pnpmBuildDependency` with `sv.file` plus `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` and `file.findUp`. + +**`@sveltejs/sv-utils`** + +- Add `pnpm.onlyBuiltDependencies` to append packages to `onlyBuiltDependencies` in pnpm YAML via `transforms.yaml`. +- Type `YamlDocument` (`parse.yaml`) with `get` / `set` using `unknown` so consumers narrow explicitly; align YAML transforms with that contract. + +**`sv`** + +- Refactor workspace / engine / package-manager flows around file IO and package JSON loading (`loadFile`, `saveFile`, `loadPackageJson`), and trim workspace addon path handling; update addons accordingly. +- Reorganize the public `testing` entry for Vitest helpers and document the surface. +- Add generated `api-surface` markdown snapshots and a `scripts/generate-api-surface.js` helper (wired through the build) to track the public API. +- Remove deprecated `pnpmBuildDependency` usage and stop exporting internal pnpm-only-built helpers from the public `sv` surface. diff --git a/.changeset/remove-pnpm-build-dependency.md b/.changeset/remove-pnpm-build-dependency.md deleted file mode 100644 index 41b340900..000000000 --- a/.changeset/remove-pnpm-build-dependency.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'sv': minor -'@sveltejs/sv-utils': minor ---- - -feat: replace `sv.pnpmBuildDependency` with `sv.file` + `pnpm.onlyBuiltDependencies` helper and `file.findUp` diff --git a/.changeset/some-rings-appear.md b/.changeset/some-rings-appear.md deleted file mode 100644 index 249478187..000000000 --- a/.changeset/some-rings-appear.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'sv': minor -'@sveltejs/sv-utils': minor ---- - -feat: community add-ons are now **experimental** From 4c58d50c8cacdb6c12b8daff078b479f33b99fd4 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sun, 5 Apr 2026 01:11:47 +0200 Subject: [PATCH 19/31] gen improvement --- package.json | 1 + packages/sv/api-surface.md | 3 +- packages/sv/src/create/index.ts | 14 +------- scripts/generate-api-surface.js | 60 ++++++++++++++++++++++++--------- tsdown.config.ts | 26 +------------- 5 files changed, 48 insertions(+), 56 deletions(-) diff --git a/package.json b/package.json index caf32fd8c..b9d98b03c 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ }, "scripts": { "build": "tsdown", + "postbuild": "node scripts/generate-api-surface.js", "changeset:publish": "changeset publish", "check": "pnpm --parallel check", "dev": "tsdown -w & pnpm --parallel check -w & wait", diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md index 7a98dcb58..77af976cf 100644 --- a/packages/sv/api-surface.md +++ b/packages/sv/api-surface.md @@ -13,8 +13,7 @@ type Options = { template: TemplateType; types: LanguageType; }; -declare function create(cwd: string, options: Omit): void; -declare function create(options: Options): void; +declare function create({ cwd, ...options }: Options): void; type FileEditor = Workspace & { content: string; }; diff --git a/packages/sv/src/create/index.ts b/packages/sv/src/create/index.ts index 5b78b6c45..489882157 100644 --- a/packages/sv/src/create/index.ts +++ b/packages/sv/src/create/index.ts @@ -33,19 +33,7 @@ export type Common = { }>; }; -export function create(cwd: string, options: Omit): void; -export function create(options: Options): void; -export function create(cwdOrOptions: string | Options, legacyOptions?: Omit): void { - let cwd: string; - let options: Omit; - if (typeof cwdOrOptions === 'string') { - cwd = cwdOrOptions; - options = legacyOptions!; - } else { - cwd = cwdOrOptions.cwd; - options = cwdOrOptions; - } - +export function create({ cwd, ...options }: Options): void { mkdirp(cwd); write_template_files(options.template, options.types, options.name, cwd); diff --git a/scripts/generate-api-surface.js b/scripts/generate-api-surface.js index 811c44d7e..e1f3c03d4 100644 --- a/scripts/generate-api-surface.js +++ b/scripts/generate-api-surface.js @@ -1,24 +1,23 @@ /** - * Reads the generated .d.mts files and produces a cleaned-up - * api-surface.md for each package. Strips `//#region` / `//#endregion` - * directives, `//# sourceMappingURL=...` lines, non-deprecated JSDoc, import-only lines, - * and blank runs so the result is a compact, diff-friendly snapshot - * of the public API. JSDoc blocks that contain `@deprecated` are kept - * in full. + * Reads generated `.d.mts` files and writes compact `api-surface.md` snapshots per package. * - * Run: node scripts/generate-api-surface.js - * Or: invoked from tsdown `build:done` after all configs finish (see tsdown.config.ts). + * Strips region/source-map directives, non-deprecated block comments, import-only lines, + * and excess blank lines. Blocks mentioning `@deprecated` are kept verbatim. * - * Finishes with Prettier (repo root config) so snapshots match `pnpm format`. + * @remarks + * Run: `node scripts/generate-api-surface.js` — or via root `postbuild` after `pnpm build`. + * Output is formatted with Prettier using the repo root `prettier.config.js` so it matches `pnpm format`. */ import fs from 'node:fs'; import path from 'node:path'; import process from 'node:process'; import { fileURLToPath } from 'node:url'; -import * as prettier from 'prettier'; +import prettier from 'prettier'; const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +/** Absolute path to the repo Prettier config (explicit so formatting does not depend on cwd). */ +const PRETTIER_CONFIG = path.join(ROOT, 'prettier.config.js'); const packages = [ { @@ -38,7 +37,11 @@ const packages = [ } ]; -/** Remove `//#region` / `//#endregion` lines emitted by the DTS bundler. */ +/** + * Remove `//#region` / `//#endregion` lines emitted by the DTS bundler. + * @param {string} source + * @returns {string} + */ function stripRegionDirectives(source) { return source .split('\n') @@ -46,7 +49,11 @@ function stripRegionDirectives(source) { .join('\n'); } -/** Remove `//# sourceMappingURL=...` lines from declaration emit. */ +/** + * Remove `//# sourceMappingURL=...` lines from declaration emit. + * @param {string} source + * @returns {string} + */ function stripSourceMappingUrl(source) { return source .split('\n') @@ -55,8 +62,9 @@ function stripSourceMappingUrl(source) { } /** - * Remove `/** ... *\/` blocks unless they contain `@deprecated`, in which case - * the full block is preserved (including inline trailing JSDoc on a line). + * Remove slash-star-star block comments unless they contain `@deprecated` (full block kept). + * @param {string} source + * @returns {string} */ function stripJsDoc(source) { return source.replace(/\/\*\*[\s\S]*?\*\//g, (match) => { @@ -67,18 +75,32 @@ function stripJsDoc(source) { }); } +/** + * Drop top-level `import …` lines (types-only noise in the snapshot). + * @param {string} source + * @returns {string} + */ function stripImportLines(source) { - // Remove `import ...` lines that are only used for type resolution return source .split('\n') .filter((line) => !line.match(/^import\s/)) .join('\n'); } +/** + * Collapse three or more consecutive newlines to two. + * @param {string} source + * @returns {string} + */ function collapseBlankLines(source) { return source.replace(/\n{3,}/g, '\n\n'); } +/** + * Apply all cleaning steps to declaration text. + * @param {string} source + * @returns {string} + */ function clean(source) { let result = stripRegionDirectives(source); result = stripSourceMappingUrl(result); @@ -89,11 +111,17 @@ function clean(source) { } /** + * Format a file with repo Prettier options (plugins + overrides). * @param {string} absPath absolute path to the markdown file + * @returns {Promise} */ async function formatWithPrettier(absPath) { const raw = fs.readFileSync(absPath, 'utf8'); - const formatted = await prettier.format(raw, { filepath: absPath }); + const options = + (await prettier.resolveConfig(absPath, { + config: PRETTIER_CONFIG + })) ?? {}; + const formatted = await prettier.format(raw, { ...options, filepath: absPath }); fs.writeFileSync(absPath, formatted, 'utf8'); } diff --git a/tsdown.config.ts b/tsdown.config.ts index ce4017a73..da4d41568 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -3,23 +3,6 @@ import process from 'node:process'; import { defineConfig } from 'tsdown'; import { buildTemplates } from './packages/sv/src/create/scripts/build-templates.js'; -/** - * tsdown runs each `defineConfig` entry in parallel. There is no single - * "all builds finished" hook, so we count `build:done` (must match the number - * of config objects below) and run api-surface generation once all `.d.mts` - * outputs exist. - */ -const API_SURFACE_CONFIG_COUNT = 3; -let apiSurfaceBuildsDone = 0; - -function hookApiSurfaceBuildDone(): void | Promise { - apiSurfaceBuildsDone++; - if (apiSurfaceBuildsDone === API_SURFACE_CONFIG_COUNT) { - apiSurfaceBuildsDone = 0; - return import('./scripts/generate-api-surface.js').then((m) => m.generateApiSurface()); - } -} - export default defineConfig([ { cwd: path.resolve('packages/sv'), @@ -74,8 +57,7 @@ export default defineConfig([ hooks: { async 'build:before'() { await buildCliTemplates(); - }, - 'build:done': () => hookApiSurfaceBuildDone() + } } }, // sv-utils: runtime build (bundles everything including svelte) @@ -106,9 +88,6 @@ export default defineConfig([ 'yaml', 'zimmerframe' ] - }, - hooks: { - 'build:done': () => hookApiSurfaceBuildDone() } }, // sv-utils: DTS-only build (svelte externalized) @@ -133,9 +112,6 @@ export default defineConfig([ 'package-manager-detector' ], onlyBundle: ['smol-toml', 'zimmerframe'] - }, - hooks: { - 'build:done': () => hookApiSurfaceBuildDone() } } ]); From b02f0d7a75264567d06b5e6beb5e3b590203a114 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sun, 5 Apr 2026 01:26:10 +0200 Subject: [PATCH 20/31] move things --- packages/sv-utils/api-surface.md | 27 +------------------------- packages/sv-utils/src/files.ts | 29 ++-------------------------- packages/sv-utils/src/index.ts | 22 +-------------------- packages/sv/src/cli/create.ts | 9 ++++++--- packages/sv/src/core/common.ts | 10 ++++++++++ packages/sv/src/core/engine.ts | 2 +- packages/sv/src/core/workspace.ts | 2 +- packages/sv/src/create/index.ts | 3 ++- packages/sv/src/create/playground.ts | 4 ++-- 9 files changed, 26 insertions(+), 82 deletions(-) diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index 1e5050d6e..d6d69bc91 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -742,15 +742,6 @@ type Package = { keywords?: string[]; workspaces?: string[]; }; -declare const commonFilePaths: { - readonly packageJson: 'package.json'; - readonly svelteConfig: 'svelte.config.js'; - readonly svelteConfigTS: 'svelte.config.ts'; - readonly jsconfig: 'jsconfig.json'; - readonly tsconfig: 'tsconfig.json'; - readonly viteConfig: 'vite.config.js'; - readonly viteConfigTS: 'vite.config.ts'; -}; declare function fileExists(cwd: string, filePath: string): boolean; declare function loadFile(cwd: string, filePath: string): string; @@ -761,18 +752,6 @@ declare function loadPackageJson(cwd: string): { data: Package; generateCode: () => string; }; -/** - * @deprecated Use {@link loadFile} instead. This alias will be removed in a future version. - */ -declare const readFile: typeof loadFile; -/** - * @deprecated Use {@link saveFile} instead. This alias will be removed in a future version. - */ -declare const writeFile: typeof saveFile; -/** - * @deprecated Use {@link loadPackageJson} instead. This alias will be removed in a future version. - */ -declare const getPackageJson: typeof loadPackageJson; type ColorInput = string | string[]; declare const color: { addon: (str: ColorInput) => string; @@ -810,7 +789,6 @@ export { index_d_exports as Walker, type YamlDocument, color, - commonFilePaths, constructCommand, createPrinter, index_d_exports$1 as css, @@ -818,7 +796,6 @@ export { detect, downloadJson, fileExists, - getPackageJson, index_d_exports$2 as html, isVersionUnsupportedBelow, index_d_exports$3 as js, @@ -827,7 +804,6 @@ export { loadPackageJson, parse, pnpm_d_exports as pnpm, - readFile, resolveCommand, resolveCommandArray, sanitizeName, @@ -835,7 +811,6 @@ export { splitVersion, index_d_exports$4 as svelte, text_d_exports as text, - transforms, - writeFile + transforms }; ``` diff --git a/packages/sv-utils/src/files.ts b/packages/sv-utils/src/files.ts index 8b6dc2488..233a11323 100644 --- a/packages/sv-utils/src/files.ts +++ b/packages/sv-utils/src/files.ts @@ -13,16 +13,6 @@ export type Package = { workspaces?: string[]; }; -export const commonFilePaths = { - packageJson: 'package.json', - svelteConfig: 'svelte.config.js', - svelteConfigTS: 'svelte.config.ts', - jsconfig: 'jsconfig.json', - tsconfig: 'tsconfig.json', - viteConfig: 'vite.config.js', - viteConfigTS: 'vite.config.ts' -} as const; - export function fileExists(cwd: string, filePath: string): boolean { const fullFilePath = path.resolve(cwd, filePath); return fs.existsSync(fullFilePath); @@ -60,27 +50,12 @@ export function loadPackageJson(cwd: string): { data: Package; generateCode: () => string; } { - const packageText = loadFile(cwd, commonFilePaths.packageJson); + const packageText = loadFile(cwd, 'package.json'); if (!packageText) { - const pkgPath = path.join(cwd, commonFilePaths.packageJson); + const pkgPath = path.join(cwd, 'package.json'); throw new Error(`Invalid workspace: missing '${pkgPath}'`); } const { data, generateCode } = parseJson(packageText); return { source: packageText, data: data as Package, generateCode }; } - -/** - * @deprecated Use {@link loadFile} instead. This alias will be removed in a future version. - */ -export const readFile: typeof loadFile = loadFile; - -/** - * @deprecated Use {@link saveFile} instead. This alias will be removed in a future version. - */ -export const writeFile: typeof saveFile = saveFile; - -/** - * @deprecated Use {@link loadPackageJson} instead. This alias will be removed in a future version. - */ -export const getPackageJson: typeof loadPackageJson = loadPackageJson; diff --git a/packages/sv-utils/src/index.ts b/packages/sv-utils/src/index.ts index d8615802c..74f334c47 100644 --- a/packages/sv-utils/src/index.ts +++ b/packages/sv-utils/src/index.ts @@ -73,27 +73,7 @@ export { sanitizeName } from './sanitize.ts'; export { downloadJson } from './downloadJson.ts'; // File system helpers (sync, workspace-relative paths) -export { - commonFilePaths, - fileExists, - loadFile, - loadPackageJson, - saveFile, - type Package -} from './files.ts'; - -/** - * @deprecated Use {@link loadFile} instead. This alias will be removed in a future version. - */ -export { readFile } from './files.ts'; -/** - * @deprecated Use {@link saveFile} instead. This alias will be removed in a future version. - */ -export { writeFile } from './files.ts'; -/** - * @deprecated Use {@link loadPackageJson} instead. This alias will be removed in a future version. - */ -export { getPackageJson } from './files.ts'; +export { fileExists, loadFile, loadPackageJson, saveFile, type Package } from './files.ts'; // Terminal styling export { color } from './color.ts'; diff --git a/packages/sv/src/cli/create.ts b/packages/sv/src/cli/create.ts index f8793efc2..b727a6425 100644 --- a/packages/sv/src/cli/create.ts +++ b/packages/sv/src/cli/create.ts @@ -1,5 +1,5 @@ import * as p from '@clack/prompts'; -import { color, commonFilePaths, loadPackageJson, resolveCommandArray } from '@sveltejs/sv-utils'; +import { color, loadPackageJson, resolveCommandArray } from '@sveltejs/sv-utils'; import { Command, Option } from 'commander'; import fs from 'node:fs'; import path from 'node:path'; @@ -468,8 +468,11 @@ export async function createVirtualWorkspace({ language: type === 'typescript' ? 'ts' : 'js', file: { ...tentativeWorkspace.file, - viteConfig: type === 'typescript' ? commonFilePaths.viteConfigTS : commonFilePaths.viteConfig, - svelteConfig: commonFilePaths.svelteConfig // currently we always use js files, never typescript files + viteConfig: + type === 'typescript' + ? common.commonFilePaths.viteConfigTS + : common.commonFilePaths.viteConfig, + svelteConfig: common.commonFilePaths.svelteConfig // currently we always use js files, never typescript files } }; diff --git a/packages/sv/src/core/common.ts b/packages/sv/src/core/common.ts index aace74cc8..c834a08a7 100644 --- a/packages/sv/src/core/common.ts +++ b/packages/sv/src/core/common.ts @@ -324,3 +324,13 @@ export function updateAgent( fs.writeFileSync(agentPath, content); } } + +export const commonFilePaths = { + packageJson: 'package.json', + svelteConfig: 'svelte.config.js', + svelteConfigTS: 'svelte.config.ts', + jsconfig: 'jsconfig.json', + tsconfig: 'tsconfig.json', + viteConfig: 'vite.config.js', + viteConfigTS: 'vite.config.ts' +} as const; diff --git a/packages/sv/src/core/engine.ts b/packages/sv/src/core/engine.ts index c9bdeb1ff..7cb87c48d 100644 --- a/packages/sv/src/core/engine.ts +++ b/packages/sv/src/core/engine.ts @@ -1,7 +1,6 @@ import * as p from '@clack/prompts'; import { color, - commonFilePaths, fileExists, loadFile, loadPackageJson, @@ -11,6 +10,7 @@ import { } from '@sveltejs/sv-utils'; import { NonZeroExitError, exec } from 'tinyexec'; import { createLoadedAddon } from '../cli/add.ts'; +import { commonFilePaths } from './common.ts'; import { getErrorHint, type Addon, diff --git a/packages/sv/src/core/workspace.ts b/packages/sv/src/core/workspace.ts index cb38bcb9b..35ceac23c 100644 --- a/packages/sv/src/core/workspace.ts +++ b/packages/sv/src/core/workspace.ts @@ -3,13 +3,13 @@ import { type AstTypes, js, parse, - commonFilePaths, loadFile, loadPackageJson } from '@sveltejs/sv-utils'; import * as find from 'empathic/find'; import fs from 'node:fs'; import path from 'node:path'; +import { commonFilePaths } from './common.ts'; import type { OptionDefinition, OptionValues } from './options.ts'; import { detectPackageManager } from './package-manager.ts'; diff --git a/packages/sv/src/create/index.ts b/packages/sv/src/create/index.ts index 489882157..ffe49c5ee 100644 --- a/packages/sv/src/create/index.ts +++ b/packages/sv/src/create/index.ts @@ -1,6 +1,7 @@ -import { sanitizeName, commonFilePaths } from '@sveltejs/sv-utils'; +import { sanitizeName } from '@sveltejs/sv-utils'; import fs from 'node:fs'; import path from 'node:path'; +import { commonFilePaths } from '../core/common.ts'; import { mkdirp, copy, dist, getSharedFiles, replace, kv } from './utils.ts'; export type TemplateType = (typeof templateTypes)[number]; diff --git a/packages/sv/src/create/playground.ts b/packages/sv/src/create/playground.ts index ae2fae244..f93788126 100644 --- a/packages/sv/src/create/playground.ts +++ b/packages/sv/src/create/playground.ts @@ -5,11 +5,11 @@ import { parse, svelte, downloadJson, - Walker, - commonFilePaths + Walker } from '@sveltejs/sv-utils'; import fs from 'node:fs'; import path from 'node:path'; +import { commonFilePaths } from '../core/common.ts'; import { getSharedFiles } from './utils.ts'; export function validatePlaygroundUrl(link: string): boolean { From 86fcf2442b0d6c9d73a78983d8dccc4bab2bac25 Mon Sep 17 00:00:00 2001 From: jycouet Date: Sun, 5 Apr 2026 01:35:15 +0200 Subject: [PATCH 21/31] cs --- .changeset/coupling-sv-and-sv-utils.md | 1 - 1 file changed, 1 deletion(-) diff --git a/.changeset/coupling-sv-and-sv-utils.md b/.changeset/coupling-sv-and-sv-utils.md index 37eec0807..f7232eff5 100644 --- a/.changeset/coupling-sv-and-sv-utils.md +++ b/.changeset/coupling-sv-and-sv-utils.md @@ -7,7 +7,6 @@ feat: sv / sv-utils coupling, pnpm helpers, experimental add-ons, and API snapsh **Highlights** -- Community add-ons are now **experimental**. - Replace `sv.pnpmBuildDependency` with `sv.file` plus `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` and `file.findUp`. **`@sveltejs/sv-utils`** From e42e5077ae2c72d4469755130cd4fff6f92ffebe Mon Sep 17 00:00:00 2001 From: jycouet Date: Mon, 6 Apr 2026 16:36:50 +0200 Subject: [PATCH 22/31] add a deprecation mechanism --- CONTRIBUTING.md | 24 ++++++++++++++++ packages/sv/api-surface-testing.md | 45 +++++++++++++++++++++++++++++- packages/sv/api-surface.md | 10 ++++++- packages/sv/src/core/config.ts | 2 ++ packages/sv/src/core/deprecated.ts | 8 ++++++ packages/sv/src/core/engine.ts | 13 +++++++++ packages/sv/src/core/workspace.ts | 41 +++++++++++++++++++++++++++ packages/sv/src/index.ts | 37 +++++++++++++++++++++++- packages/sv/src/testing.ts | 40 ++++++++++++++++++++++++++ 9 files changed, 217 insertions(+), 3 deletions(-) create mode 100644 packages/sv/src/core/deprecated.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e5ea225dd..8b9d4b874 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -153,6 +153,30 @@ To run svelte-migrate locally: node ./packages/migrate/bin.js ``` +## Deprecation pattern + +When removing public API from `sv`, **do not hard-remove** it. Instead, deprecate it and keep it working until the next major version. + +### How to deprecate + +1. **Add `@deprecated` JSDoc** on the type/function - IDEs will show strikethrough: + + ```ts + /** @deprecated use `newThing()` instead */ + ``` + +2. **Emit a runtime warning** (for functions/methods) using `svDeprecated()` from `core/deprecated.ts`. Warns once per message: + + ```ts + svDeprecated('use `newThing()` instead of `oldThing()`'); + ``` + +3. **Keep the old behavior working** - the deprecated API should still function correctly, just with a warning. + +### Before a major release + +Search for `svDeprecated` and `@deprecated` to find and remove all deprecated APIs: + ## Generating changelogs Here is the command to generate a change set: diff --git a/packages/sv/api-surface-testing.md b/packages/sv/api-surface-testing.md index 5f0ded335..9d565c4f3 100644 --- a/packages/sv/api-surface-testing.md +++ b/packages/sv/api-surface-testing.md @@ -10,6 +10,20 @@ type CreateProject = (options: { variant: ProjectVariant; clean?: boolean; }) => string; +type SetupOptions = { + cwd: string; + variants: readonly ProjectVariant[]; + clean?: boolean; +}; +type CreateOptions = { + cwd: string; + testName: string; + templatesDir: string; +}; +type PreviewOptions = { + cwd: string; + command?: string; +}; declare module 'vitest' { interface ProvidedContext { testDir: string; @@ -59,8 +73,12 @@ declare function prepareServer({ buildCommand, previewCommand }: PrepareServerOptions): Promise; +type PlaywrightContext = Pick; type VitestContext = Pick; -declare function createSetupTest(vitest: VitestContext): ( +declare function createSetupTest( + vitest: VitestContext, + playwright?: PlaywrightContext +): ( addons: Addons, options?: SetupTestOptions ) => { @@ -68,16 +86,41 @@ declare function createSetupTest(vitest: VitestContext): >; prepareServer: typeof prepareServer; }; +/** @deprecated use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead */ +declare function addPnpmBuildDependencies( + cwd: string, + packageManager: AgentName | null | undefined, + allowedPackages: string[] +): Promise; +/** @deprecated internal test utility, no longer part of the public API */ +declare function deprecatedSetup(options: SetupOptions): { + templatesDir: string; +}; +/** @deprecated internal test utility, no longer part of the public API */ +declare function deprecatedCreateProject(options: CreateOptions): CreateProject; +/** @deprecated internal test utility, no longer part of the public API */ +declare function deprecatedStartPreview(options: PreviewOptions): Promise<{ + url: string; + close: () => Promise; +}>; export { AddonTestCase, CreateProject, Fixtures, + PlaywrightContext, PrepareServerOptions, PrepareServerReturn, ProjectVariant, SetupTestOptions, VitestContext, + addPnpmBuildDependencies, + deprecatedCreateProject as createProject, + deprecatedCreateProject, createSetupTest, + deprecatedSetup, + deprecatedSetup as setup, + deprecatedStartPreview, + deprecatedStartPreview as startPreview, prepareServer, setupGlobal, variants diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md index 77af976cf..03d27b2cd 100644 --- a/packages/sv/api-surface.md +++ b/packages/sv/api-surface.md @@ -13,7 +13,6 @@ type Options = { template: TemplateType; types: LanguageType; }; -declare function create({ cwd, ...options }: Options): void; type FileEditor = Workspace & { content: string; }; @@ -22,6 +21,9 @@ type FileType = { condition?: ConditionDefinition; content: (editor: FileEditor) => string; }; +/** @deprecated use `create({ cwd, ...options })` instead */ +declare function create(cwd: string, options: Omit): void; +declare function create(options: Options): void; export { type Addon, type AddonDefinition, @@ -32,6 +34,7 @@ export { type AddonSource, type BaseQuestion, type BooleanQuestion, + type ConditionDefinition, type ConfiguredAddon, type FileEditor, type FileType, @@ -44,13 +47,18 @@ export { type OptionDefinition, type OptionMap, type OptionValues, + type PackageDefinition, type PreparedAddon, type Question, + type Scripts, type SelectQuestion, type SetupResult, type StringQuestion, type SvApi, type TemplateType, + type TestDefinition, + type Tests, + type Verification, type Workspace, type WorkspaceOptions, add, diff --git a/packages/sv/src/core/config.ts b/packages/sv/src/core/config.ts index b0c02226e..2a3322c98 100644 --- a/packages/sv/src/core/config.ts +++ b/packages/sv/src/core/config.ts @@ -21,6 +21,8 @@ export type Scripts = { }; export type SvApi = { + /** @deprecated use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead */ + pnpmBuildDependency: (pkg: string) => void; /** Add a package to the dependencies. */ dependency: (pkg: string, version: string) => void; /** Add a package to the dev dependencies. */ diff --git a/packages/sv/src/core/deprecated.ts b/packages/sv/src/core/deprecated.ts new file mode 100644 index 000000000..a0594e83c --- /dev/null +++ b/packages/sv/src/core/deprecated.ts @@ -0,0 +1,8 @@ +const warned = new Set(); + +/** Emit a one-time deprecation warning. */ +export function svDeprecated(message: string): void { + if (warned.has(message)) return; + warned.add(message); + console.warn(`[sv] Deprecated: ${message}`); +} diff --git a/packages/sv/src/core/engine.ts b/packages/sv/src/core/engine.ts index 7cb87c48d..66d95438e 100644 --- a/packages/sv/src/core/engine.ts +++ b/packages/sv/src/core/engine.ts @@ -20,7 +20,9 @@ import { type SetupResult, type SvApi } from './config.ts'; +import { svDeprecated } from './deprecated.ts'; import { TESTING } from './env.ts'; +import { addPnpmOnlyBuiltDependencies } from './package-manager.ts'; import { createWorkspace, type Workspace } from './workspace.ts'; function alphabetizePackageJsonDependencies(obj: Record) { @@ -104,6 +106,8 @@ export async function applyAddons({ options }: ApplyAddonOptions): Promise<{ filesToFormat: string[]; + /** @deprecated use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead */ + pnpmBuildDependencies: string[]; status: Record; }> { const filesToFormat = new Set(); @@ -144,6 +148,8 @@ export async function applyAddons({ return { filesToFormat: hasFormatter ? Array.from(filesToFormat) : [], + /** @deprecated */ + pnpmBuildDependencies: [], status }; } @@ -253,6 +259,13 @@ async function runAddon({ addon, loaded, multiple, workspace, workspaceOptions } }, devDependency: (pkg, version) => { dependencies.push({ pkg, version, dev: true }); + }, + /** @deprecated use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead */ + pnpmBuildDependency: (pkg) => { + svDeprecated( + 'use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead of `sv.pnpmBuildDependency`' + ); + addPnpmOnlyBuiltDependencies(workspace.cwd, workspace.packageManager, pkg); } }; diff --git a/packages/sv/src/core/workspace.ts b/packages/sv/src/core/workspace.ts index 35ceac23c..ec4b9f27f 100644 --- a/packages/sv/src/core/workspace.ts +++ b/packages/sv/src/core/workspace.ts @@ -10,6 +10,7 @@ import * as find from 'empathic/find'; import fs from 'node:fs'; import path from 'node:path'; import { commonFilePaths } from './common.ts'; +import { svDeprecated } from './deprecated.ts'; import type { OptionDefinition, OptionValues } from './options.ts'; import { detectPackageManager } from './package-manager.ts'; @@ -37,6 +38,17 @@ export type Workspace = { package: 'package.json'; gitignore: '.gitignore'; + /** @deprecated use `findUp('.prettierignore')` instead */ + prettierignore: '.prettierignore'; + /** @deprecated use `findUp('.prettierrc')` instead */ + prettierrc: '.prettierrc'; + /** @deprecated use `findUp('eslint.config.js')` instead */ + eslintConfig: 'eslint.config.js'; + /** @deprecated use `findUp('.vscode/settings.json')` instead */ + vscodeSettings: '.vscode/settings.json'; + /** @deprecated use `findUp('.vscode/extensions.json')` instead */ + vscodeExtensions: '.vscode/extensions.json'; + /** Get the relative path between two files */ getRelative: ({ from, to }: { from?: string; to: string }) => string; @@ -141,6 +153,35 @@ export async function createWorkspace({ stylesheet, package: 'package.json', gitignore: '.gitignore', + /** @deprecated */ + get prettierignore() { + svDeprecated('use `findUp(".prettierignore")` instead of `workspace.file.prettierignore`'); + return '.prettierignore' as const; + }, + /** @deprecated */ + get prettierrc() { + svDeprecated('use `findUp(".prettierrc")` instead of `workspace.file.prettierrc`'); + return '.prettierrc' as const; + }, + /** @deprecated */ + get eslintConfig() { + svDeprecated('use `findUp("eslint.config.js")` instead of `workspace.file.eslintConfig`'); + return 'eslint.config.js' as const; + }, + /** @deprecated */ + get vscodeSettings() { + svDeprecated( + 'use `findUp(".vscode/settings.json")` instead of `workspace.file.vscodeSettings`' + ); + return '.vscode/settings.json' as const; + }, + /** @deprecated */ + get vscodeExtensions() { + svDeprecated( + 'use `findUp(".vscode/extensions.json")` instead of `workspace.file.vscodeExtensions`' + ); + return '.vscode/extensions.json' as const; + }, getRelative({ from, to }) { from = from ?? ''; let relativePath = path.posix.relative(path.posix.dirname(from), to); diff --git a/packages/sv/src/index.ts b/packages/sv/src/index.ts index 3c3fe50b0..6a95390a1 100644 --- a/packages/sv/src/index.ts +++ b/packages/sv/src/index.ts @@ -1,4 +1,23 @@ -export { create, type TemplateType, type LanguageType } from './create/index.ts'; +import { svDeprecated } from './core/deprecated.ts'; +import { create as _create, type Options as CreateOptions } from './create/index.ts'; + +export type { TemplateType, LanguageType } from './create/index.ts'; + +/** @deprecated use `create({ cwd, ...options })` instead */ +export function create(cwd: string, options: Omit): void; +export function create(options: CreateOptions): void; +export function create( + cwdOrOptions: string | CreateOptions, + legacyOptions?: Omit +): void { + if (typeof cwdOrOptions === 'string') { + svDeprecated('use `create({ cwd, ...options })` instead of `create(cwd, options)`'); + _create({ cwd: cwdOrOptions, ...legacyOptions! }); + } else { + _create(cwdOrOptions); + } +} + export { add } from './core/engine.ts'; export type { AddonMap, InstallOptions, OptionMap } from './core/engine.ts'; export { officialAddons } from './addons/index.ts'; @@ -38,3 +57,19 @@ export type { export type { Workspace, WorkspaceOptions } from './core/workspace.ts'; export type { FileEditor, FileType } from './core/processors.ts'; + +// Deprecated types kept for backward compatibility, will be removed in next major. +export type { + /** @deprecated not part of the public API */ + ConditionDefinition, + /** @deprecated not part of the public API */ + PackageDefinition, + /** @deprecated not part of the public API */ + Scripts, + /** @deprecated not part of the public API */ + Tests, + /** @deprecated not part of the public API */ + TestDefinition, + /** @deprecated not part of the public API */ + Verification +} from './core/config.ts'; diff --git a/packages/sv/src/testing.ts b/packages/sv/src/testing.ts index 1075f4496..b952c901b 100644 --- a/packages/sv/src/testing.ts +++ b/packages/sv/src/testing.ts @@ -1,4 +1,5 @@ import type { Page } from '@playwright/test'; +import type { AgentName } from '@sveltejs/sv-utils'; import { execSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; @@ -6,6 +7,7 @@ import process from 'node:process'; import pstree, { type PS } from 'ps-tree'; import { exec, x } from 'tinyexec'; import type { TestProject } from 'vitest/node'; +import { svDeprecated } from './core/deprecated.ts'; import { add, type AddonMap, type OptionMap } from './core/engine.ts'; import { addPnpmOnlyBuiltDependencies } from './core/package-manager.ts'; import { create } from './create/index.ts'; @@ -370,3 +372,41 @@ export function createSetupTest( return { test, testCases, prepareServer }; }; } + +// Deprecated exports kept for backward compatibility, will be removed in next major. + +/** @deprecated use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead */ +export function addPnpmBuildDependencies( + cwd: string, + packageManager: AgentName | null | undefined, + allowedPackages: string[] +): Promise { + svDeprecated( + 'use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead of `addPnpmBuildDependencies`' + ); + addPnpmOnlyBuiltDependencies(cwd, packageManager, ...allowedPackages); + return Promise.resolve(); +} + +/** @deprecated internal test utility, no longer part of the public API */ +export function deprecatedSetup(options: SetupOptions): { templatesDir: string } { + svDeprecated('`setup` from `sv/testing` is deprecated'); + return setup(options); +} +export { deprecatedSetup as setup }; + +/** @deprecated internal test utility, no longer part of the public API */ +export function deprecatedCreateProject(options: CreateOptions): CreateProject { + svDeprecated('`createProject` from `sv/testing` is deprecated'); + return createProject(options); +} +export { deprecatedCreateProject as createProject }; + +/** @deprecated internal test utility, no longer part of the public API */ +export function deprecatedStartPreview( + options: PreviewOptions +): Promise<{ url: string; close: () => Promise }> { + svDeprecated('`startPreview` from `sv/testing` is deprecated'); + return Promise.resolve(startPreview(options)); +} +export { deprecatedStartPreview as startPreview }; From 4b26be10dcba18dec31747ae258ea2c693dd47ac Mon Sep 17 00:00:00 2001 From: jycouet Date: Mon, 6 Apr 2026 16:45:57 +0200 Subject: [PATCH 23/31] deprecated types --- packages/sv/api-surface.md | 12 +++--- packages/sv/src/core/config.ts | 6 +++ scripts/generate-api-surface.js | 69 ++++++++++++++++++++++++++++++++- 3 files changed, 80 insertions(+), 7 deletions(-) diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md index 03d27b2cd..364af2ab4 100644 --- a/packages/sv/api-surface.md +++ b/packages/sv/api-surface.md @@ -34,7 +34,7 @@ export { type AddonSource, type BaseQuestion, type BooleanQuestion, - type ConditionDefinition, + /** @deprecated */ type ConditionDefinition, type ConfiguredAddon, type FileEditor, type FileType, @@ -47,18 +47,18 @@ export { type OptionDefinition, type OptionMap, type OptionValues, - type PackageDefinition, + /** @deprecated */ type PackageDefinition, type PreparedAddon, type Question, - type Scripts, + /** @deprecated */ type Scripts, type SelectQuestion, type SetupResult, type StringQuestion, type SvApi, type TemplateType, - type TestDefinition, - type Tests, - type Verification, + /** @deprecated */ type TestDefinition, + /** @deprecated */ type Tests, + /** @deprecated */ type Verification, type Workspace, type WorkspaceOptions, add, diff --git a/packages/sv/src/core/config.ts b/packages/sv/src/core/config.ts index 2a3322c98..ae07d60b0 100644 --- a/packages/sv/src/core/config.ts +++ b/packages/sv/src/core/config.ts @@ -4,8 +4,10 @@ import type { Workspace, WorkspaceOptions } from './workspace.ts'; export type { OptionValues } from './options.ts'; +/** @deprecated not part of the public API */ export type ConditionDefinition = (Workspace: Workspace) => boolean; +/** @deprecated not part of the public API */ export type PackageDefinition = { name: string; version: string; @@ -13,6 +15,7 @@ export type PackageDefinition = { condition?: ConditionDefinition; }; +/** @deprecated not part of the public API */ export type Scripts = { description: string; args: string[]; @@ -199,6 +202,7 @@ export type SetupResult = { dependsOn: string[]; unsupported: string[]; runsAfte export type AddonDefinition = Addon>, Id>; +/** @deprecated not part of the public API */ export type Tests = { expectProperty: (selector: string, property: string, expectedValue: string) => Promise; elementExists: (selector: string) => Promise; @@ -206,6 +210,7 @@ export type Tests = { expectUrlPath: (path: string) => void; }; +/** @deprecated not part of the public API */ export type TestDefinition = { name: string; run: (tests: Tests) => Promise; @@ -214,6 +219,7 @@ export type TestDefinition = { type MaybePromise = Promise | T; +/** @deprecated not part of the public API */ export type Verification = { name: string; run: () => MaybePromise<{ success: boolean; message: string | undefined }>; diff --git a/scripts/generate-api-surface.js b/scripts/generate-api-surface.js index e1f3c03d4..d96d45bcd 100644 --- a/scripts/generate-api-surface.js +++ b/scripts/generate-api-surface.js @@ -125,6 +125,71 @@ async function formatWithPrettier(absPath) { fs.writeFileSync(absPath, formatted, 'utf8'); } +/** + * Collect names marked `@deprecated` in chunk files imported by the entry .d.mts. + * Returns a Set of exported names whose declarations carry `@deprecated`. + * @param {string} entrySource + * @param {string} entryDir + * @returns {Set} + */ +function collectDeprecatedFromChunks(entrySource, entryDir) { + /** @type {Set} */ + const deprecated = new Set(); + + // match: import { A as Foo, B as Bar } from "../chunk.mjs"; + const importRe = /^import\s+\{([^}]+)\}\s+from\s+"([^"]+)"/gm; + let m; + while ((m = importRe.exec(entrySource))) { + const specifiers = m[1]; + const chunkRel = m[2]; + const chunkPath = path.resolve(entryDir, chunkRel.replace(/\.mjs$/, '.d.mts')); + if (!fs.existsSync(chunkPath)) continue; + + const chunkSrc = fs.readFileSync(chunkPath, 'utf8'); + + // collect full type names marked @deprecated in the chunk + const deprecatedNames = new Set(); + // Match /** @deprecated ... */ directly followed by a top-level type declaration + // The [^{}]* ensures we don't cross type body boundaries + const depRe = /\/\*\*\s*@deprecated[^{}]*?\*\/\s*(?:export\s+)?type\s+(\w+)/g; + let dm; + while ((dm = depRe.exec(chunkSrc))) { + deprecatedNames.add(dm[1]); + } + + // map import specifiers (alias as ExportedName) back to chunk names + // entry: "d as ConditionDefinition" -> chunk exports "ConditionDefinition as d" + // so we check if ExportedName is deprecated in the chunk + for (const spec of specifiers.split(',')) { + const parts = spec.trim().split(/\s+as\s+/); + if (parts.length !== 2) continue; + const exportedName = parts[1]; + if (deprecatedNames.has(exportedName)) { + deprecated.add(exportedName); + } + } + } + return deprecated; +} + +/** + * Annotate `type Foo` entries in the export block with `/** @deprecated *\/` if + * the underlying declaration was marked deprecated in a chunk file. + * @param {string} cleaned + * @param {Set} deprecated + * @returns {string} + */ +function annotateDeprecatedExports(cleaned, deprecated) { + if (deprecated.size === 0) return cleaned; + // match "type Name" inside export { ... } blocks + return cleaned.replace(/\btype\s+(\w+)/g, (match, name) => { + if (deprecated.has(name)) { + return `/** @deprecated */ type ${name}`; + } + return match; + }); +} + /** @returns {Promise} number of api-surface files written */ export async function generateApiSurface() { let generated = 0; @@ -136,7 +201,9 @@ export async function generateApiSurface() { } const raw = fs.readFileSync(dtsPath, 'utf8'); - const cleaned = clean(raw); + const deprecated = collectDeprecatedFromChunks(raw, path.dirname(dtsPath)); + let cleaned = clean(raw); + cleaned = annotateDeprecatedExports(cleaned, deprecated); const header = `# ${pkg.name} - Public API Surface\n\n` + From 135826a39f592359b96b07ef1e035be2c2355386 Mon Sep 17 00:00:00 2001 From: jycouet Date: Mon, 6 Apr 2026 17:08:43 +0200 Subject: [PATCH 24/31] trim deprecations: hard-remove internal-only stuff, fix file path messages --- packages/sv/api-surface-testing.md | 38 ---------------------------- packages/sv/api-surface.md | 6 ----- packages/sv/src/core/config.ts | 6 ----- packages/sv/src/core/engine.ts | 4 --- packages/sv/src/core/workspace.ts | 26 +++++++++++-------- packages/sv/src/index.ts | 16 ------------ packages/sv/src/testing.ts | 40 ------------------------------ 7 files changed, 16 insertions(+), 120 deletions(-) diff --git a/packages/sv/api-surface-testing.md b/packages/sv/api-surface-testing.md index 9d565c4f3..29beb34f8 100644 --- a/packages/sv/api-surface-testing.md +++ b/packages/sv/api-surface-testing.md @@ -10,20 +10,6 @@ type CreateProject = (options: { variant: ProjectVariant; clean?: boolean; }) => string; -type SetupOptions = { - cwd: string; - variants: readonly ProjectVariant[]; - clean?: boolean; -}; -type CreateOptions = { - cwd: string; - testName: string; - templatesDir: string; -}; -type PreviewOptions = { - cwd: string; - command?: string; -}; declare module 'vitest' { interface ProvidedContext { testDir: string; @@ -86,23 +72,6 @@ declare function createSetupTest( testCases: Array>; prepareServer: typeof prepareServer; }; -/** @deprecated use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead */ -declare function addPnpmBuildDependencies( - cwd: string, - packageManager: AgentName | null | undefined, - allowedPackages: string[] -): Promise; -/** @deprecated internal test utility, no longer part of the public API */ -declare function deprecatedSetup(options: SetupOptions): { - templatesDir: string; -}; -/** @deprecated internal test utility, no longer part of the public API */ -declare function deprecatedCreateProject(options: CreateOptions): CreateProject; -/** @deprecated internal test utility, no longer part of the public API */ -declare function deprecatedStartPreview(options: PreviewOptions): Promise<{ - url: string; - close: () => Promise; -}>; export { AddonTestCase, CreateProject, @@ -113,14 +82,7 @@ export { ProjectVariant, SetupTestOptions, VitestContext, - addPnpmBuildDependencies, - deprecatedCreateProject as createProject, - deprecatedCreateProject, createSetupTest, - deprecatedSetup, - deprecatedSetup as setup, - deprecatedStartPreview, - deprecatedStartPreview as startPreview, prepareServer, setupGlobal, variants diff --git a/packages/sv/api-surface.md b/packages/sv/api-surface.md index 364af2ab4..f83add881 100644 --- a/packages/sv/api-surface.md +++ b/packages/sv/api-surface.md @@ -34,7 +34,6 @@ export { type AddonSource, type BaseQuestion, type BooleanQuestion, - /** @deprecated */ type ConditionDefinition, type ConfiguredAddon, type FileEditor, type FileType, @@ -47,18 +46,13 @@ export { type OptionDefinition, type OptionMap, type OptionValues, - /** @deprecated */ type PackageDefinition, type PreparedAddon, type Question, - /** @deprecated */ type Scripts, type SelectQuestion, type SetupResult, type StringQuestion, type SvApi, type TemplateType, - /** @deprecated */ type TestDefinition, - /** @deprecated */ type Tests, - /** @deprecated */ type Verification, type Workspace, type WorkspaceOptions, add, diff --git a/packages/sv/src/core/config.ts b/packages/sv/src/core/config.ts index ae07d60b0..2a3322c98 100644 --- a/packages/sv/src/core/config.ts +++ b/packages/sv/src/core/config.ts @@ -4,10 +4,8 @@ import type { Workspace, WorkspaceOptions } from './workspace.ts'; export type { OptionValues } from './options.ts'; -/** @deprecated not part of the public API */ export type ConditionDefinition = (Workspace: Workspace) => boolean; -/** @deprecated not part of the public API */ export type PackageDefinition = { name: string; version: string; @@ -15,7 +13,6 @@ export type PackageDefinition = { condition?: ConditionDefinition; }; -/** @deprecated not part of the public API */ export type Scripts = { description: string; args: string[]; @@ -202,7 +199,6 @@ export type SetupResult = { dependsOn: string[]; unsupported: string[]; runsAfte export type AddonDefinition = Addon>, Id>; -/** @deprecated not part of the public API */ export type Tests = { expectProperty: (selector: string, property: string, expectedValue: string) => Promise; elementExists: (selector: string) => Promise; @@ -210,7 +206,6 @@ export type Tests = { expectUrlPath: (path: string) => void; }; -/** @deprecated not part of the public API */ export type TestDefinition = { name: string; run: (tests: Tests) => Promise; @@ -219,7 +214,6 @@ export type TestDefinition = { type MaybePromise = Promise | T; -/** @deprecated not part of the public API */ export type Verification = { name: string; run: () => MaybePromise<{ success: boolean; message: string | undefined }>; diff --git a/packages/sv/src/core/engine.ts b/packages/sv/src/core/engine.ts index 66d95438e..99304e745 100644 --- a/packages/sv/src/core/engine.ts +++ b/packages/sv/src/core/engine.ts @@ -106,8 +106,6 @@ export async function applyAddons({ options }: ApplyAddonOptions): Promise<{ filesToFormat: string[]; - /** @deprecated use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead */ - pnpmBuildDependencies: string[]; status: Record; }> { const filesToFormat = new Set(); @@ -148,8 +146,6 @@ export async function applyAddons({ return { filesToFormat: hasFormatter ? Array.from(filesToFormat) : [], - /** @deprecated */ - pnpmBuildDependencies: [], status }; } diff --git a/packages/sv/src/core/workspace.ts b/packages/sv/src/core/workspace.ts index ec4b9f27f..1c30d550d 100644 --- a/packages/sv/src/core/workspace.ts +++ b/packages/sv/src/core/workspace.ts @@ -38,15 +38,15 @@ export type Workspace = { package: 'package.json'; gitignore: '.gitignore'; - /** @deprecated use `findUp('.prettierignore')` instead */ + /** @deprecated use the string `'.prettierignore'` directly */ prettierignore: '.prettierignore'; - /** @deprecated use `findUp('.prettierrc')` instead */ + /** @deprecated use the string `'.prettierrc'` directly */ prettierrc: '.prettierrc'; - /** @deprecated use `findUp('eslint.config.js')` instead */ + /** @deprecated use the string `'eslint.config.js'` directly */ eslintConfig: 'eslint.config.js'; - /** @deprecated use `findUp('.vscode/settings.json')` instead */ + /** @deprecated use the string `'.vscode/settings.json'` directly */ vscodeSettings: '.vscode/settings.json'; - /** @deprecated use `findUp('.vscode/extensions.json')` instead */ + /** @deprecated use the string `'.vscode/extensions.json'` directly */ vscodeExtensions: '.vscode/extensions.json'; /** Get the relative path between two files */ @@ -155,30 +155,36 @@ export async function createWorkspace({ gitignore: '.gitignore', /** @deprecated */ get prettierignore() { - svDeprecated('use `findUp(".prettierignore")` instead of `workspace.file.prettierignore`'); + svDeprecated( + '`workspace.file.prettierignore` is deprecated, use the string `".prettierignore"` directly' + ); return '.prettierignore' as const; }, /** @deprecated */ get prettierrc() { - svDeprecated('use `findUp(".prettierrc")` instead of `workspace.file.prettierrc`'); + svDeprecated( + '`workspace.file.prettierrc` is deprecated, use the string `".prettierrc"` directly' + ); return '.prettierrc' as const; }, /** @deprecated */ get eslintConfig() { - svDeprecated('use `findUp("eslint.config.js")` instead of `workspace.file.eslintConfig`'); + svDeprecated( + '`workspace.file.eslintConfig` is deprecated, use the string `"eslint.config.js"` directly' + ); return 'eslint.config.js' as const; }, /** @deprecated */ get vscodeSettings() { svDeprecated( - 'use `findUp(".vscode/settings.json")` instead of `workspace.file.vscodeSettings`' + '`workspace.file.vscodeSettings` is deprecated, use the string `".vscode/settings.json"` directly' ); return '.vscode/settings.json' as const; }, /** @deprecated */ get vscodeExtensions() { svDeprecated( - 'use `findUp(".vscode/extensions.json")` instead of `workspace.file.vscodeExtensions`' + '`workspace.file.vscodeExtensions` is deprecated, use the string `".vscode/extensions.json"` directly' ); return '.vscode/extensions.json' as const; }, diff --git a/packages/sv/src/index.ts b/packages/sv/src/index.ts index 6a95390a1..ed4108934 100644 --- a/packages/sv/src/index.ts +++ b/packages/sv/src/index.ts @@ -57,19 +57,3 @@ export type { export type { Workspace, WorkspaceOptions } from './core/workspace.ts'; export type { FileEditor, FileType } from './core/processors.ts'; - -// Deprecated types kept for backward compatibility, will be removed in next major. -export type { - /** @deprecated not part of the public API */ - ConditionDefinition, - /** @deprecated not part of the public API */ - PackageDefinition, - /** @deprecated not part of the public API */ - Scripts, - /** @deprecated not part of the public API */ - Tests, - /** @deprecated not part of the public API */ - TestDefinition, - /** @deprecated not part of the public API */ - Verification -} from './core/config.ts'; diff --git a/packages/sv/src/testing.ts b/packages/sv/src/testing.ts index b952c901b..1075f4496 100644 --- a/packages/sv/src/testing.ts +++ b/packages/sv/src/testing.ts @@ -1,5 +1,4 @@ import type { Page } from '@playwright/test'; -import type { AgentName } from '@sveltejs/sv-utils'; import { execSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; @@ -7,7 +6,6 @@ import process from 'node:process'; import pstree, { type PS } from 'ps-tree'; import { exec, x } from 'tinyexec'; import type { TestProject } from 'vitest/node'; -import { svDeprecated } from './core/deprecated.ts'; import { add, type AddonMap, type OptionMap } from './core/engine.ts'; import { addPnpmOnlyBuiltDependencies } from './core/package-manager.ts'; import { create } from './create/index.ts'; @@ -372,41 +370,3 @@ export function createSetupTest( return { test, testCases, prepareServer }; }; } - -// Deprecated exports kept for backward compatibility, will be removed in next major. - -/** @deprecated use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead */ -export function addPnpmBuildDependencies( - cwd: string, - packageManager: AgentName | null | undefined, - allowedPackages: string[] -): Promise { - svDeprecated( - 'use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead of `addPnpmBuildDependencies`' - ); - addPnpmOnlyBuiltDependencies(cwd, packageManager, ...allowedPackages); - return Promise.resolve(); -} - -/** @deprecated internal test utility, no longer part of the public API */ -export function deprecatedSetup(options: SetupOptions): { templatesDir: string } { - svDeprecated('`setup` from `sv/testing` is deprecated'); - return setup(options); -} -export { deprecatedSetup as setup }; - -/** @deprecated internal test utility, no longer part of the public API */ -export function deprecatedCreateProject(options: CreateOptions): CreateProject { - svDeprecated('`createProject` from `sv/testing` is deprecated'); - return createProject(options); -} -export { deprecatedCreateProject as createProject }; - -/** @deprecated internal test utility, no longer part of the public API */ -export function deprecatedStartPreview( - options: PreviewOptions -): Promise<{ url: string; close: () => Promise }> { - svDeprecated('`startPreview` from `sv/testing` is deprecated'); - return Promise.resolve(startPreview(options)); -} -export { deprecatedStartPreview as startPreview }; From c5e94b64a92fba93b6f530ed04c56f963b3a512f Mon Sep 17 00:00:00 2001 From: jycouet Date: Mon, 6 Apr 2026 17:10:24 +0200 Subject: [PATCH 25/31] remove dead types: PackageDefinition, Scripts, TestDefinition --- packages/sv/src/core/config.ts | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/packages/sv/src/core/config.ts b/packages/sv/src/core/config.ts index 2a3322c98..f1467f09f 100644 --- a/packages/sv/src/core/config.ts +++ b/packages/sv/src/core/config.ts @@ -6,20 +6,6 @@ export type { OptionValues } from './options.ts'; export type ConditionDefinition = (Workspace: Workspace) => boolean; -export type PackageDefinition = { - name: string; - version: string; - dev: boolean; - condition?: ConditionDefinition; -}; - -export type Scripts = { - description: string; - args: string[]; - stdio: 'inherit' | 'pipe'; - condition?: ConditionDefinition; -}; - export type SvApi = { /** @deprecated use `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` instead */ pnpmBuildDependency: (pkg: string) => void; @@ -206,12 +192,6 @@ export type Tests = { expectUrlPath: (path: string) => void; }; -export type TestDefinition = { - name: string; - run: (tests: Tests) => Promise; - condition?: (options: OptionValues) => boolean; -}; - type MaybePromise = Promise | T; export type Verification = { From 5a091ba5b2ca1fb15dce4c35252436a1eefab573 Mon Sep 17 00:00:00 2001 From: jycouet Date: Mon, 6 Apr 2026 17:13:27 +0200 Subject: [PATCH 26/31] update changeset --- .changeset/coupling-sv-and-sv-utils.md | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/.changeset/coupling-sv-and-sv-utils.md b/.changeset/coupling-sv-and-sv-utils.md index f7232eff5..60630d8a9 100644 --- a/.changeset/coupling-sv-and-sv-utils.md +++ b/.changeset/coupling-sv-and-sv-utils.md @@ -3,20 +3,21 @@ '@sveltejs/sv-utils': minor --- -feat: sv / sv-utils coupling, pnpm helpers, experimental add-ons, and API snapshots - -**Highlights** - -- Replace `sv.pnpmBuildDependency` with `sv.file` plus `pnpm.onlyBuiltDependencies` from `@sveltejs/sv-utils` and `file.findUp`. +feat: decouple sv / sv-utils, explicit public API, deprecation pass **`@sveltejs/sv-utils`** -- Add `pnpm.onlyBuiltDependencies` to append packages to `onlyBuiltDependencies` in pnpm YAML via `transforms.yaml`. -- Type `YamlDocument` (`parse.yaml`) with `get` / `set` using `unknown` so consumers narrow explicitly; align YAML transforms with that contract. +- Rename file helpers: `readFile` -> `loadFile`, `writeFile` -> `saveFile`, `getPackageJson` -> `loadPackageJson` +- Add `pnpm.onlyBuiltDependencies()` transform for `pnpm-workspace.yaml` +- Export `YamlDocument` type from parsers +- Remove `commonFilePaths`, `installPackages` (moved internal to `sv`) **`sv`** -- Refactor workspace / engine / package-manager flows around file IO and package JSON loading (`loadFile`, `saveFile`, `loadPackageJson`), and trim workspace addon path handling; update addons accordingly. -- Reorganize the public `testing` entry for Vitest helpers and document the surface. -- Add generated `api-surface` markdown snapshots and a `scripts/generate-api-surface.js` helper (wired through the build) to track the public API. -- Remove deprecated `pnpmBuildDependency` usage and stop exporting internal pnpm-only-built helpers from the public `sv` surface. +- `create()` signature changed to `create({ cwd, ...options })`. The old `create(cwd, options)` form still works but is deprecated and will be removed in the next major. +- `sv.pnpmBuildDependency()` is deprecated. Use `sv.file()` with `pnpm.onlyBuiltDependencies()` from `@sveltejs/sv-utils` instead. Still works for now. +- `workspace.file.prettierignore`, `.prettierrc`, `.eslintConfig`, `.vscodeSettings`, `.vscodeExtensions` are deprecated. Use the raw strings directly (e.g. `'.prettierignore'`). Still works for now. +- Add `workspace.file.findUp()` to locate files by walking up the directory tree. +- Make type exports explicit (no more `export type *`). Removed types that were never part of the intended public API: `PackageDefinition`, `Scripts`, `TestDefinition`. +- Remove `setup`, `createProject`, `startPreview`, `addPnpmBuildDependencies` from `sv/testing` exports. +- Add `api-surface.md` snapshots (auto-generated on build) to track the public API of `sv` and `@sveltejs/sv-utils`. From ab880a81fd8666afa1c152e07c6753b6072f358a Mon Sep 17 00:00:00 2001 From: jycouet Date: Mon, 6 Apr 2026 20:06:35 +0200 Subject: [PATCH 27/31] dedent is back --- packages/sv-utils/api-surface.md | 14 ++++++++++---- packages/sv-utils/src/dedent.ts | 13 ------------- packages/sv-utils/src/index.ts | 2 +- tsdown.config.ts | 3 +-- 4 files changed, 12 insertions(+), 20 deletions(-) delete mode 100644 packages/sv-utils/src/dedent.ts diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index d6d69bc91..4e6e5dc86 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -194,11 +194,17 @@ declare function parseSvelte(source: string): { declare function parseToml(source: string): { data: TomlTable; } & ParseBase; - -type Dedent = { +interface DedentOptions { + alignValues?: boolean; + escapeSpecialCharacters?: boolean; + trimWhitespace?: boolean; +} +interface Dedent { + (literals: string): string; (strings: TemplateStringsArray, ...values: unknown[]): string; - (source: string): string; -}; + withOptions: CreateDedent; +} +type CreateDedent = (options: DedentOptions) => Dedent; declare const dedent: Dedent; declare module 'zimmerframe' { export function walk< diff --git a/packages/sv-utils/src/dedent.ts b/packages/sv-utils/src/dedent.ts deleted file mode 100644 index 1210bdac9..000000000 --- a/packages/sv-utils/src/dedent.ts +++ /dev/null @@ -1,13 +0,0 @@ -import dedentImpl from 'dedent'; - -/** - * Template-tag or single-string dedent helper (same behavior as the `dedent` package). - * Types are hand-written so the public `.d.mts` does not inline `dedent`'s full declarations. - */ -export type Dedent = { - (strings: TemplateStringsArray, ...values: unknown[]): string; - (source: string): string; -}; - -const dedent: Dedent = dedentImpl as Dedent; -export default dedent; diff --git a/packages/sv-utils/src/index.ts b/packages/sv-utils/src/index.ts index 74f334c47..8dc8fbb4b 100644 --- a/packages/sv-utils/src/index.ts +++ b/packages/sv-utils/src/index.ts @@ -9,7 +9,7 @@ import { } from './tooling/parsers.ts'; // External re-exports -export { default as dedent } from './dedent.ts'; +export { default as dedent } from 'dedent'; export * as Walker from 'zimmerframe'; // Package managers (delegates to `package-manager-detector`; see `pm.ts`) diff --git a/tsdown.config.ts b/tsdown.config.ts index da4d41568..08c348579 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -108,10 +108,9 @@ export default defineConfig([ '@types/estree', 'estree', 'yaml', - 'dedent', 'package-manager-detector' ], - onlyBundle: ['smol-toml', 'zimmerframe'] + onlyBundle: ['smol-toml', 'zimmerframe', 'dedent'] } } ]); From 5c4683e7e76916feefa9926ef500436640e2cea0 Mon Sep 17 00:00:00 2001 From: jycouet Date: Mon, 6 Apr 2026 20:10:43 +0200 Subject: [PATCH 28/31] JSDocs --- packages/sv-utils/src/files.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/sv-utils/src/files.ts b/packages/sv-utils/src/files.ts index 233a11323..156e07271 100644 --- a/packages/sv-utils/src/files.ts +++ b/packages/sv-utils/src/files.ts @@ -13,12 +13,13 @@ export type Package = { workspaces?: string[]; }; +/** Check if a file exists at the given workspace-relative path. */ export function fileExists(cwd: string, filePath: string): boolean { const fullFilePath = path.resolve(cwd, filePath); return fs.existsSync(fullFilePath); } -/** Synchronous load of a workspace-relative file as UTF-8 text; missing files yield `''`. */ +/** Synchronous load of a workspace-relative file; missing files yield `''`. */ export function loadFile(cwd: string, filePath: string): string { const fullFilePath = path.resolve(cwd, filePath); @@ -45,6 +46,7 @@ export function saveFile(cwd: string, filePath: string, content: string): void { fs.writeFileSync(fullFilePath, content, 'utf8'); } +/** Load and parse a workspace-relative `package.json`. Throws if missing or invalid. */ export function loadPackageJson(cwd: string): { source: string; data: Package; From 5f84095c59a9bc8a409cf185771e08bc35772b39 Mon Sep 17 00:00:00 2001 From: Scott Wu Date: Tue, 7 Apr 2026 02:47:33 +0800 Subject: [PATCH 29/31] adjustments (#1051) --- .changeset/coupling-sv-and-sv-utils.md | 10 +++--- CONTRIBUTING.md | 8 ++--- packages/sv-utils/src/files.ts | 22 ++++++++++++-- packages/sv/src/cli/create.ts | 6 ++-- packages/sv/src/core/common.ts | 2 +- packages/sv/src/core/engine.ts | 6 ++-- packages/sv/src/core/workspace.ts | 42 ++++++++++++-------------- packages/sv/src/create/index.ts | 6 ++-- packages/sv/src/create/playground.ts | 6 ++-- packages/sv/src/index.ts | 2 +- 10 files changed, 62 insertions(+), 48 deletions(-) diff --git a/.changeset/coupling-sv-and-sv-utils.md b/.changeset/coupling-sv-and-sv-utils.md index 60630d8a9..2da746c6d 100644 --- a/.changeset/coupling-sv-and-sv-utils.md +++ b/.changeset/coupling-sv-and-sv-utils.md @@ -14,10 +14,10 @@ feat: decouple sv / sv-utils, explicit public API, deprecation pass **`sv`** -- `create()` signature changed to `create({ cwd, ...options })`. The old `create(cwd, options)` form still works but is deprecated and will be removed in the next major. -- `sv.pnpmBuildDependency()` is deprecated. Use `sv.file()` with `pnpm.onlyBuiltDependencies()` from `@sveltejs/sv-utils` instead. Still works for now. -- `workspace.file.prettierignore`, `.prettierrc`, `.eslintConfig`, `.vscodeSettings`, `.vscodeExtensions` are deprecated. Use the raw strings directly (e.g. `'.prettierignore'`). Still works for now. +- `create()` signature changed to `create({ cwd, ...options })`. The old `create(cwd, options)` is deprecated and will be removed in the next major release. +- `sv.pnpmBuildDependency()` is deprecated and will be removed in the next major release. Use `sv.file()` with `pnpm.onlyBuiltDependencies()` from `@sveltejs/sv-utils` instead. +- `workspace.file.prettierignore`, `.prettierrc`, `.eslintConfig`, `.vscodeSettings`, `.vscodeExtensions` are deprecated and will be removed in the next major release. Use the raw strings directly (e.g. `'.prettierignore'`). - Add `workspace.file.findUp()` to locate files by walking up the directory tree. -- Make type exports explicit (no more `export type *`). Removed types that were never part of the intended public API: `PackageDefinition`, `Scripts`, `TestDefinition`. -- Remove `setup`, `createProject`, `startPreview`, `addPnpmBuildDependencies` from `sv/testing` exports. - Add `api-surface.md` snapshots (auto-generated on build) to track the public API of `sv` and `@sveltejs/sv-utils`. +- Remove `setup`, `createProject`, `startPreview`, `addPnpmBuildDependencies` from `sv/testing` exports. +- Make type exports explicit (no more `export type *`). Removed types that were never part of the intended public API: `PackageDefinition`, `Scripts`, `TestDefinition`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8b9d4b874..37835e7c5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -153,16 +153,16 @@ To run svelte-migrate locally: node ./packages/migrate/bin.js ``` -## Deprecation pattern +## Deprecation -When removing public API from `sv`, **do not hard-remove** it. Instead, deprecate it and keep it working until the next major version. +Public APIs cannot be changed in a minor release since it is a breaking change. Instead, the old behaviour is marked as deprecated until the next major version, at which point they can be removed. ### How to deprecate 1. **Add `@deprecated` JSDoc** on the type/function - IDEs will show strikethrough: ```ts - /** @deprecated use `newThing()` instead */ + /** @deprecated use `newThing()` instead. */ ``` 2. **Emit a runtime warning** (for functions/methods) using `svDeprecated()` from `core/deprecated.ts`. Warns once per message: @@ -175,7 +175,7 @@ When removing public API from `sv`, **do not hard-remove** it. Instead, deprecat ### Before a major release -Search for `svDeprecated` and `@deprecated` to find and remove all deprecated APIs: +Search for `svDeprecated` and `@deprecated` to find and remove all deprecated APIs. ## Generating changelogs diff --git a/packages/sv-utils/src/files.ts b/packages/sv-utils/src/files.ts index 156e07271..c4c9c9135 100644 --- a/packages/sv-utils/src/files.ts +++ b/packages/sv-utils/src/files.ts @@ -14,12 +14,20 @@ export type Package = { }; /** Check if a file exists at the given workspace-relative path. */ +/** + * Checks the file. + * @param filePath - Resolves paths relative to the workspace. + */ export function fileExists(cwd: string, filePath: string): boolean { const fullFilePath = path.resolve(cwd, filePath); return fs.existsSync(fullFilePath); } -/** Synchronous load of a workspace-relative file; missing files yield `''`. */ +/** + * Reads the file. + * @param filePath - Resolves paths relative to the workspace. + * @returns The raw UTF-8 text, or `''` if the file is not found. + */ export function loadFile(cwd: string, filePath: string): string { const fullFilePath = path.resolve(cwd, filePath); @@ -32,7 +40,10 @@ export function loadFile(cwd: string, filePath: string): string { return text; } -/** Synchronous write of a workspace-relative file (creates parent dirs). */ +/** + * Writes the file. Will make parent directories as needed. + * @param filePath - Resolves paths relative to the workspace. + */ export function saveFile(cwd: string, filePath: string, content: string): void { const fullFilePath = path.resolve(cwd, filePath); const fullDirectoryPath = path.dirname(fullFilePath); @@ -47,6 +58,13 @@ export function saveFile(cwd: string, filePath: string, content: string): void { } /** Load and parse a workspace-relative `package.json`. Throws if missing or invalid. */ +/** + * Loads the workspace `package.json`. + * @returns + * - `source`: The raw UTF-8 text. + * - `data`: The parsed JSON object. + * - `generateCode`: A function to serialize the data back to a string. + */ export function loadPackageJson(cwd: string): { source: string; data: Package; diff --git a/packages/sv/src/cli/create.ts b/packages/sv/src/cli/create.ts index 75888d8ee..5f28b9aa5 100644 --- a/packages/sv/src/cli/create.ts +++ b/packages/sv/src/cli/create.ts @@ -480,10 +480,8 @@ export async function createVirtualWorkspace({ file: { ...tentativeWorkspace.file, viteConfig: - type === 'typescript' - ? common.commonFilePaths.viteConfigTS - : common.commonFilePaths.viteConfig, - svelteConfig: common.commonFilePaths.svelteConfig // currently we always use js files, never typescript files + type === 'typescript' ? common.filePaths.viteConfigTS : common.filePaths.viteConfig, + svelteConfig: common.filePaths.svelteConfig // currently we always use js files, never typescript files } }; diff --git a/packages/sv/src/core/common.ts b/packages/sv/src/core/common.ts index c834a08a7..dce24eab7 100644 --- a/packages/sv/src/core/common.ts +++ b/packages/sv/src/core/common.ts @@ -325,7 +325,7 @@ export function updateAgent( } } -export const commonFilePaths = { +export const filePaths = { packageJson: 'package.json', svelteConfig: 'svelte.config.js', svelteConfigTS: 'svelte.config.ts', diff --git a/packages/sv/src/core/engine.ts b/packages/sv/src/core/engine.ts index 99304e745..f575d92af 100644 --- a/packages/sv/src/core/engine.ts +++ b/packages/sv/src/core/engine.ts @@ -10,7 +10,7 @@ import { } from '@sveltejs/sv-utils'; import { NonZeroExitError, exec } from 'tinyexec'; import { createLoadedAddon } from '../cli/add.ts'; -import { commonFilePaths } from './common.ts'; +import { filePaths } from './common.ts'; import { getErrorHint, type Addon, @@ -53,8 +53,8 @@ function updatePackages( if (data.devDependencies) data.devDependencies = alphabetizePackageJsonDependencies(data.devDependencies); - saveFile(cwd, commonFilePaths.packageJson, generateCode()); - return commonFilePaths.packageJson; + saveFile(cwd, filePaths.packageJson, generateCode()); + return filePaths.packageJson; } export type InstallOptions = { diff --git a/packages/sv/src/core/workspace.ts b/packages/sv/src/core/workspace.ts index 1c30d550d..d7e22716e 100644 --- a/packages/sv/src/core/workspace.ts +++ b/packages/sv/src/core/workspace.ts @@ -9,7 +9,7 @@ import { import * as find from 'empathic/find'; import fs from 'node:fs'; import path from 'node:path'; -import { commonFilePaths } from './common.ts'; +import { filePaths } from './common.ts'; import { svDeprecated } from './deprecated.ts'; import type { OptionDefinition, OptionValues } from './options.ts'; import { detectPackageManager } from './package-manager.ts'; @@ -38,15 +38,15 @@ export type Workspace = { package: 'package.json'; gitignore: '.gitignore'; - /** @deprecated use the string `'.prettierignore'` directly */ + /** @deprecated use the string `.prettierignore` instead. */ prettierignore: '.prettierignore'; - /** @deprecated use the string `'.prettierrc'` directly */ + /** @deprecated use the string `.prettierrc` instead. */ prettierrc: '.prettierrc'; - /** @deprecated use the string `'eslint.config.js'` directly */ + /** @deprecated use the string `eslint.config.js` instead. */ eslintConfig: 'eslint.config.js'; - /** @deprecated use the string `'.vscode/settings.json'` directly */ + /** @deprecated use the string `.vscode/settings.json` instead. */ vscodeSettings: '.vscode/settings.json'; - /** @deprecated use the string `'.vscode/extensions.json'` directly */ + /** @deprecated use the string `.vscode/extensions.json` instead. */ vscodeExtensions: '.vscode/extensions.json'; /** Get the relative path between two files */ @@ -87,18 +87,16 @@ export async function createWorkspace({ const resolvedCwd = path.resolve(cwd); // Will go up and prioritize jsconfig.json as it's first in the array - const typeConfigOptions = [commonFilePaths.jsconfig, commonFilePaths.tsconfig]; + const typeConfigOptions = [filePaths.jsconfig, filePaths.tsconfig]; const typeConfig = find.any(typeConfigOptions, { cwd }) as Workspace['file']['typeConfig']; - const typescript = typeConfig?.endsWith(commonFilePaths.tsconfig) ?? false; + const typescript = typeConfig?.endsWith(filePaths.tsconfig) ?? false; // This is not linked with typescript detection - const viteConfigPath = path.join(resolvedCwd, commonFilePaths.viteConfigTS); - const viteConfig = fs.existsSync(viteConfigPath) - ? commonFilePaths.viteConfigTS - : commonFilePaths.viteConfig; - const svelteConfigPath = path.join(resolvedCwd, commonFilePaths.svelteConfigTS); + const viteConfigPath = path.join(resolvedCwd, filePaths.viteConfigTS); + const viteConfig = fs.existsSync(viteConfigPath) ? filePaths.viteConfigTS : filePaths.viteConfig; + const svelteConfigPath = path.join(resolvedCwd, filePaths.svelteConfigTS); const svelteConfig = fs.existsSync(svelteConfigPath) - ? commonFilePaths.svelteConfigTS - : commonFilePaths.svelteConfig; + ? filePaths.svelteConfigTS + : filePaths.svelteConfig; let dependencies: Record = {}; if (override?.dependencies) { @@ -113,7 +111,7 @@ export async function createWorkspace({ // we are still in the workspace (including the workspace root) directory.length >= workspaceRoot.length ) { - if (fs.existsSync(path.join(directory, commonFilePaths.packageJson))) { + if (fs.existsSync(path.join(directory, filePaths.packageJson))) { const { data: packageJson } = loadPackageJson(directory); dependencies = { ...packageJson.devDependencies, @@ -156,35 +154,35 @@ export async function createWorkspace({ /** @deprecated */ get prettierignore() { svDeprecated( - '`workspace.file.prettierignore` is deprecated, use the string `".prettierignore"` directly' + '`workspace.file.prettierignore` is deprecated, use the string `.prettierignore` isntead.' ); return '.prettierignore' as const; }, /** @deprecated */ get prettierrc() { svDeprecated( - '`workspace.file.prettierrc` is deprecated, use the string `".prettierrc"` directly' + '`workspace.file.prettierrc` is deprecated, use the string `.prettierrc` isntead.' ); return '.prettierrc' as const; }, /** @deprecated */ get eslintConfig() { svDeprecated( - '`workspace.file.eslintConfig` is deprecated, use the string `"eslint.config.js"` directly' + '`workspace.file.eslintConfig` is deprecated, use the string `eslint.config.js` isntead.' ); return 'eslint.config.js' as const; }, /** @deprecated */ get vscodeSettings() { svDeprecated( - '`workspace.file.vscodeSettings` is deprecated, use the string `".vscode/settings.json"` directly' + '`workspace.file.vscodeSettings` is deprecated, use the string `.vscode/settings.json` isntead.' ); return '.vscode/settings.json' as const; }, /** @deprecated */ get vscodeExtensions() { svDeprecated( - '`workspace.file.vscodeExtensions` is deprecated, use the string `".vscode/extensions.json"` directly' + '`workspace.file.vscodeExtensions` is deprecated, use the string `.vscode/extensions.json` isntead.' ); return '.vscode/extensions.json' as const; }, @@ -217,7 +215,7 @@ function findWorkspaceRoot(cwd: string): string { const { root } = path.parse(cwd); let directory = cwd; while (directory && directory !== root) { - if (fs.existsSync(path.join(directory, commonFilePaths.packageJson))) { + if (fs.existsSync(path.join(directory, filePaths.packageJson))) { // in pnpm it can be a file if (fs.existsSync(path.join(directory, 'pnpm-workspace.yaml'))) { return directory; diff --git a/packages/sv/src/create/index.ts b/packages/sv/src/create/index.ts index ffe49c5ee..8b487a481 100644 --- a/packages/sv/src/create/index.ts +++ b/packages/sv/src/create/index.ts @@ -1,7 +1,7 @@ import { sanitizeName } from '@sveltejs/sv-utils'; import fs from 'node:fs'; import path from 'node:path'; -import { commonFilePaths } from '../core/common.ts'; +import { filePaths } from '../core/common.ts'; import { mkdirp, copy, dist, getSharedFiles, replace, kv } from './utils.ts'; export type TemplateType = (typeof templateTypes)[number]; @@ -81,7 +81,7 @@ function write_template_files(template: string, types: LanguageType, name: strin function write_common_files(cwd: string, options: Omit, name: string) { const files = getSharedFiles(); - const pkg_file = path.join(cwd, commonFilePaths.packageJson); + const pkg_file = path.join(cwd, filePaths.packageJson); const pkg = /** @type {any} */ JSON.parse(fs.readFileSync(pkg_file, 'utf-8')); sort_files(files).forEach((file) => { @@ -90,7 +90,7 @@ function write_common_files(cwd: string, options: Omit, name: st if (exclude || !include) return; - if (file.name === commonFilePaths.packageJson) { + if (file.name === filePaths.packageJson) { const new_pkg = JSON.parse(file.contents); merge(pkg, new_pkg); } else { diff --git a/packages/sv/src/create/playground.ts b/packages/sv/src/create/playground.ts index f93788126..b93a393bb 100644 --- a/packages/sv/src/create/playground.ts +++ b/packages/sv/src/create/playground.ts @@ -9,7 +9,7 @@ import { } from '@sveltejs/sv-utils'; import fs from 'node:fs'; import path from 'node:path'; -import { commonFilePaths } from '../core/common.ts'; +import { filePaths } from '../core/common.ts'; import { getSharedFiles } from './utils.ts'; export function validatePlaygroundUrl(link: string): boolean { @@ -241,7 +241,7 @@ export function setupPlaygroundProject( fs.writeFileSync(filePath, newContent, 'utf-8'); // add packages as dependencies to package.json if requested - const pkgPath = path.join(cwd, commonFilePaths.packageJson); + const pkgPath = path.join(cwd, filePaths.packageJson); const pkgSource = fs.readFileSync(pkgPath, 'utf-8'); const pkgJson = parse.json(pkgSource); let updatePackageJson = false; @@ -255,7 +255,7 @@ export function setupPlaygroundProject( let experimentalAsyncNeeded = true; const addExperimentalAsync = () => { - const svelteConfigPath = path.join(cwd, commonFilePaths.svelteConfig); + const svelteConfigPath = path.join(cwd, filePaths.svelteConfig); const svelteConfig = fs.readFileSync(svelteConfigPath, 'utf-8'); const { ast, generateCode } = parse.script(svelteConfig); const { value: config } = js.exports.createDefault(ast, { fallback: js.object.create({}) }); diff --git a/packages/sv/src/index.ts b/packages/sv/src/index.ts index ed4108934..7d99276e8 100644 --- a/packages/sv/src/index.ts +++ b/packages/sv/src/index.ts @@ -3,7 +3,7 @@ import { create as _create, type Options as CreateOptions } from './create/index export type { TemplateType, LanguageType } from './create/index.ts'; -/** @deprecated use `create({ cwd, ...options })` instead */ +/** @deprecated use `create({ cwd, ...options })` instead. */ export function create(cwd: string, options: Omit): void; export function create(options: CreateOptions): void; export function create( From 1a59ab07a29f3f7afb52c5ab66f402c8058749b3 Mon Sep 17 00:00:00 2001 From: jycouet Date: Mon, 6 Apr 2026 20:56:11 +0200 Subject: [PATCH 30/31] rmv some JSDoc --- packages/sv-utils/src/files.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/sv-utils/src/files.ts b/packages/sv-utils/src/files.ts index c4c9c9135..3aaaf052e 100644 --- a/packages/sv-utils/src/files.ts +++ b/packages/sv-utils/src/files.ts @@ -13,7 +13,6 @@ export type Package = { workspaces?: string[]; }; -/** Check if a file exists at the given workspace-relative path. */ /** * Checks the file. * @param filePath - Resolves paths relative to the workspace. @@ -57,7 +56,6 @@ export function saveFile(cwd: string, filePath: string, content: string): void { fs.writeFileSync(fullFilePath, content, 'utf8'); } -/** Load and parse a workspace-relative `package.json`. Throws if missing or invalid. */ /** * Loads the workspace `package.json`. * @returns From f712cde879210a77d87754b039d6304ebf5a99c3 Mon Sep 17 00:00:00 2001 From: jycouet Date: Mon, 6 Apr 2026 21:03:20 +0200 Subject: [PATCH 31/31] small cleanup --- packages/sv-utils/api-surface.md | 1 - packages/sv-utils/src/files.ts | 11 +++++------ packages/sv/src/core/engine.ts | 11 ++++++----- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/packages/sv-utils/api-surface.md b/packages/sv-utils/api-surface.md index 4e6e5dc86..21dfcbb01 100644 --- a/packages/sv-utils/api-surface.md +++ b/packages/sv-utils/api-surface.md @@ -756,7 +756,6 @@ declare function saveFile(cwd: string, filePath: string, content: string): void; declare function loadPackageJson(cwd: string): { source: string; data: Package; - generateCode: () => string; }; type ColorInput = string | string[]; declare const color: { diff --git a/packages/sv-utils/src/files.ts b/packages/sv-utils/src/files.ts index 3aaaf052e..8b8633f16 100644 --- a/packages/sv-utils/src/files.ts +++ b/packages/sv-utils/src/files.ts @@ -61,19 +61,18 @@ export function saveFile(cwd: string, filePath: string, content: string): void { * @returns * - `source`: The raw UTF-8 text. * - `data`: The parsed JSON object. - * - `generateCode`: A function to serialize the data back to a string. */ export function loadPackageJson(cwd: string): { source: string; data: Package; - generateCode: () => string; } { - const packageText = loadFile(cwd, 'package.json'); - if (!packageText) { + const source = loadFile(cwd, 'package.json'); + + if (!source) { const pkgPath = path.join(cwd, 'package.json'); throw new Error(`Invalid workspace: missing '${pkgPath}'`); } - const { data, generateCode } = parseJson(packageText); - return { source: packageText, data: data as Package, generateCode }; + const { data } = parseJson(source); + return { source, data: data as Package }; } diff --git a/packages/sv/src/core/engine.ts b/packages/sv/src/core/engine.ts index f575d92af..ecd19cd47 100644 --- a/packages/sv/src/core/engine.ts +++ b/packages/sv/src/core/engine.ts @@ -4,6 +4,7 @@ import { fileExists, loadFile, loadPackageJson, + parse, saveFile, resolveCommand, type AgentName @@ -25,7 +26,7 @@ import { TESTING } from './env.ts'; import { addPnpmOnlyBuiltDependencies } from './package-manager.ts'; import { createWorkspace, type Workspace } from './workspace.ts'; -function alphabetizePackageJsonDependencies(obj: Record) { +function alphabetizeRecord(obj: Record) { const ordered: Record = {}; for (const [key, value] of Object.entries(obj).sort(([a], [b]) => a.localeCompare(b))) { ordered[key] = value; @@ -37,7 +38,8 @@ function updatePackages( dependencies: Array<{ pkg: string; version: string; dev: boolean }>, cwd: string ): string { - const { data, generateCode } = loadPackageJson(cwd); + const { source } = loadPackageJson(cwd); + const { data, generateCode } = parse.json(source); for (const dependency of dependencies) { if (dependency.dev) { @@ -49,9 +51,8 @@ function updatePackages( } } - if (data.dependencies) data.dependencies = alphabetizePackageJsonDependencies(data.dependencies); - if (data.devDependencies) - data.devDependencies = alphabetizePackageJsonDependencies(data.devDependencies); + if (data.dependencies) data.dependencies = alphabetizeRecord(data.dependencies); + if (data.devDependencies) data.devDependencies = alphabetizeRecord(data.devDependencies); saveFile(cwd, filePaths.packageJson, generateCode()); return filePaths.packageJson;