Skip to content

Commit

Permalink
chore: 合并vercel adapter到主工程
Browse files Browse the repository at this point in the history
  • Loading branch information
TBXark committed Aug 28, 2024
1 parent eed134a commit 65bdea5
Show file tree
Hide file tree
Showing 13 changed files with 747 additions and 81 deletions.
7 changes: 3 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,11 @@ out

.idea
.vscode
/wrangler.toml
/wrangler-test.toml
.vercel
.wrangler
package-lock.json
/config.json
/wrangler.toml
/wrangler-test.toml
/plugins/interpolate.js
config.json
/dist/index.cjs
/dist/index.d.ts
10 changes: 7 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,18 @@
"dist"
],
"scripts": {
"lint": "eslint --fix *.js *.ts *.json src adapter",
"lint": "eslint --fix *.js *.ts src adapter plugins scripts",
"build": "vite build",
"build:local": "BUILD_MODE=local vite build",
"build:docker": "npm run build:local && cd dist && docker build -t chatgpt-telegram-workers:latest .",
"build:vercel": "BUILD_MODE=vercel vite build",
"deploy:dist": "wrangler deploy",
"deploy:build": "npm run build && wrangler deploy",
"deploy:vercel": "vercel deploy --prod",
"start:dist": "node dist/index.js",
"start:local": "CONFIG_PATH=./config.json TOML_PATH=./wrangler.toml tsx src/adapter/local.ts",
"start:debug": "wrangler dev --local"
"start:local": "CONFIG_PATH=./config.json TOML_PATH=./wrangler.toml tsx src/adapter/local/index.ts",
"start:debug": "wrangler dev --local",
"prepare:vercel": "tsx ./scripts/plugins/vercel/setenv.ts"
},
"dependencies": {
"cloudflare-worker-adapter": "^1.3.0"
Expand All @@ -36,6 +39,7 @@
"@antfu/eslint-config": "^2.27.3",
"@rollup/plugin-node-resolve": "^15.2.3",
"@types/node": "^22.5.1",
"@vercel/node": "^3.2.9",
"eslint": "^9.8.0",
"eslint-plugin-format": "^0.1.2",
"rollup-plugin-cleanup": "^3.2.1",
Expand Down
26 changes: 13 additions & 13 deletions plugins/dicten.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
{
"url": "https://api.dictionaryapi.dev/api/v2/entries/en/{{DATA}}",
"method": "GET",
"response": {
"content": {
"input_type": "json",
"output_type": "html",
"output": "{{#each word in .}}\n<b>{{word.word}}</b>{{#if word.phonetic}}<i>{{word.phonetic}}</i>{{/if}}\n{{#each:word meanings in word.meanings}}\n <b>+ {{meanings.partOfSpeech}}</b>\n {{#each:meanings definitions in meanings.definitions}}\n <i>{{definitions.definition}}</i>\n {{/each:meanings}}\n{{/each:word}}\n{{/each}}\n"
},
"error": {
"input_type": "json",
"output_type": "text",
"output": "Error: {{message}}"
"url": "https://api.dictionaryapi.dev/api/v2/entries/en/{{DATA}}",
"method": "GET",
"response": {
"content": {
"input_type": "json",
"output_type": "html",
"output": "{{#each word in .}}\n<b>{{word.word}}</b>{{#if word.phonetic}}<i>{{word.phonetic}}</i>{{/if}}\n{{#each:word meanings in word.meanings}}\n <b>+ {{meanings.partOfSpeech}}</b>\n {{#each:meanings definitions in meanings.definitions}}\n <i>{{definitions.definition}}</i>\n {{/each:meanings}}\n{{/each:word}}\n{{/each}}\n"
},
"error": {
"input_type": "json",
"output_type": "text",
"output": "Error: {{message}}"
}
}
}
}
44 changes: 22 additions & 22 deletions plugins/dns.json
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
{
"url": "https://cloudflare-dns.com/dns-query",
"method": "GET",
"headers": {
"accept": "application/dns-json"
},
"input": {
"type": "space-separated"
},
"query": {
"type": "{{DATA[0]}}",
"name": "{{DATA[1]}}"
},
"response": {
"content": {
"input_type": "json",
"output_type": "html",
"output": "\n<b>DNS query: {{Question[0].name}}</b>\n<code>Status: {{#if TC}}TC,{{/if}}{{#if RD}}RD,{{/if}}{{#if RA}}RA,{{/if}}{{#if AD}}AD,{{/if}}{{#if CD}}CD,{{/if}}{{Status}}</code>\n\n<b>Answer</b>{{#each answer in Answer}}\n<code>{{answer.name}}, {{answer.type}}, (TTL: {{answer.TTL}}),{{answer.data}}</code>{{/each}}\n"
"url": "https://cloudflare-dns.com/dns-query",
"method": "GET",
"headers": {
"accept": "application/dns-json"
},
"error": {
"input_type": "json",
"output_type": "text",
"output": "Error: {{error}}"
"input": {
"type": "space-separated"
},
"query": {
"type": "{{DATA[0]}}",
"name": "{{DATA[1]}}"
},
"response": {
"content": {
"input_type": "json",
"output_type": "html",
"output": "\n<b>DNS query: {{Question[0].name}}</b>\n<code>Status: {{#if TC}}TC,{{/if}}{{#if RD}}RD,{{/if}}{{#if RA}}RA,{{/if}}{{#if AD}}AD,{{/if}}{{#if CD}}CD,{{/if}}{{Status}}</code>\n\n<b>Answer</b>{{#each answer in Answer}}\n<code>{{answer.name}}, {{answer.type}}, (TTL: {{answer.TTL}}),{{answer.data}}</code>{{/each}}\n"
},
"error": {
"input_type": "json",
"output_type": "text",
"output": "Error: {{error}}"
}
}
}
}
File renamed without changes.
18 changes: 18 additions & 0 deletions scripts/plugins/vercel/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import fs from 'node:fs/promises';
import { execSync } from 'node:child_process';
import { parse } from 'toml';

export function createVercelPlugin(vercelPath: string, tomlPath: string) {
return {
name: 'vercel',
async closeBundle() {
const { vars } = parse(await fs.readFile(tomlPath, 'utf-8'));
for (const [key, value] of Object.entries(vars)) {
execSync(`${vercelPath} env add ${key} production --force`, {
input: `${value}`,
encoding: 'utf-8',
});
}
},
};
}
10 changes: 10 additions & 0 deletions scripts/plugins/vercel/setenv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * as process from 'node:process';
import { createVercelPlugin } from './index';

const {
VERCEL_PATH = 'vercel',
TOML_PATH = 'wrangler.toml',
} = process.env;

const plugin = createVercelPlugin(VERCEL_PATH, TOML_PATH);
plugin.closeBundle().catch(console.error);
File renamed without changes.
10 changes: 5 additions & 5 deletions src/adapter/local.ts → src/adapter/local/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { defaultRequestBuilder, initEnv, startServerV2 } from 'cloudflare-worker
import type { GetUpdatesResponse } from 'telegram-bot-api-types';
import { installFetchProxy } from 'cloudflare-worker-adapter/proxy';
import { createCache } from 'cloudflare-worker-adapter/cache';
import { ENV } from '../config/env';
import type { TelegramBotAPI } from '../telegram/api';
import { createTelegramBotAPI } from '../telegram/api';
import { handleUpdate } from '../telegram/handler';
import { createRouter } from '../route';
import { ENV } from '../../config/env';
import type { TelegramBotAPI } from '../../telegram/api';
import { createTelegramBotAPI } from '../../telegram/api';
import { handleUpdate } from '../../telegram/handler';
import { createRouter } from '../../route';

const {
CONFIG_PATH = '/app/config.json',
Expand Down
66 changes: 66 additions & 0 deletions src/adapter/vercel/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import * as process from 'node:process';
import { RedisCache } from 'cloudflare-worker-adapter/cache/redis';
import type { VercelRequest, VercelResponse } from '@vercel/node';
import { ENV } from '../../config/env';
import { createRouter } from '../../route';

export default async function (request: VercelRequest, response: VercelResponse) {
let redis: RedisCache | null = null;
try {
const {
VERCEL_DOMAIN,
REDIS_URL,
} = process.env;
if (!VERCEL_DOMAIN) {
response.status(500).send('VERCEL_DOMAIN is required');
return;
}
if (!REDIS_URL) {
response.status(500).send('REDIS_URL is required');
return;
}
const cache = RedisCache.createFromUri(REDIS_URL);
// edge function 使用 redis 作为数据库容易出现连接数过多的问题,此处仅作为演示,请自行实现 `Cache` 接口
redis = cache;
ENV.merge({
...process.env,
DATABASE: cache,
});
const router = createRouter();
let body: BodyInit | null = null;
if (request.body) {
body = JSON.stringify(request.body);
}
const newReq = new Request(VERCEL_DOMAIN + request.url, {
method: request.method,
headers: Object.entries(request.headers).reduce((acc, [key, value]) => {
if (value === undefined) {
return acc;
}
if (Array.isArray(value)) {
for (const v of value) {
acc.append(key, v);
}
return acc;
}
acc.set(key, value);
return acc;
}, new Headers()),
body,
});
const res = await router.fetch(newReq);
if (redis) {
await redis.close().catch(console.error);
redis = null;
}
response.status(res.status).send(await res.text());
} catch (e) {
if (redis) {
await redis.close();
}
response.status(500).send(JSON.stringify({
message: (e as Error).message,
stack: (e as Error).stack,
}, null, 2));
}
}
8 changes: 8 additions & 0 deletions vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"builds": [
{ "src": "dist/**", "use": "@vercel/node" }
],
"routes": [
{ "src": "/(.*)", "dest": "/dist" }
]
}
43 changes: 27 additions & 16 deletions vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import * as path from 'node:path';
import type { Plugin } from 'vite';
import type { LibraryFormats, Plugin } from 'vite';
import { defineConfig } from 'vite';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import cleanup from 'rollup-plugin-cleanup';
import checker from 'vite-plugin-checker';
import nodeExternals from 'rollup-plugin-node-externals';
import dts from 'vite-plugin-dts';
import { createVersionPlugin, versionDefine } from './src/adapter/version';
import { createDockerPlugin } from './src/adapter/docker';
import { createVersionPlugin, versionDefine } from './scripts/plugins/version';
import { createDockerPlugin } from './scripts/plugins/docker';
import { createVercelPlugin } from './scripts/plugins/vercel';

const { BUILD_MODE } = process.env;

const plugins: Plugin[] = [
nodeResolve({
preferBuiltins: true,
Expand All @@ -25,26 +25,37 @@ const plugins: Plugin[] = [
nodeExternals(),
];

const buildLocalMode = BUILD_MODE === 'local';
const entry = path.resolve(__dirname, buildLocalMode ? 'src/adapter/local.ts' : 'src/index.ts');

if (buildLocalMode) {
plugins.push(createDockerPlugin('dist'));
} else {
plugins.push(createVersionPlugin('dist'));
plugins.push(dts({
rollupTypes: true,
}));
let entry: string;
let formats: LibraryFormats[] = ['es'];
switch (BUILD_MODE) {
case 'local':
entry = 'src/adapter/local/index.ts';
plugins.push(createDockerPlugin('dist'));
break;
case 'vercel':
entry = 'src/adapter/vercel/index.ts';
break;
case 'pack':
entry = 'src/index.ts';
formats = ['es', 'cjs'];
plugins.push(dts({
rollupTypes: true,
}));
break;
default:
entry = 'src/index.ts';
plugins.push(createVersionPlugin('dist'));
break;
}

export default defineConfig({
plugins,
build: {
target: 'esnext',
lib: {
entry,
entry: path.resolve(__dirname, entry),
fileName: 'index',
formats: buildLocalMode ? ['es'] : ['es', 'cjs'],
formats,
},
minify: false,
},
Expand Down
Loading

0 comments on commit 65bdea5

Please sign in to comment.