run_app.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // 导入所需模块
  2. import { Hono } from 'hono'
  3. import { APIClient } from '@d8d-appcontainer/api'
  4. import debug from "debug"
  5. import { cors } from 'hono/cors'
  6. import { Server } from "socket.io"
  7. import httpServer from './app.tsx'
  8. import { setupSocketIO } from './routes_socketio.ts'
  9. // 初始化debug实例
  10. const log = {
  11. app: debug('app:server'),
  12. auth: debug('auth:server'),
  13. api: debug('api:server'),
  14. debug: debug('debug:server')
  15. }
  16. // 启用所有日志
  17. Object.values(log).forEach(logger => logger.enabled = true)
  18. // 初始化 API Client
  19. const getApiClient = async (workspaceKey: string, serverUrl?: string) => {
  20. try {
  21. log.api('正在初始化API Client实例')
  22. const apiClient = await APIClient.getInstance({
  23. scope: 'user',
  24. config: {
  25. serverUrl: serverUrl || Deno.env.get('SERVER_URL') || 'https://app-server.d8d.fun',
  26. workspaceKey: workspaceKey,
  27. type: 'http',
  28. }
  29. })
  30. log.api('API Client初始化成功')
  31. return apiClient
  32. } catch (error) {
  33. log.api('API Client初始化失败:', error)
  34. throw error
  35. }
  36. }
  37. // 初始化API Client
  38. // 注意:WORKSPACE_KEY 需要在 多八多(www.d8d.fun) 平台注册并开通工作空间后获取
  39. const workspaceKey = Deno.env.get('WORKSPACE_KEY') || ''
  40. if (!workspaceKey) {
  41. console.warn('未设置WORKSPACE_KEY,请前往 多八多(www.d8d.fun) 注册并开通工作空间以获取密钥')
  42. }
  43. const apiClient = await getApiClient(workspaceKey)
  44. // 创建Hono应用实例
  45. const app = new Hono()
  46. // 注册CORS中间件
  47. app.use('/*', cors())
  48. // 创建Socket.IO实例
  49. const io = new Server({
  50. cors: {
  51. origin: "*",
  52. methods: ["GET", "POST"],
  53. credentials: true
  54. }
  55. })
  56. setupSocketIO(io);
  57. // 动态加载并运行模板
  58. const runTemplate = async () => {
  59. try {
  60. // 创建基础app实例
  61. const moduleApp = new Hono()
  62. // 传入必要参数并初始化应用
  63. const appInstance = httpServer({
  64. apiClient: apiClient,
  65. app: moduleApp,
  66. moduleDir: './'
  67. })
  68. // 启动服务器
  69. Deno.serve({
  70. handler: io.handler(async (req) => {
  71. return await appInstance.fetch(req) || new Response(null, { status: 404 });
  72. }),
  73. port: 8080
  74. })
  75. console.log('应用已启动,监听端口: 8080')
  76. } catch (error) {
  77. console.error('模板加载失败:', error)
  78. }
  79. }
  80. // 执行模板
  81. runTemplate()