chore: move everything to esm

This commit is contained in:
alina 🌸 2024-08-12 09:19:45 +03:00
parent 407910c2be
commit e429dbe40a
Signed by: teidesu
SSH key fingerprint: SHA256:uNeCpw6aTSU4aIObXLvHfLkDa82HWH9EiOj9AXOIRpI
22 changed files with 133 additions and 120 deletions

View file

@ -167,6 +167,7 @@ module.exports = {
'import/no-relative-packages': 'error',
'import/no-mutable-exports': 'error',
'import/no-default-export': 'error',
'import/no-unresolved': 'off',
'no-console': ['error', { allow: ['warn', 'error'] }],
},
ignorePatterns: [
@ -281,17 +282,10 @@ module.exports = {
{
files: ['packages/bun/**', 'packages/deno/**'],
rules: {
'import/no-unresolved': 'off',
'no-restricted-imports': 'off',
'import/no-relative-packages': 'off', // common-internals is symlinked from node
}
},
{
files: ['e2e/deno/**'],
rules: {
'import/no-unresolved': 'off',
}
},
],
settings: {
'import/resolver': {

View file

@ -1,7 +1,7 @@
import { Plugin } from 'vite'
import { fileURLToPath } from 'url'
const setupFile = fileURLToPath(new URL('./test-setup.mts', import.meta.url))
const setupFile = fileURLToPath(new URL('./test-setup.ts', import.meta.url))
export function testSetup(params?: { additionalCode?: string }): Plugin {
const { additionalCode = '' } = params || {}

View file

@ -2,7 +2,7 @@
import { mergeConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import baseConfig from './vite.mjs'
import baseConfig from './vite.js'
import { fixupCjs } from './vite-utils/fixup-cjs'
export default mergeConfig(baseConfig, {

View file

@ -20,7 +20,7 @@ export default defineConfig({
]
},
setupFiles: [
'./.config/vite-utils/test-setup.mts'
'./.config/vite-utils/test-setup.ts'
]
},
define: {

View file

@ -52,7 +52,7 @@ jobs:
with:
bun-version: '1.1.4'
- name: 'Build tests'
run: pnpm exec vite build -c .config/vite.bun.mts
run: pnpm exec vite build -c .config/vite.bun.ts
- name: 'Run tests'
run: cd dist/tests && bun test
@ -65,7 +65,7 @@ jobs:
with:
deno-version: '1.43.1'
- name: 'Build tests'
run: pnpm exec vite build -c .config/vite.deno.mts
run: pnpm exec vite build -c .config/vite.deno.ts
- name: 'Run tests'
run: cd dist/tests && deno test -A --unstable-ffi

View file

@ -1,5 +1,5 @@
/* eslint-disable no-console */
const { execSync } = require('child_process')
import { execSync } from 'child_process'
function getDockerContainerIp(name) {
const containerId = execSync(`docker compose ps -q ${name}`).toString().trim()
@ -41,27 +41,25 @@ async function createBucket(name) {
}
}
(async () => {
for (const bucket of ['modules', 'docs', 'publishing', 'npm']) {
const ok = await createBucket(bucket)
console.log(`[i] Created bucket ${bucket}: ${ok}`)
}
for (const bucket of ['modules', 'docs', 'publishing', 'npm']) {
const ok = await createBucket(bucket)
console.log(`[i] Created bucket ${bucket}: ${ok}`)
}
// create @mtcute scope if it doesn't exist
const resp = await fetch(`${API_URL}api/scopes`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: 'token=token',
},
body: JSON.stringify({ scope: 'mtcute' }),
})
// create @mtcute scope if it doesn't exist
const resp = await fetch(`${API_URL}api/scopes`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: 'token=token',
},
body: JSON.stringify({ scope: 'mtcute' }),
})
if (resp.status !== 200 && resp.status !== 409) {
throw new Error(`Failed to create scope: ${resp.statusText} ${await resp.text()}`)
}
if (resp.status !== 200 && resp.status !== 409) {
throw new Error(`Failed to create scope: ${resp.statusText} ${await resp.text()}`)
}
if (resp.status === 200) {
console.log('[i] Created scope mtcute')
}
})()
if (resp.status === 200) {
console.log('[i] Created scope mtcute')
}

View file

@ -5,6 +5,7 @@
"description": "Type-safe library for MTProto (Telegram API) for browser and NodeJS",
"license": "MIT",
"author": "alina sireneva <alina@tei.su>",
"type": "module",
"keywords": [
"telegram",
"telegram-api",
@ -24,16 +25,16 @@
"packages/*"
],
"scripts": {
"postinstall": "node scripts/validate-deps-versions.mjs && node scripts/remove-jsr-sourcefiles.mjs",
"test": "pnpm run -r test && vitest --config .config/vite.mts run",
"test:dev": "vitest --config .config/vite.mts watch",
"test:ui": "vitest --config .config/vite.mts --ui",
"test:coverage": "vitest --config .config/vite.mts run --coverage",
"test:ci": "vitest --config .config/vite.mts run --coverage.enabled --coverage.reporter=json",
"test:browser": "vitest --config .config/vite.browser.mts run",
"test:browser:dev": "vitest --config .config/vite.browser.mts watch",
"postinstall": "node scripts/validate-deps-versions.js && node scripts/remove-jsr-sourcefiles.js",
"test": "pnpm run -r test && vitest --config .config/vite.ts run",
"test:dev": "vitest --config .config/vite.ts watch",
"test:ui": "vitest --config .config/vite.ts --ui",
"test:coverage": "vitest --config .config/vite.ts run --coverage",
"test:ci": "vitest --config .config/vite.ts run --coverage.enabled --coverage.reporter=json",
"test:browser": "vitest --config .config/vite.browser.ts run",
"test:browser:dev": "vitest --config .config/vite.browser.ts watch",
"lint": "eslint .",
"lint:ci": "NODE_OPTIONS=\\\"--max_old_space_size=8192\\\" eslint --config .config/eslint.ci.js .",
"lint:ci": "NODE_OPTIONS=\\\"--max_old_space_size=8192\\\" eslint --config .config/eslint.ci.cjs .",
"lint:tsc": "rimraf packages/**/dist packages/**/*.tsbuildinfo && pnpm -r --workspace-concurrency=4 exec tsc --build",
"lint:tsc:ci": "pnpm -r exec tsc --build",
"lint:dpdm": "dpdm -T --no-warning --no-tree --exit-code circular:1 packages/*",

View file

@ -4,7 +4,7 @@ const fs = require('fs')
const cp = require('child_process')
const { Readable } = require('stream')
const git = require('../../scripts/git-utils')
let git
const GITHUB_TOKEN = process.env.GITHUB_TOKEN
let SKIP_PREBUILT = process.env.BUILD_FOR_DOCS === '1'
@ -151,6 +151,8 @@ async function extractArtifacts(artifacts) {
module.exports = ({ fs, glob, path, packageDir, outDir }) => ({
async final() {
// eslint-disable-next-line import/no-relative-packages
git = await import('../../scripts/git-utils.js')
const libDir = path.join(packageDir, 'lib')
if (!SKIP_PREBUILT) {

View file

@ -1,12 +1,15 @@
/* eslint-disable no-inner-declarations */
const cp = require('child_process')
const path = require('path')
const fs = require('fs')
const glob = require('glob')
const ts = require('typescript')
const stc = require('@teidesu/slow-types-compiler')
// @ts-ignore
const rootPackageJson = require('../package.json')
import * as cp from 'child_process'
import * as fs from 'fs'
import * as glob from 'glob'
import { createRequire } from 'module'
import * as path from 'path'
import ts from 'typescript'
import * as stc from '@teidesu/slow-types-compiler'
const __dirname = path.dirname(new URL(import.meta.url).pathname)
const rootPackageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8'))
if (process.argv.length < 3) {
console.log('Usage: build-package.js <package name>')
@ -30,6 +33,9 @@ function transformFile(file, transform) {
if (res != null) fs.writeFileSync(file, res)
}
// todo make them esm
const require = createRequire(import.meta.url)
const buildConfig = {
buildTs: true,
buildCjs: true,
@ -617,12 +623,12 @@ if (!IS_JSR) {
fs.writeFileSync(path.join(outDir, '.npmignore'), '*.tsbuildinfo\n')
}
Promise.resolve(buildConfig.final()).then(() => {
if (IS_JSR && !process.env.CI) {
console.log('[i] Trying to publish with --dry-run')
exec('deno publish --dry-run --allow-dirty --quiet', { cwd: outDir })
console.log('[v] All good!')
} else {
console.log('[v] Done!')
}
})
await buildConfig.final()
if (IS_JSR && !process.env.CI) {
console.log('[i] Trying to publish with --dry-run')
exec('deno publish --dry-run --allow-dirty --quiet', { cwd: outDir })
console.log('[v] All good!')
} else {
console.log('[v] Done!')
}

View file

@ -1,14 +1,17 @@
const fs = require('fs')
const path = require('path')
const semver = require('semver')
import { appendFileSync, readdirSync, readFileSync, writeFileSync } from 'fs'
import { EOL } from 'os'
import { dirname, join } from 'path'
import { inc, rcompare } from 'semver'
import { fileURLToPath } from 'url'
const __dirname = dirname(new URL(import.meta.url).pathname)
function collectPackageJsons() {
return fs
.readdirSync(path.join(__dirname, '../packages'))
return readdirSync(join(__dirname, '../packages'))
.filter((s) => !s.startsWith('.'))
.map((name) => {
try {
return JSON.parse(fs.readFileSync(path.join(__dirname, '../packages', name, 'package.json'), 'utf-8'))
return JSON.parse(readFileSync(join(__dirname, '../packages', name, 'package.json'), 'utf-8'))
} catch (e) {
if (e.code !== 'ENOENT') throw e
@ -23,9 +26,9 @@ function bumpVersions(packages, kind) {
const maxVersion = pkgJsons
.filter((it) => it.name !== '@mtcute/tl')
.map((it) => it.version)
.sort(semver.rcompare)[0]
.sort(rcompare)[0]
const nextVersion = semver.inc(maxVersion, kind)
const nextVersion = inc(maxVersion, kind)
console.log('[i] Bumping versions to %s', nextVersion)
for (const pkg of packages) {
@ -38,20 +41,20 @@ function bumpVersions(packages, kind) {
}
pkgJson.version = nextVersion
fs.writeFileSync(
path.join(__dirname, '../packages', pkg, 'package.json'),
writeFileSync(
join(__dirname, '../packages', pkg, 'package.json'),
JSON.stringify(pkgJson, null, 4) + '\n',
)
}
const rootPkgJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8'))
const rootPkgJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
rootPkgJson.version = nextVersion
fs.writeFileSync(path.join(__dirname, '../package.json'), JSON.stringify(rootPkgJson, null, 4) + '\n')
writeFileSync(join(__dirname, '../package.json'), JSON.stringify(rootPkgJson, null, 4) + '\n')
return nextVersion
}
if (require.main === module) {
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const kind = process.argv[2]
const packages = process.argv[3]
@ -75,8 +78,8 @@ if (require.main === module) {
const ver = bumpVersions(packagesList, kind)
if (process.env.GITHUB_OUTPUT) {
fs.appendFileSync(process.env.GITHUB_OUTPUT, `version=${ver}${require('os').EOL}`)
appendFileSync(process.env.GITHUB_OUTPUT, `version=${ver}${EOL}`)
}
}
module.exports = { bumpVersions }
export { bumpVersions }

View file

@ -1,22 +1,27 @@
const cp = require('child_process')
const fs = require('fs')
const path = require('path')
const { listPackages } = require('./publish')
const { getLatestTag, findChangedFilesSince } = require('./git-utils')
import { execSync } from 'child_process'
import { appendFileSync, existsSync } from 'fs'
import { EOL } from 'os'
import { dirname, join } from 'path'
import { fileURLToPath } from 'url'
import { findChangedFilesSince, getLatestTag } from './git-utils.js'
import { listPackages } from './publish.js'
getTsconfigFiles.cache = {}
const __dirname = dirname(new URL(import.meta.url).pathname)
function getTsconfigFiles(pkg) {
if (!fs.existsSync(path.join(__dirname, `../packages/${pkg}/tsconfig.json`))) {
if (!existsSync(join(__dirname, `../packages/${pkg}/tsconfig.json`))) {
throw new Error(`[!] ${pkg} does not have a tsconfig.json`)
}
if (pkg in getTsconfigFiles.cache) return getTsconfigFiles.cache[pkg]
console.log('[i] Getting tsconfig files for %s', pkg)
const res = cp.execSync('pnpm exec tsc --showConfig', {
const res = execSync('pnpm exec tsc --showConfig', {
encoding: 'utf8',
stdio: 'pipe',
cwd: path.join(__dirname, `../packages/${pkg}`),
cwd: join(__dirname, `../packages/${pkg}`),
})
const json = JSON.parse(res)
@ -68,9 +73,9 @@ function findChangedPackagesSince(tag, until) {
return Array.from(changedPackages)
}
module.exports = { findChangedPackagesSince, getLatestTag }
export { findChangedPackagesSince, getLatestTag }
if (require.main === module && process.env.CI && process.env.GITHUB_OUTPUT) {
if (process.argv[1] === fileURLToPath(import.meta.url) && process.env.CI && process.env.GITHUB_OUTPUT) {
const kind = process.argv[2]
const input = process.argv[3]
@ -102,5 +107,5 @@ if (require.main === module && process.env.CI && process.env.GITHUB_OUTPUT) {
}
console.log('[i] Will publish:', res)
fs.appendFileSync(process.env.GITHUB_OUTPUT, `modified=${res.join(',')}${require('os').EOL}`)
appendFileSync(process.env.GITHUB_OUTPUT, `modified=${res.join(',')}${EOL}`)
}

View file

@ -1,5 +1,5 @@
// node scripts/gen-deps-graph.mjs | dot -Tsvg > deps.svg
import { getPackageJsons } from './utils.mjs'
// node scripts/gen-deps-graph.js | dot -Tsvg > deps.svg
import { getPackageJsons } from './utils.js'
const packageJsons = await getPackageJsons()

View file

@ -1,5 +1,9 @@
const fs = require('fs')
const { getLatestTag, getCommitsSince, parseConventionalCommit, findChangedFilesSince } = require('./git-utils')
import { randomUUID } from 'crypto'
import { appendFileSync } from 'fs'
import { EOL } from 'os'
import { fileURLToPath } from 'url'
import { findChangedFilesSince, getCommitsSince, getLatestTag, parseConventionalCommit } from './git-utils.js'
function generateChangelog(onlyPackages) {
const byPackage = {}
@ -52,7 +56,7 @@ function generateChangelog(onlyPackages) {
return ret
}
if (require.main === module) {
if (process.argv[1] === fileURLToPath(import.meta.url)) {
let onlyPackages = null
if (process.argv[2]) {
@ -62,8 +66,8 @@ if (require.main === module) {
const res = generateChangelog(onlyPackages)
if (process.env.CI && process.env.GITHUB_OUTPUT) {
const delim = `---${require('crypto').randomUUID()}---${require('os').EOL}`
fs.appendFileSync(process.env.GITHUB_OUTPUT, `changelog<<${delim}${res}${delim}`)
const delim = `---${randomUUID()}---${EOL}`
appendFileSync(process.env.GITHUB_OUTPUT, `changelog<<${delim}${res}${delim}`)
} else {
console.log(res)
}

View file

@ -1,14 +1,14 @@
const cp = require('child_process')
import { execSync } from 'child_process'
function getLatestTag() {
try {
const res = cp.execSync('git describe --abbrev=0 --tags', { encoding: 'utf8', stdio: 'pipe' }).trim()
const res = execSync('git describe --abbrev=0 --tags', { encoding: 'utf8', stdio: 'pipe' }).trim()
return res
} catch (e) {
if (e.stderr.match(/^fatal: (No names found|No tags can describe)/i)) {
// no tags found, let's just return the first commit
return cp.execSync('git rev-list --max-parents=0 HEAD', { encoding: 'utf8' }).trim()
return execSync('git rev-list --max-parents=0 HEAD', { encoding: 'utf8' }).trim()
}
throw e
@ -16,14 +16,13 @@ function getLatestTag() {
}
function findChangedFilesSince(tag, until = 'HEAD') {
return cp.execSync(`git diff --name-only ${tag} ${until}`, { encoding: 'utf8', stdio: 'pipe' }).trim().split('\n')
return execSync(`git diff --name-only ${tag} ${until}`, { encoding: 'utf8', stdio: 'pipe' }).trim().split('\n')
}
function getCommitsSince(tag, until = 'HEAD') {
const delim = `---${Math.random().toString(36).slice(2)}---`
const lines = cp
.execSync(`git log --pretty="format:%H %s%n%b%n${delim}" ${tag}..${until}`, { encoding: 'utf8', stdio: 'pipe' })
const lines = execSync(`git log --pretty="format:%H %s%n%b%n${delim}" ${tag}..${until}`, { encoding: 'utf8', stdio: 'pipe' })
.trim()
.split('\n')
@ -50,11 +49,11 @@ function getCommitsSince(tag, until = 'HEAD') {
}
function getCurrentCommit() {
return cp.execSync('git rev-parse HEAD', { encoding: 'utf8', stdio: 'pipe' }).trim()
return execSync('git rev-parse HEAD', { encoding: 'utf8', stdio: 'pipe' }).trim()
}
function getCurrentBranch() {
return cp.execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8', stdio: 'pipe' }).trim()
return execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8', stdio: 'pipe' }).trim()
}
function parseConventionalCommit(msg) {
@ -67,11 +66,11 @@ function parseConventionalCommit(msg) {
return { type, scope, breaking: Boolean(breaking), subject }
}
module.exports = {
getLatestTag,
export {
findChangedFilesSince,
getCommitsSince,
parseConventionalCommit,
getCurrentCommit,
getCurrentBranch,
getCurrentCommit,
getLatestTag,
parseConventionalCommit,
}

View file

@ -1,12 +1,18 @@
const fs = require('fs')
const path = require('path')
const cp = require('child_process')
const stc = require('@teidesu/slow-types-compiler')
import * as cp from 'child_process'
import * as fs from 'fs'
import { createRequire } from 'module'
import * as path from 'path'
import { fileURLToPath } from 'url'
import * as stc from '@teidesu/slow-types-compiler'
const IS_JSR = process.env.JSR === '1'
const MAIN_REGISTRY = IS_JSR ? 'https://jsr.io/' : 'https://registry.npmjs.org'
let REGISTRY = process.env.REGISTRY || MAIN_REGISTRY
exports.REGISTRY = REGISTRY
const EXPORTED_REGISTRY = REGISTRY
const __dirname = path.dirname(new URL(import.meta.url).pathname)
const require = createRequire(import.meta.url)
if (!REGISTRY.endsWith('/')) REGISTRY += '/'
if (process.env.E2E && IS_JSR) {
@ -148,8 +154,6 @@ function listPackages(all = false) {
return packages
}
exports.listPackages = listPackages
async function main(arg = process.argv[2]) {
if (!arg) {
console.log('Usage: publish.js <package name | all | updated>')
@ -248,11 +252,8 @@ async function main(arg = process.argv[2]) {
process.exit(0) // idk why but it sometimes hangs indefinitely
}
exports.main = main
export { listPackages, main, EXPORTED_REGISTRY as REGISTRY }
if (require.main === module) {
main().catch((e) => {
console.error(e)
process.exit(1)
})
if (process.argv[1] === fileURLToPath(import.meta.url)) {
await main()
}

View file

@ -1,7 +1,7 @@
import semver from 'semver'
import { fileURLToPath } from 'url'
import { getPackageJsons } from './utils.mjs'
import { getPackageJsons } from './utils.js'
export async function validateDepsVersions() {
const packageJsons = await getPackageJsons(true)