Skip to content

Commit d8e3827

Browse files
authored
site: fix type errors in JS files (#9354)
1 parent ac7505d commit d8e3827

File tree

20 files changed

+164
-85
lines changed

20 files changed

+164
-85
lines changed

sites/svelte.dev/src/lib/db/client.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,14 @@ import { dev } from '$app/environment';
22
import { SUPABASE_URL, SUPABASE_KEY } from '$env/static/private';
33
import { createClient } from '@supabase/supabase-js';
44

5+
const client_enabled = !!(!dev || (SUPABASE_URL && SUPABASE_KEY));
6+
7+
/**
8+
* @type {import('@supabase/supabase-js').SupabaseClient<any, "public", any>}
9+
*/
10+
// @ts-ignore-line
511
export const client =
6-
(!dev || (SUPABASE_URL && SUPABASE_KEY)) &&
12+
client_enabled &&
713
createClient(SUPABASE_URL, SUPABASE_KEY, {
814
global: { fetch },
915
auth: { persistSession: false }

sites/svelte.dev/src/lib/db/gist.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ const PAGE_SIZE = 90;
88

99
/**
1010
* @param {User} user
11+
* @param {{
12+
* offset: number;
13+
* search: string | null;
14+
* }} opts
1115
*/
1216
export async function list(user, { offset, search }) {
1317
const { data, error } = await client.rpc('gist_list', {
@@ -20,9 +24,11 @@ export async function list(user, { offset, search }) {
2024
if (error) throw new Error(error.message);
2125

2226
// normalize IDs
23-
data.forEach((gist) => {
24-
gist.id = gist.id.replace(/-/g, '');
25-
});
27+
data.forEach(
28+
/** @param {{id:string}} gist */ (gist) => {
29+
gist.id = gist.id.replace(/-/g, '');
30+
}
31+
);
2632

2733
return {
2834
gists: data.slice(0, PAGE_SIZE),

sites/svelte.dev/src/lib/db/session.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { client } from './client.js';
55
/** @typedef {import('./types').User} User */
66

77
/**
8-
* @type {import('flru').flruCache<User>}
8+
* @type {import('flru').flruCache<User | null>}
99
*/
1010
const session_cache = flru(1000);
1111

@@ -39,7 +39,7 @@ export async function create(user) {
3939

4040
/**
4141
* @param {string} sessionid
42-
* @returns {Promise<User>}
42+
* @returns {Promise<User | null>}
4343
*/
4444
export async function read(sessionid) {
4545
if (!sessionid) return null;
@@ -58,7 +58,7 @@ export async function read(sessionid) {
5858
);
5959
}
6060

61-
return session_cache.get(sessionid);
61+
return session_cache.get(sessionid) || null;
6262
}
6363

6464
/** @param {string} sessionid */

sites/svelte.dev/src/lib/server/docs/index.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ export function get_docs_list(docs_data) {
9999
}));
100100
}
101101

102+
/** @param {string} str */
102103
const titled = async (str) =>
103104
removeMarkdown(
104105
escape(await markedTransform(str, { paragraph: (txt) => txt }))
@@ -111,7 +112,10 @@ const titled = async (str) =>
111112
.replace(/<(\/)?(em|b|strong|code)>/g, '')
112113
);
113114

114-
/** @param {string} markdown */
115+
/**
116+
* @param {string} markdown
117+
* @returns {Promise<import('./types').Section[]>}
118+
*/
115119
export async function get_sections(markdown) {
116120
const lines = markdown.split('\n');
117121
const root = /** @type {import('./types').Section} */ ({
@@ -141,7 +145,9 @@ export async function get_sections(markdown) {
141145
};
142146

143147
// Add the new node to the tree
144-
currentNodes[level].sections.push(newNode);
148+
const sections = currentNodes[level].sections;
149+
if (!sections) throw new Error(`Could not find section ${level}`);
150+
sections.push(newNode);
145151

146152
// Prepare for potential children of the new node
147153
currentNodes = currentNodes.slice(0, level + 1);
@@ -152,5 +158,5 @@ export async function get_sections(markdown) {
152158
}
153159
}
154160

155-
return root.sections;
161+
return /** @type {import('./types').Section[]} */ (root.sections);
156162
}

sites/svelte.dev/src/lib/server/examples/index.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export async function get_examples_data(base = CONTENT_BASE_PATHS.EXAMPLES) {
2525
const examples = [];
2626

2727
for (const subdir of await readdir(base)) {
28+
/** @type {import('./types').ExamplesDatum} */
2829
const section = {
2930
title: '', // Initialise with empty
3031
slug: subdir.split('-').slice(1).join('-'),
@@ -51,13 +52,24 @@ export async function get_examples_data(base = CONTENT_BASE_PATHS.EXAMPLES) {
5152
await readFile(`${example_base_dir}/meta.json`, 'utf-8')
5253
).title;
5354

55+
/**
56+
* @type {Array<{
57+
* name: string;
58+
* type: string;
59+
* content: string;
60+
* }>}
61+
*/
5462
const files = [];
5563
for (const file of (await readdir(example_base_dir)).filter(
5664
(file) => !file.endsWith('meta.json')
5765
)) {
66+
const type = file.split('.').at(-1);
67+
if (!type) {
68+
throw new Error(`Could not determine type from ${file}`);
69+
}
5870
files.push({
5971
name: file,
60-
type: file.split('.').at(-1),
72+
type,
6173
content: await readFile(`${example_base_dir}/${file}`, 'utf-8')
6274
});
6375
}

sites/svelte.dev/src/lib/server/examples/types.d.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
export type ExamplesData = {
1+
export interface ExamplesDatum {
22
title: string;
33
slug: string;
44
examples: {
@@ -10,7 +10,9 @@ export type ExamplesData = {
1010
name: string;
1111
}[];
1212
}[];
13-
}[];
13+
}
14+
15+
export type ExamplesData = ExamplesDatum[];
1416

1517
export interface Example {
1618
title: string;

sites/svelte.dev/src/lib/server/tutorial/index.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export async function get_tutorial_data(base = CONTENT_BASE_PATHS.TUTORIAL) {
3030
const tutorials = [];
3131

3232
for (const subdir of await readdir(base)) {
33+
/** @type {import('./types').TutorialDatum} */
3334
const section = {
3435
title: '', // Initialise with empty
3536
slug: subdir.split('-').slice(1).join('-'),
@@ -55,6 +56,12 @@ export async function get_tutorial_data(base = CONTENT_BASE_PATHS.TUTORIAL) {
5556
const { metadata, body } = extractFrontmatter(contents);
5657

5758
// Get the contents of the apps.
59+
/**
60+
* @type {{
61+
* initial: import('./types').CompletionState[];
62+
* complete: import('./types').CompletionState[];
63+
* }}
64+
*/
5865
const completion_states_data = { initial: [], complete: [] };
5966
for (const app_dir of await readdir(tutorial_base_dir)) {
6067
if (!app_dir.startsWith('app-')) continue;
@@ -63,9 +70,13 @@ export async function get_tutorial_data(base = CONTENT_BASE_PATHS.TUTORIAL) {
6370
const app_contents = await readdir(app_dir_path, 'utf-8');
6471

6572
for (const file of app_contents) {
73+
const type = file.split('.').at(-1);
74+
if (!type) {
75+
throw new Error(`Could not determine type from ${file}`);
76+
}
6677
completion_states_data[app_dir === 'app-a' ? 'initial' : 'complete'].push({
6778
name: file,
68-
type: file.split('.').at(-1),
79+
type,
6980
content: await readFile(`${app_dir_path}/${file}`, 'utf-8')
7081
});
7182
}

sites/svelte.dev/src/lib/server/tutorial/types.d.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,23 @@
1-
export type TutorialData = {
1+
export interface TutorialDatum {
22
title: string;
33
slug: string;
44
tutorials: {
55
title: string;
66
slug: string;
77
dir: string;
88
content: string;
9-
initial: { name: string; type: string; content: string }[];
10-
complete: { name: string; type: string; content: string }[];
9+
initial: CompletionState[];
10+
complete: CompletionState[];
1111
}[];
12-
}[];
12+
}
13+
14+
export interface CompletionState {
15+
name: string;
16+
type: string;
17+
content: string;
18+
}
19+
20+
export type TutorialData = TutorialDatum[];
1321

1422
export interface Tutorial {
1523
title: string;

sites/svelte.dev/src/lib/time.js

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,28 @@
1-
// adapted from https://github.com/digplan/time-ago
2-
// https://github.com/digplan/time-ago/blob/master/license.txt
3-
const o = {
4-
second: 1000,
5-
minute: 60 * 1000,
6-
hour: 60 * 1000 * 60,
7-
day: 24 * 60 * 1000 * 60,
8-
week: 7 * 24 * 60 * 1000 * 60,
9-
month: 30 * 24 * 60 * 1000 * 60,
10-
year: 365 * 24 * 60 * 1000 * 60
1+
const formatter = new Intl.RelativeTimeFormat(undefined, {
2+
numeric: 'auto'
3+
});
4+
5+
const DIVISIONS = {
6+
seconds: 60,
7+
minutes: 60,
8+
hours: 24,
9+
days: 7,
10+
weeks: 4.34524,
11+
months: 12,
12+
years: Number.POSITIVE_INFINITY
1113
};
1214

13-
export const ago = (nd, s) => {
14-
var r = Math.round,
15-
dir = ' ago',
16-
pl = function (v, n) {
17-
return s === undefined ? n + ' ' + v + (n > 1 ? 's' : '') + dir : n + v.substring(0, 1);
18-
},
19-
ts = Date.now() - new Date(nd).getTime(),
20-
ii;
21-
if (ts < 0) {
22-
ts *= -1;
23-
dir = ' from now';
24-
}
25-
for (var i in o) {
26-
if (r(ts) < o[i]) return pl(ii || 'm', r(ts / (o[ii] || 1)));
27-
ii = i;
15+
/**
16+
* @param {Date} date
17+
*/
18+
export const ago = (date) => {
19+
let duration = (date.getTime() - new Date().getTime()) / 1000;
20+
21+
for (const [name, amount] of Object.entries(DIVISIONS)) {
22+
if (Math.abs(duration) < amount) {
23+
const format = /** @type {keyof(DIVISIONS)} */ (name);
24+
return formatter.format(Math.round(duration), format);
25+
}
26+
duration /= amount;
2827
}
29-
return pl(i, r(ts / o[i]));
3028
};

sites/svelte.dev/src/lib/utils/events.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1+
/** @param {number} code */
12
export function keyEvent(code) {
3+
/**
4+
* @param {HTMLInputElement} node
5+
* @param {(event: KeyboardEvent) => void} callback
6+
*/
27
return function (node, callback) {
38
node.addEventListener('keydown', handleKeydown);
49

10+
/** @param {KeyboardEvent} event */
511
function handleKeydown(event) {
612
if (event.keyCode === code) {
713
callback.call(this, event);

sites/svelte.dev/src/lib/utils/examples.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
/**
2+
* @param {Array<{
3+
* content: string;
4+
* name: string;
5+
* source: string;
6+
* type: string;
7+
* }>} files
8+
*/
19
export function process_example(files) {
210
return files
311
.map((file) => {
@@ -12,5 +20,7 @@ export function process_example(files) {
1220

1321
if (a.type === 'svelte') return -1;
1422
if (b.type === 'svelte') return 1;
23+
24+
return 0;
1525
});
1626
}

sites/svelte.dev/src/routes/(authed)/apps/+page.server.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ export async function load({ url, parent }) {
99
const { user } = await parent();
1010

1111
if (user) {
12-
const offset = url.searchParams.get('offset') ? parseInt(url.searchParams.get('offset')) : 0;
12+
const offset_param = url.searchParams.get('offset');
13+
const offset = offset_param ? parseInt(offset_param) : 0;
1314
const search = url.searchParams.get('search');
1415

1516
({ gists, next } = await gist.list(user, { offset, search }));

sites/svelte.dev/src/routes/(authed)/repl/+page.js

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,14 @@ export function load({ url }) {
88
const vim = query.get('vim');
99

1010
// redirect to v2 REPL if appropriate
11-
if (/^[^>]?[12]/.test(version)) {
11+
if (version && /^[^>]?[12]/.test(version)) {
1212
throw redirect(302, `https://v2.svelte.dev/repl?${query}`);
1313
}
1414

1515
const id = gist || example || 'hello-world';
1616
// we need to filter out null values
17-
const q = new URLSearchParams(
18-
Object.entries({
19-
version,
20-
vim
21-
}).filter(([, value]) => value !== null)
22-
).toString();
17+
const q = new URLSearchParams();
18+
if (version) q.set('version', version);
19+
if (vim) q.set('vim', vim);
2320
throw redirect(301, `/repl/${id}?${q}`);
2421
}

sites/svelte.dev/src/routes/(authed)/repl/[id]/AppControls.svelte

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ export default app;`
189189
<svelte:window on:keydown={handleKeydown} />
190190

191191
<div class="app-controls">
192-
<input bind:value={name} on:focus={(e) => e.target.select()} use:enter={(e) => e.target.blur()} />
192+
<input bind:value={name} on:focus={(e) => e.target.select()} use:enter={(e) => /** @type {HTMLInputElement} */ (e.target).blur()} />
193193

194194
<div class="buttons">
195195
<button class="icon" on:click={() => (zen_mode = !zen_mode)} title="fullscreen editor">

sites/svelte.dev/src/routes/(authed)/repl/[id]/downloadBlob.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
/**
2+
* @param {Blob} blob
3+
* @param {string} filename
4+
*/
15
export default (blob, filename) => {
26
const url = URL.createObjectURL(blob);
37
const link = document.createElement('a');

sites/svelte.dev/src/routes/(authed)/repl/api/[id].json/+server.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,8 @@ export async function GET({ params }) {
4646
.map((example) => example.slug)
4747
);
4848

49-
if (examples.has(params.id)) {
50-
const example = get_example(examples_data, params.id);
51-
49+
const example = get_example(examples_data, params.id);
50+
if (example) {
5251
return json({
5352
id: params.id,
5453
name: example.title,

sites/svelte.dev/src/routes/auth/callback/+server.js

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,13 @@ import { oauth, client_id, client_secret } from '../_config.js';
66
export async function GET({ url }) {
77
try {
88
// Trade "code" for "access_token"
9-
const r1 = await fetch(
10-
`${oauth}/access_token?` +
11-
new URLSearchParams({
12-
code: url.searchParams.get('code'),
13-
client_id,
14-
client_secret
15-
}).toString()
16-
);
9+
const code = url.searchParams.get('code') || undefined;
10+
const params = new URLSearchParams({
11+
client_id,
12+
client_secret
13+
});
14+
if (code) params.set('code', code);
15+
const r1 = await fetch(`${oauth}/access_token?` + params.toString());
1716
const access_token = new URLSearchParams(await r1.text()).get('access_token');
1817

1918
// Now fetch User details

0 commit comments

Comments
 (0)