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

feat: Custom types package based on @types/chrome #1332

Draft
wants to merge 2 commits into
base: 0.20.0-breaking-changes
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ pnpm-lock.yaml linguist-generated
package-lock.json linguist-generated
bun.lockb linguist-generated
yarn.lock linguist-generated
packages/browser-types/npm/gen/** linguist-generated
6 changes: 5 additions & 1 deletion docs/guide/resources/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,11 @@ function getMessageSenderUrl(sender: browser.runtime.MessageSender): string { //
}
```

`@types/chrome` are more up-to-date, contain less bugs, and don't have any auto-generated names. So even if you continue to use the polyfill, you will need to update your types to use these types.
`@types/chrome` are more up-to-date and contain less bugs, but not all types do not have the same names. You will have to find the equivalent types in `@types/chrome` that you were using before.

:::warning
Even if you continue to use the polyfill, you will need to update your types to use `@types/chrome`.
:::

### `public/` and `modules/` Directories Moved

Expand Down
100 changes: 100 additions & 0 deletions packages/browser-types/generate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { downloadTemplate } from 'giget';
import fs from 'fs-extra';
import { dirname, join } from 'node:path';
import { execSync } from 'node:child_process';

const generatedDir = 'npm/gen';
const templatesDir = 'templates';
const joinGenerated = (...path: string[]) => join(generatedDir, ...path);
const joinTemplate = (...path: string[]) => join(templatesDir, ...path);

// Clone the code

await fs.ensureDir(generatedDir);
await fs.emptyDir(generatedDir);

console.log('Fetching latest version details...');
const chromeMeta = JSON.parse(
execSync('npm view @types/chrome --json', { encoding: 'utf8' }),
);

console.log('Downloading latest files from @types/chrome');
const files = await downloadFolder(
'DefinitelyTyped/DefinitelyTyped',
'types/chrome',
);
console.log(
'Downloaded:',
files.map((file) => file.path),
);

// Update code

const pkgJson = await fs.readJson(`${templatesDir}/package.json`);
pkgJson.version = chromeMeta.version;
pkgJson.dependencies = chromeMeta.dependencies;

// Write output

await fs.copyFile(joinTemplate('README.md'), joinGenerated('README.md'));
await fs.writeJson(joinGenerated('package.json'), pkgJson, { spaces: 2 });
for (const file of files) {
const path = file.path.replace('types/chrome', generatedDir);
await fs.ensureDir(dirname(path));
await fs.writeFile(
path,
file.text
.replaceAll('chrome: typeof chrome', 'browser: typeof browser')
.replaceAll('declare namespace chrome', 'declare namespace browser')
.replaceAll('chrome.', 'browser.'),
'utf8',
);
}

///
/// UTILS
///

async function downloadFolder(repo: string, path: string) {
const res: Array<{ path: string; text: string }> = [];
const queue = [path];

while (queue.length > 0) {
const folder = queue.shift()!;
console.log('Loading folder:', path);
const files = await githubFetch(`/repos/${repo}/contents/${folder}`);
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.type === 'dir') {
queue.push(file.path);
} else if (file.type === 'file' && file.name.endsWith('.d.ts')) {
console.log('Downloading:', file.path);
const text = await githubFetch(file.download_url, 'text');
res.push({ path: file.path, text });
}
}
}

return res;
}

async function githubFetch(
path: string,
method: 'json' | 'text' = 'json',
): Promise<any> {
const token = process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN;
const url = new URL(path, 'https://api.github.com');
const response = await fetch(url.href, {
headers: {
...(token && { Authorization: `Bearer ${token}` }),
Accept: 'application/vnd.github.v3+json',
},
});

if (!response.ok) {
console.log(await response.text());
throw new Error(`HTTP error! status: ${response.status}`);
}

return await response[method]();
}
1 change: 1 addition & 0 deletions packages/browser-types/npm/gen/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading