Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure public types don't reference internal types #4021

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion documentation/docs/14-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: Types

### @sveltejs/kit

All APIs in SvelteKit are fully typed. The following types can be imported from `@sveltejs/kit`:
All APIs in SvelteKit are fully typed. The following types are defined by `@sveltejs/kit`:

**TYPES**

Expand Down
14 changes: 12 additions & 2 deletions packages/kit/scripts/extract-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,18 @@ for (const statement of node.statements) {
start = statement.jsDoc[0].end;
}

const i = code.indexOf('export', start);
start = i + 6;
start = Math.min(
...[
code.indexOf('export class ', start),
code.indexOf('export namespace ', start),
code.indexOf('export interface ', start),
code.indexOf('export type ', start),
code.indexOf('class ', start),
code.indexOf('namespace ', start),
code.indexOf('interface ', start),
code.indexOf('type ', start)
].filter((i) => i >= 0)
);

const snippet = prettier.format(code.slice(start, statement.end).trim(), {
parser: 'typescript',
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/core/dev/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export async function create_plugin(config, cwd) {
configureServer(vite) {
__fetch_polyfill();

/** @type {import('types').SSRManifest} */
/** @type {import('types').SSRManifestInternal} */
let manifest;

function update_manifest() {
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/core/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export function get_mime_lookup(manifest_data) {
return mime;
}

/** @param {import('@sveltejs/kit').ValidatedConfig} config */
/** @param {import('types').ValidatedConfig} config */
export function get_aliases(config) {
const alias = {
__GENERATED__: path.posix.resolve(`${SVELTE_KIT}/generated`),
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export async function respond(request, options, state = {}) {
rawBody: body_getter
});

/** @type {import('types').RequiredResolveOptions} */
/** @type {Required<import('types').ResolveOptions>} */
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since this is used in a bunch of places perhaps it would make sense to have a RequiredResolveOptions type in internal.d.ts

Copy link
Member Author

@benmccann benmccann Feb 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd thought about it, but it only saves two characters and adds a layer of indirection, so is it even worth it?

let resolve_opts = {
ssr: true,
transformPage: default_transform
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/server/page/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { respond } from './respond.js';
* @param {import('types').SSRPage} route
* @param {import('types').SSROptions} options
* @param {import('types').SSRState} state
* @param {import('types').RequiredResolveOptions} resolve_opts
* @param {Required<import('types').ResolveOptions>} resolve_opts
* @returns {Promise<Response | undefined>}
*/
export async function render_page(event, route, options, state, resolve_opts) {
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/server/page/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const updated = {
* error?: Error;
* url: URL;
* params: Record<string, string>;
* resolve_opts: import('types').RequiredResolveOptions;
* resolve_opts: Required<import('types').ResolveOptions>;
* stuff: Record<string, any>;
* }} opts
*/
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/server/page/respond.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { coalesce_to_error } from '../../../utils/error.js';
* options: SSROptions;
* state: SSRState;
* $session: any;
* resolve_opts: import('types').RequiredResolveOptions;
* resolve_opts: Required<import('types').ResolveOptions>;
* route: import('types').SSRPage;
* params: Record<string, string>;
* }} opts
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/server/page/respond_with_error.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { coalesce_to_error } from '../../../utils/error.js';
* $session: any;
* status: number;
* error: Error;
* resolve_opts: import('types').RequiredResolveOptions;
* resolve_opts: Required<import('types').ResolveOptions>;
* }} opts
*/
export async function respond_with_error({
Expand Down
107 changes: 77 additions & 30 deletions packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,39 @@
import './ambient';

import { CompileOptions } from 'svelte/types/compiler/interfaces';
import {
AdapterEntry,
Body,
Either,
Fallthrough,
Logger,
MaybePromise,
PrerenderOnErrorValue,
RecursiveRequired,
RequiredResolveOptions,
ResponseHeaders,
RouteDefinition,
SSRNodeLoader,
SSRRoute,
TrailingSlash
} from './internal';
import './ambient';

export interface Adapter {
name: string;
adapt(builder: Builder): Promise<void>;
}

interface AdapterEntry {
/**
* A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication.
* For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both
* be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID
*/
id: string;

/**
* A function that compares the candidate route with the current route to determine
* if it should be treated as a fallback for the current route. For example, `/foo/[c]`
* is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes
*/
filter: (route: RouteDefinition) => boolean;

/**
* A function that is invoked once the entry has been created. This is where you
* should write the function to the filesystem and generate redirect manifests.
*/
complete: (entry: {
generateManifest: (opts: { relativePath: string; format?: 'esm' | 'cjs' }) => string;
}) => void;
}

type Body = JSONValue | Uint8Array | ReadableStream | import('stream').Readable;

export interface Builder {
log: Logger;
rimraf(dir: string): void;
Expand Down Expand Up @@ -250,6 +261,8 @@ export type CspDirectives = {
>;
};

type Either<T, U> = Only<T, U> | Only<U, T>;

export interface EndpointOutput<Output extends Body = Body> {
status?: number;
headers?: Headers | Partial<ResponseHeaders>;
Expand All @@ -269,6 +282,10 @@ export interface ExternalFetch {
(req: Request): Promise<Response>;
}

interface Fallthrough {
fallthrough: true;
}

export interface GetSession {
(event: RequestEvent): MaybePromise<App.Session>;
}
Expand All @@ -284,6 +301,12 @@ export interface HandleError {
(input: { error: Error & { frame?: string }; event: RequestEvent }): void;
}

type HttpMethod = 'get' | 'head' | 'post' | 'put' | 'delete' | 'patch';

type JSONObject = { [key: string]: JSONValue };

type JSONValue = string | number | boolean | null | ToJSON | JSONValue[] | JSONObject;

export interface Load<Params = Record<string, string>, Props = Record<string, any>> {
(input: LoadInput<Params>): MaybePromise<Either<Fallthrough, LoadOutput<Props>>>;
}
Expand All @@ -306,11 +329,24 @@ export interface LoadOutput<Props = Record<string, any>> {
maxage?: number;
}

interface Logger {
(msg: string): void;
success(msg: string): void;
error(msg: string): void;
warn(msg: string): void;
minor(msg: string): void;
info(msg: string): void;
}

type MaybePromise<T> = T | Promise<T>;

export interface Navigation {
from: URL;
to: URL;
}

type Only<T, U> = { [P in keyof T]: T[P] } & { [P in Exclude<keyof U, keyof T>]?: never };

export interface Page<Params extends Record<string, string> = Record<string, string>> {
url: URL;
params: Params;
Expand Down Expand Up @@ -354,6 +390,11 @@ export interface PrerenderErrorHandler {
}): void;
}

type PrerenderOnErrorValue = 'fail' | 'continue' | PrerenderErrorHandler;

/** `string[]` is only for set-cookie, everything else must be type of `string` */
type ResponseHeaders = Record<string, string | number | string[]>;

export interface RequestEvent<Params = Record<string, string>> {
request: Request;
url: URL;
Expand All @@ -378,28 +419,34 @@ export interface RequestOptions {
platform?: App.Platform;
}

export type ResolveOptions = Partial<RequiredResolveOptions>;
export type ResolveOptions = {
ssr?: boolean;
transformPage?: ({ html }: { html: string }) => MaybePromise<string>;
};

export class Server {
constructor(manifest: SSRManifest);
respond(request: Request, options?: RequestOptions): Promise<Response>;
}

interface RouteDefinition {
type: 'page' | 'endpoint';
pattern: RegExp;
segments: RouteSegment[];
methods: HttpMethod[];
}

interface RouteSegment {
content: string;
dynamic: boolean;
rest: boolean;
}

export interface SSRManifest {
appDir: string;
assets: Set<string>;
/** private fields */
_: {
mime: Record<string, string>;
entry: {
file: string;
js: string[];
css: string[];
};
nodes: SSRNodeLoader[];
routes: SSRRoute[];
};
}

// TODO should this be public?
export type ValidatedConfig = RecursiveRequired<Config>;
type ToJSON = { toJSON(...args: any[]): Exclude<JSONValue, ToJSON> };

type TrailingSlash = 'never' | 'always' | 'ignore';
Loading