@rtc-agent/component 0.2.4 → 0.2.6-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,55 @@
2
2
 
3
3
  基于 Lit 的 Web Component 组件库,提供浮窗式 RTC Agent 交互界面。
4
4
 
5
+ ## 快速开始
6
+
7
+ ### 安装
8
+
9
+ ```bash
10
+ pnpm add @rtc-agent/component
11
+ ```
12
+
13
+ ### 使用工厂函数(推荐)
14
+
15
+ ```ts
16
+ import { createRtcAgent } from '@rtc-agent/component';
17
+
18
+ const agent = createRtcAgent({
19
+ appLabel: 'My Assistant',
20
+ server: { url: 'https://api.example.com' },
21
+ auth: {
22
+ getToken: () => localStorage.getItem('token'),
23
+ refreshToken: async () => {
24
+ const res = await fetch('/api/refresh');
25
+ const data = await res.json();
26
+ return { accessToken: data.token };
27
+ },
28
+ userId: 'user-123',
29
+ },
30
+ });
31
+
32
+ document.body.appendChild(agent);
33
+
34
+ // 销毁
35
+ agent.destroy();
36
+ ```
37
+
38
+ 完整 API 文档见 [API.md](./API.md),更多示例见 [EXAMPLES.md](./EXAMPLES.md)。
39
+
40
+ ### 使用 HTML 元素
41
+
42
+ ```html
43
+ <script type="module">
44
+ import '@rtc-agent/component';
45
+ </script>
46
+
47
+ <rtc-agent
48
+ theme="system"
49
+ app-label="RTC Agent"
50
+ scenarios-url="./scenarios/"
51
+ ></rtc-agent>
52
+ ```
53
+
5
54
  ## 导出
6
55
 
7
56
  ### 组件
@@ -18,6 +67,17 @@ import { RtcAgent } from '@rtc-agent/component';
18
67
  const agent = document.querySelector<RtcAgent>('rtc-agent')!;
19
68
  ```
20
69
 
70
+ ### 工厂函数
71
+
72
+ - `createRtcAgent` — 声明式创建 `<rtc-agent>` 实例
73
+
74
+ ```ts
75
+ import { createRtcAgent } from '@rtc-agent/component';
76
+ const agent = createRtcAgent({ /* ... */ });
77
+ ```
78
+
79
+ 详细配置见 [API.md](./API.md)。
80
+
21
81
  ## 用法
22
82
 
23
83
  ```html
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * RTC Agent SharedWorker Setup Tool
5
+ *
6
+ * Automatically copies the SharedWorker file to the host application's public directory.
7
+ * This solves the NPM distribution problem where the worker file inside node_modules
8
+ * cannot be accessed by the browser.
9
+ *
10
+ * Usage:
11
+ * npx rtc-agent-setup
12
+ *
13
+ * Or in package.json:
14
+ * "scripts": {
15
+ * "postinstall": "rtc-agent-setup"
16
+ * }
17
+ */
18
+
19
+ import { existsSync, mkdirSync, copyFileSync, readFileSync, readdirSync, writeFileSync } from 'fs';
20
+ import { join, dirname } from 'path';
21
+ import { fileURLToPath } from 'url';
22
+
23
+ const __filename = fileURLToPath(import.meta.url);
24
+ const __dirname = dirname(__filename);
25
+
26
+ /**
27
+ * Detect project type based on dependencies
28
+ */
29
+ function detectProjectType(cwd) {
30
+ const packageJsonPath = join(cwd, 'package.json');
31
+ if (!existsSync(packageJsonPath)) {
32
+ return null;
33
+ }
34
+
35
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
36
+ const allDeps = {
37
+ ...packageJson.dependencies,
38
+ ...packageJson.devDependencies,
39
+ };
40
+
41
+ // Detect SvelteKit first (more specific, also uses Vite)
42
+ if (allDeps?.['@sveltejs/kit']) {
43
+ return 'sveltekit';
44
+ }
45
+
46
+ // Detect Vite (generic)
47
+ if (allDeps?.vite) {
48
+ return 'vite';
49
+ }
50
+
51
+ // Detect Webpack
52
+ if (allDeps?.webpack) {
53
+ return 'webpack';
54
+ }
55
+
56
+ return 'generic';
57
+ }
58
+
59
+ /**
60
+ * Get target directory based on project type
61
+ */
62
+ function getTargetDir(projectType, cwd) {
63
+ switch (projectType) {
64
+ case 'sveltekit':
65
+ // SvelteKit uses 'static' directory for static assets
66
+ return join(cwd, 'static', 'rtc-agent');
67
+ case 'vite':
68
+ // Plain Vite projects typically use 'public' directory
69
+ return join(cwd, 'public', 'rtc-agent');
70
+ case 'webpack':
71
+ return join(cwd, 'static', 'rtc-agent');
72
+ default:
73
+ return join(cwd, 'public', 'rtc-agent');
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Copy SharedWorker files to target directory
79
+ */
80
+ function copyWorkerFiles(targetDir) {
81
+ const sourceDir = join(__dirname, '..', 'dist', 'assets');
82
+
83
+ if (!existsSync(sourceDir)) {
84
+ console.error('❌ Error: Cannot find @rtc-agent/component dist files');
85
+ console.error(' Please ensure the package is built correctly');
86
+ process.exit(1);
87
+ }
88
+
89
+ // Create target directory
90
+ if (!existsSync(targetDir)) {
91
+ mkdirSync(targetDir, { recursive: true });
92
+ console.log(`📁 Created directory: ${targetDir}`);
93
+ }
94
+
95
+ // Find and copy shared-worker files
96
+ const distFiles = readdirSync(sourceDir);
97
+ const workerFiles = distFiles.filter(f => f.startsWith('shared-worker') && f.endsWith('.js'));
98
+
99
+ if (workerFiles.length === 0) {
100
+ console.warn('⚠️ Warning: No shared-worker files found in dist/assets');
101
+ console.log(' Available files:', distFiles.join(', '));
102
+ return 0;
103
+ }
104
+
105
+ let copiedCount = 0;
106
+ let mainWorkerFile = null;
107
+
108
+ for (const file of workerFiles) {
109
+ const sourcePath = join(sourceDir, file);
110
+ const targetPath = join(targetDir, file);
111
+ copyFileSync(sourcePath, targetPath);
112
+ console.log(`✅ Copied ${file} → ${targetDir}`);
113
+ copiedCount++;
114
+
115
+ // Track the main worker file (without .map or other extensions)
116
+ if (file.endsWith('.js') && !file.includes('.map')) {
117
+ mainWorkerFile = file;
118
+ }
119
+ }
120
+
121
+ // Create a stable symlink or copy without hash for easy reference
122
+ if (mainWorkerFile && mainWorkerFile !== 'shared-worker.js') {
123
+ const stablePath = join(targetDir, 'shared-worker.js');
124
+ copyFileSync(join(targetDir, mainWorkerFile), stablePath);
125
+ console.log(`✅ Created stable link: shared-worker.js → ${mainWorkerFile}`);
126
+ }
127
+
128
+ // Create manifest.json with version info
129
+ const packageJsonPath = join(__dirname, '..', 'package.json');
130
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
131
+
132
+ const manifest = {
133
+ version: packageJson.version,
134
+ workerFile: mainWorkerFile,
135
+ stableWorkerUrl: '/rtc-agent/shared-worker.js',
136
+ timestamp: new Date().toISOString(),
137
+ };
138
+
139
+ writeFileSync(
140
+ join(targetDir, 'manifest.json'),
141
+ JSON.stringify(manifest, null, 2)
142
+ );
143
+ console.log(`✅ Created manifest.json (version ${packageJson.version})`);
144
+
145
+ return copiedCount;
146
+ }
147
+
148
+ /**
149
+ * Main entry point
150
+ */
151
+ async function main() {
152
+ console.log('🔧 RTC Agent SharedWorker Setup\n');
153
+
154
+ const cwd = process.cwd();
155
+ const projectType = detectProjectType(cwd);
156
+
157
+ if (!projectType) {
158
+ console.error('❌ Error: No package.json found in current directory');
159
+ process.exit(1);
160
+ }
161
+
162
+ console.log(`📦 Detected project type: ${projectType}`);
163
+
164
+ const targetDir = getTargetDir(projectType, cwd);
165
+ console.log(`📂 Target directory: ${targetDir}\n`);
166
+
167
+ const copiedFiles = copyWorkerFiles(targetDir);
168
+
169
+ if (copiedFiles > 0) {
170
+ console.log('\n✅ Setup complete!');
171
+ console.log('\nNext steps:');
172
+ console.log(' 1. SharedWorker files are now available in your public directory');
173
+ console.log(' 2. Configure createRtcAgent() to use the worker:');
174
+ console.log(' createRtcAgent({');
175
+ console.log(' workerUrl: \'/rtc-agent/shared-worker.js\'');
176
+ console.log(' })');
177
+ console.log(' 3. When upgrading @rtc-agent/component, run:');
178
+ console.log(' npx rtc-agent-setup');
179
+ console.log(' This will update the worker files and manifest.json');
180
+ } else {
181
+ console.log('\n⚠️ Setup completed with warnings');
182
+ console.log(' Please check if @rtc-agent/component is installed correctly');
183
+ }
184
+ }
185
+
186
+ main().catch(err => {
187
+ console.error('❌ Setup failed:', err);
188
+ process.exit(1);
189
+ });