Skip to content

Commit

Permalink
fix typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
ryansolid committed Feb 13, 2024
1 parent f73de3a commit dafdd97
Show file tree
Hide file tree
Showing 24 changed files with 159 additions and 119 deletions.
5 changes: 5 additions & 0 deletions .changeset/dry-seals-hang.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solidjs/start": patch
---

fix typescript
3 changes: 2 additions & 1 deletion packages/start/client/StartClient.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// @ts-ignore
import App from "#start/app";
import type { JSX } from "solid-js";
import { ErrorBoundary } from "../shared/ErrorBoundary";
import "./mount";

function Dummy(props) {
function Dummy(props: { children: JSX.Element }) {
return props.children;
}

Expand Down
11 changes: 6 additions & 5 deletions packages/start/client/mount.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { JSX } from "solid-js";
import { createStore } from "solid-js/store";
import { createComponent, getHydrationKey, getOwner, hydrate } from "solid-js/web";
import { createComponent, getHydrationKey, getOwner, hydrate, type MountableElement } from "solid-js/web";

export function mount(fn, el) {
export function mount(fn: () => JSX.Element, el: MountableElement) {
if (import.meta.env.START_ISLANDS) {
const map = new WeakMap();
async function mountIsland(el: HTMLElement) {
Expand All @@ -19,11 +20,11 @@ export function mount(fn, el) {

let mod = await import(
/* @vite-ignore */
import.meta.env.MANIFEST["client"].chunks[el.dataset.id.split("#")[0]].output.path
import.meta.env.MANIFEST["client"]!.chunks[el.dataset.id!.split("#")[0] as string]!.output.path
);
if (!mod || !el.dataset.hk) return;

let Component = mod[el.dataset.id.split("#")[1]];
let Component = mod[el.dataset.id!.split("#")[1] as string];
let hk = el.dataset.hk;
// _$DEBUG("hydrating island", el.dataset.island, hk.slice(0, hk.length - 1) + `1-`, el);

Expand Down Expand Up @@ -68,7 +69,7 @@ export function mount(fn, el) {
Promise.all(
[...assets].map(
asset =>
import(/* @vite-ignore */import.meta.env.MANIFEST["client"].chunks[asset.split("#")[0]].output.path)
import(/* @vite-ignore */import.meta.env.MANIFEST["client"]!.chunks[asset.split("#")[0] as string]!.output.path)
)
)
.then(() => {
Expand Down
3 changes: 2 additions & 1 deletion packages/start/client/spa/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { JSX } from "solid-js";
import { render } from "solid-js/web";
import "vinxi/client";

export function mount(fn, el) {
export function mount(fn: () => JSX.Element, el: HTMLElement) {
render(fn, el);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/start/config/server-fns-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { getRequestEvent } from "solid-js/web";
import { provideRequestEvent } from "solid-js/web/storage";
import { cloneEvent } from "../server/fetchEvent";

export function createServerReference(fn, id, name) {
export function createServerReference(fn: Function, id: string, name: string) {
if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
const baseURL = import.meta.env.SERVER_BASE_URL;
return new Proxy(fn, {
Expand Down
30 changes: 15 additions & 15 deletions packages/start/config/server-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,22 @@ import {
import { sharedConfig } from "solid-js";
import { renderToStringAsync } from "solid-js/web";
import { provideRequestEvent } from "solid-js/web/storage";
import { eventHandler, setHeader, setResponseStatus } from "vinxi/http";
import { eventHandler, setHeader, setResponseStatus, type H3Event } from "vinxi/http";
import invariant from "vinxi/lib/invariant";
import { cloneEvent, getFetchEvent, mergeResponseHeaders } from "../server/fetchEvent";
import { createPageEvent } from "../server/pageEvent";
// @ts-ignore
import App from "#start/app";
import { FetchEvent, PageEvent } from "../server";

function createChunk(data) {
function createChunk(data: string) {
const bytes = data.length;
const baseHex = bytes.toString(16);
const totalHex = "00000000".substring(0, 8 - baseHex.length) + baseHex; // 32-bit
return new TextEncoder().encode(`;0x${totalHex};${data}`);
}

function serializeToStream(id: string, value) {
function serializeToStream(id: string, value: any) {
return new ReadableStream({
start(controller) {
crossSerializeStream(value, {
Expand Down Expand Up @@ -64,7 +64,7 @@ function serializeToStream(id: string, value) {
});
}

async function handleServerFunction(h3Event) {
async function handleServerFunction(h3Event: H3Event) {
const event = getFetchEvent(h3Event);
const request = event.request;

Expand All @@ -83,14 +83,14 @@ async function handleServerFunction(h3Event) {
}

const serverFunction = (
await import.meta.env.MANIFEST[import.meta.env.ROUTER_NAME].chunks[filepath].import()
)[name];
let parsed = [];
await import.meta.env.MANIFEST[import.meta.env.ROUTER_NAME]!.chunks[filepath!]!.import()
)[name!];
let parsed: any[] = [];

// grab bound arguments from url when no JS
if (!instance || h3Event.method === "GET") {
const args = url.searchParams.get("args");
if (args) JSON.parse(args).forEach(arg => parsed.push(arg));
if (args) JSON.parse(args).forEach((arg: any) => parsed.push(arg));
}
if (h3Event.method === "POST") {
const contentType = request.headers.get("content-type");
Expand All @@ -101,14 +101,14 @@ async function handleServerFunction(h3Event) {
// workaround for https://github.com/unjs/nitro/issues/1721
// (issue only in edge runtimes)
parsed.push(
await new Request(request, { ...request, body: h3Event.node.req.body }).formData()
await new Request(request, { ...request, body: (h3Event.node.req as any).body }).formData()
);
// what should work when #1721 is fixed
// parsed.push(await request.formData);
} else {
// workaround for https://github.com/unjs/nitro/issues/1721
// (issue only in edge runtimes)
const tmpReq = new Request(request, { ...request, body: h3Event.node.req.body });
const tmpReq = new Request(request, { ...request, body: (h3Event.node.req as any).body });
// what should work when #1721 is fixed
// just use request.json() here
parsed = fromJSON(await tmpReq.json(), {
Expand Down Expand Up @@ -150,7 +150,7 @@ async function handleServerFunction(h3Event) {
// handle no JS success case
if (!instance) {
const isError = result instanceof Error;
const refererUrl = new URL(request.headers.get("referer"));
const refererUrl = new URL(request.headers.get("referer")!);
return new Response(null, {
status: 302,
headers: {
Expand Down Expand Up @@ -184,14 +184,14 @@ async function handleServerFunction(h3Event) {
}

async function handleSingleFlight(sourceEvent: FetchEvent, result: any) {
let revalidate;
let url = new URL(sourceEvent.request.headers.get("referer")).toString();
let revalidate: string[];
let url = new URL(sourceEvent.request.headers.get("referer")!).toString();
if (result instanceof Response) {
if (result.headers.has("X-Revalidate"))
revalidate = result.headers.get("X-Revalidate").split(",");
revalidate = result.headers.get("X-Revalidate")!.split(",");
if (result.headers.has("Location"))
url = new URL(
result.headers.get("Location"),
result.headers.get("Location")!,
new URL(sourceEvent.request.url).origin + import.meta.env.SERVER_BASE_URL
).toString();
}
Expand Down
13 changes: 7 additions & 6 deletions packages/start/config/server-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ import {
URLPlugin,
URLSearchParamsPlugin
} from "seroval-plugins/web";
import { type Component } from "solid-js";
import { createIslandReference } from "../server/islands";

class SerovalChunkReader {
reader: ReadableStreamDefaultReader<Uint8Array>;
buffer: string;
done: boolean;
constructor(stream) {
constructor(stream: ReadableStream<Uint8Array>) {
this.reader = stream.getReader();
this.buffer = "";
this.done = false;
Expand All @@ -34,7 +35,7 @@ class SerovalChunkReader {
}
}

async next() {
async next(): Promise<any> {
// Check if the buffer is empty
if (this.buffer === "") {
// if we are already done...
Expand Down Expand Up @@ -84,7 +85,7 @@ class SerovalChunkReader {
}
}

async function deserializeStream(id, response) {
async function deserializeStream(id: string, response: Response) {
if (!response.body) {
throw new Error("missing body");
}
Expand Down Expand Up @@ -184,7 +185,7 @@ async function fetchServerFunction(
throw result;
}

export function createServerReference(fn, id, name) {
export function createServerReference(fn: Function, id: string, name: string) {
const baseURL = import.meta.env.SERVER_BASE_URL;
return new Proxy(fn, {
get(target, prop, receiver) {
Expand All @@ -196,7 +197,7 @@ export function createServerReference(fn, id, name) {
}
if (prop === "withOptions") {
return (options: RequestInit) => {
const fn = (...args) => {
const fn = (...args: any[]) => {
const encodeArgs = options.method && options.method.toUpperCase() === "GET";
return fetchServerFunction(
encodeArgs
Expand All @@ -218,7 +219,7 @@ export function createServerReference(fn, id, name) {
});
}

export function createClientReference(Component, id, name) {
export function createClientReference(Component: Component<any>, id: string, name: string) {
if (typeof Component === "function") {
return createIslandReference(Component, id, name);
}
Expand Down
32 changes: 17 additions & 15 deletions packages/start/server/StartServer.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-ignore
import App from "#start/app";
import type { Component } from "solid-js";
import type { Component, JSX } from "solid-js";
import {
Hydration,
HydrationScript,
Expand All @@ -11,15 +11,15 @@ import {
} from "solid-js/web";
import { ErrorBoundary } from "../shared/ErrorBoundary";
import { renderAsset } from "./renderAsset";
import type { DocumentComponentProps } from "./types";
import type { Asset, DocumentComponentProps, PageEvent } from "./types";

const docType = ssr("<!DOCTYPE html>");

function matchRoute(matches, routes, matched = []) {
function matchRoute(matches: any[], routes: any[], matched = []): any[] | undefined {
for (let i = 0; i < routes.length; i++) {
const segment = routes[i];
if (segment.path !== matches[0].path) continue;
let next = [...matched, segment];
let next: any = [...matched, segment];
if (segment.children) {
const nextMatches = matches.slice(1);
if (nextMatches.length === 0) continue;
Expand All @@ -31,21 +31,23 @@ function matchRoute(matches, routes, matched = []) {
}

export function StartServer(props: { document: Component<DocumentComponentProps> }) {
const context = getRequestEvent() as any;
const context = getRequestEvent() as PageEvent;

let assets = [];
let assets: Asset[] = [];
Promise.resolve().then(async () => {
// @ts-ignore
if (context.router && context.router.matches) {
// @ts-ignore
const matches = [...context.router.matches];
while (matches.length && (!matches[0].info || !matches[0].info.filesystem))
matches.shift();
const matched = matches.length && matchRoute(matches, context.routes);
if (matched) {
for (let i = 0; i < matched.length; i++) {
const segment = matched[i];
const part = import.meta.env.MANIFEST[import.meta.env.START_ISLANDS ? "ssr" : "client"]
.inputs[segment["$component"].src];
const asset = await part.assets();
const part = import.meta.env.MANIFEST[import.meta.env.START_ISLANDS ? "ssr" : "client"]!
.inputs[segment["$component"].src]!;
const asset = await part.assets() as any;
assets.push.apply(assets, asset);
}
} else console.warn("No route matched for preloading js assets");
Expand All @@ -54,8 +56,8 @@ export function StartServer(props: { document: Component<DocumentComponentProps>
assets = [...new Map(assets.map(item => [item.attrs.key, item])).values()].filter(asset =>
import.meta.env.START_ISLANDS
? false
: asset.attrs.rel === "modulepreload" &&
!context.assets.find(a => a.attrs.key === asset.attrs.key)
: (asset.attrs as JSX.LinkHTMLAttributes<HTMLLinkElement>).rel === "modulepreload" &&
!context.assets.find((a: Asset) => a.attrs.key === asset.attrs.key)
);
});

Expand All @@ -68,7 +70,7 @@ export function StartServer(props: { document: Component<DocumentComponentProps>
assets={
<>
<HydrationScript />
{context.assets.map(m => renderAsset(m))}
{context.assets.map((m: any) => renderAsset(m))}
</>
}
scripts={
Expand All @@ -78,9 +80,9 @@ export function StartServer(props: { document: Component<DocumentComponentProps>
type="module"
async
src={
import.meta.env.MANIFEST["client"].inputs[
import.meta.env.MANIFEST["client"].handler
].output.path
import.meta.env.MANIFEST["client"]!.inputs[
import.meta.env.MANIFEST["client"]!.handler
]!.output.path
}
/>
</>
Expand Down
9 changes: 5 additions & 4 deletions packages/start/server/fetchEvent.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
H3Event,
HTTPEvent,
HTTPEventSymbol,
appendResponseHeader,
getRequestIP,
Expand Down Expand Up @@ -37,15 +38,15 @@ export function cloneEvent<T extends FetchEvent>(fetchEvent: T): T {
}

export function getFetchEvent(h3Event: H3Event): FetchEvent {
if (!h3Event[fetchEventSymbol]) {
if (!(h3Event as any)[fetchEventSymbol]) {
const fetchEvent = createFetchEvent(h3Event);
h3Event[fetchEventSymbol] = fetchEvent;
(h3Event as any)[fetchEventSymbol] = fetchEvent;
}

return h3Event[fetchEventSymbol];
return (h3Event as any)[fetchEventSymbol];
}

export function mergeResponseHeaders(h3Event, headers) {
export function mergeResponseHeaders(h3Event: HTTPEvent, headers: Headers) {
for (const [key, value] of headers.entries()) {
setHeader(h3Event, key, value);
}
Expand Down
10 changes: 5 additions & 5 deletions packages/start/server/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function createBaseHandler(
return eventHandler({
onRequest: options.onRequest,
onBeforeResponse: options.onBeforeResponse,
handler: (e: H3Event<EventHandlerRequest> & { startEvent: FetchEvent }) => {
handler: (e: H3Event<EventHandlerRequest>) => {
const event = getFetchEvent(e);
const mode = import.meta.env.START_SSR;

Expand All @@ -41,7 +41,7 @@ export function createBaseHandler(
if (match) {
const mod = await match.handler.import();
const fn = mod[event.request.method];
(event as APIEvent).params = match.params;
(event as APIEvent).params = match.params || {};
// @ts-ignore
sharedConfig.context = { event };
const res = await fn(event);
Expand All @@ -61,7 +61,7 @@ export function createBaseHandler(
return fn(context);
}, options);
if (context.response && context.response.headers.get("Location")) {
return sendRedirect(event, context.response.headers.get("Location"));
return sendRedirect(event, context.response.headers.get("Location")!);
}
return html;
}
Expand All @@ -85,7 +85,7 @@ export function createBaseHandler(
return fn(context);
}, cloned);
if (context.response && context.response.headers.get("Location")) {
return sendRedirect(event, context.response.headers.get("Location"));
return sendRedirect(event, context.response.headers.get("Location")!);
}
if (mode === "async") return stream;
// fix cloudflare streaming
Expand All @@ -101,7 +101,7 @@ function handleShellCompleteRedirect(context: PageEvent, e: H3Event<EventHandler
return () => {
if (context.response && context.response.headers.get("Location")) {
setResponseStatus(e, 302);
setHeader(e, "Location", context.response.headers.get("Location"));
setHeader(e, "Location", context.response.headers.get("Location")!);
}
};
}
Expand Down
Loading

0 comments on commit dafdd97

Please sign in to comment.