@h-ai/kit 0.1.0-alpha.10

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [2026] [idealworld.group]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,195 @@
1
+ # @h-ai/kit
2
+
3
+ `@h-ai/kit` 是 hai-framework 的 SvelteKit 集成模块,提供统一的请求管道与 API 工具:
4
+
5
+ - `kit.createHandle()`:会话解析、路由守卫、中间件链、可选传输加密与 Cookie 加密
6
+ - `kit.handler()`:API 端点异常边界
7
+ - `kit.guard` / `kit.response` / `kit.validate` / `kit.auth` / `kit.client` / `kit.crud`
8
+
9
+ ## 安装
10
+
11
+ ```bash
12
+ npm install @h-ai/kit
13
+ npm install svelte @sveltejs/kit zod
14
+ npm install -D @sveltejs/vite-plugin-svelte vite
15
+ ```
16
+
17
+ ## 支持的能力
18
+
19
+ - Handle Hook 组合(`createHandle` / `sequence`)
20
+ - 认证/角色/权限守卫(`guard.require` / `guard.check`)
21
+ - 内置 Logging / RateLimit / CORS 中间件(通过 `createHandle` 配置启用)
22
+ - 统一 API 响应与请求验证(Zod)
23
+ - Bearer Token 工具(服务端 login/logout + 浏览器端 Token 存储)
24
+ - 浏览器端统一客户端(自动 CSRF,支持传输加密)
25
+ - 基于 EndpointDef 的契约模式(`fromContract`)
26
+ - 声明式 CRUD 资源定义(`crud.define`)
27
+ - A2A 协议集成
28
+ - 双构建模式(`createAdapter()`)
29
+
30
+ ## 依赖
31
+
32
+ - `@h-ai/iam` — 身份认证与授权(A2A 认证),可选;使用 A2A 功能时需在 kit 使用前初始化
33
+ - `@h-ai/crypto` — 加密(传输加密 / Cookie 加密),可选;启用加密时需在 kit 使用前初始化
34
+
35
+ ## 快速开始
36
+
37
+ ### 项目配置
38
+
39
+ **svelte.config.js**:
40
+
41
+ ```js
42
+ import adapter from '@sveltejs/adapter-auto'
43
+ import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
44
+
45
+ const config = {
46
+ preprocess: [vitePreprocess()],
47
+ compilerOptions: { runes: true },
48
+ kit: {
49
+ adapter: adapter(),
50
+ // 双构建模式:import { createAdapter } from '@h-ai/kit/adapter'
51
+ // adapter: createAdapter(),
52
+ },
53
+ }
54
+
55
+ export default config
56
+ ```
57
+
58
+ **vite.config.ts**:
59
+
60
+ ```ts
61
+ import { sveltekit } from '@sveltejs/kit/vite'
62
+ import tailwindcss from '@tailwindcss/vite'
63
+ import { defineConfig } from 'vite'
64
+
65
+ export default defineConfig({
66
+ plugins: [sveltekit(), tailwindcss()],
67
+ optimizeDeps: { exclude: ['bits-ui'] },
68
+ ssr: { noExternal: [/@h-ai\//] },
69
+ })
70
+ ```
71
+
72
+ ### 搭建请求管道
73
+
74
+ **src/hooks.server.ts**:
75
+
76
+ ```typescript
77
+ import type { Handle } from '@sveltejs/kit'
78
+ import { kit } from '@h-ai/kit'
79
+
80
+ const haiHandle = kit.createHandle({
81
+ auth: {
82
+ verifyToken: async (token) => {
83
+ return token ? { userId: 'u_1', roles: ['admin'], permissions: ['user:read'] } : null
84
+ },
85
+ loginUrl: '/auth/login',
86
+ protectedPaths: ['/admin/*', '/api/*'],
87
+ publicPaths: ['/api/auth/*', '/api/public/*'],
88
+ },
89
+ rateLimit: { windowMs: 60_000, maxRequests: 100 },
90
+ logging: true,
91
+ })
92
+
93
+ export const handle: Handle = haiHandle
94
+ ```
95
+
96
+ **src/hooks.client.ts**:
97
+
98
+ ```typescript
99
+ import { kit } from '@h-ai/kit'
100
+
101
+ export const handleFetch = kit.auth.createHandleFetch()
102
+ ```
103
+
104
+ ### API 端点
105
+
106
+ ```typescript
107
+ import { kit } from '@h-ai/kit'
108
+ import { z } from 'zod'
109
+
110
+ const CreateUserSchema = z.object({
111
+ name: z.string().min(1),
112
+ email: z.string().email(),
113
+ })
114
+
115
+ export const POST = kit.handler(async ({ request, locals }) => {
116
+ kit.guard.require(locals.session, 'user:create')
117
+ const payload = await kit.validate.body(request, CreateUserSchema)
118
+ return kit.response.created(payload)
119
+ })
120
+ ```
121
+
122
+ ### 契约模式(推荐)
123
+
124
+ ```typescript
125
+ import { iamEndpoints } from '@h-ai/iam/api'
126
+ import { kit } from '@h-ai/kit'
127
+
128
+ export const POST = kit.fromContract(iamEndpoints.login, async (input) => {
129
+ const result = await iam.auth.login(input)
130
+ if (!result.success)
131
+ return kit.response.unauthorized(result.error.message)
132
+ return kit.response.ok(result.data)
133
+ })
134
+ ```
135
+
136
+ ### 浏览器客户端
137
+
138
+ ```typescript
139
+ // src/lib/utils/api.ts — 全应用共享
140
+ import { kit } from '@h-ai/kit'
141
+
142
+ const client = kit.client.create({ auth: true })
143
+ export const { apiFetch } = client
144
+ ```
145
+
146
+ ```typescript
147
+ // 使用
148
+ import { apiFetch } from '$lib/utils/api'
149
+
150
+ const response = await apiFetch('/api/users', { method: 'GET' })
151
+ ```
152
+
153
+ > CSRF Header 注入由 `apiFetch` 自动处理;`@h-ai/kit` 不提供独立的 CSRF 中间件工厂。
154
+
155
+ ## 配置
156
+
157
+ `kit.createHandle()` 配置项:
158
+
159
+ | 字段 | 类型 | 说明 |
160
+ | ------------ | ---------------------------------------- | ----------------------------------------------------------------- |
161
+ | `auth` | `HandleAuthConfig` | 认证配置(verifyToken / protectedPaths / publicPaths / loginUrl) |
162
+ | `rateLimit` | `object \| false` | 速率限制(windowMs / maxRequests) |
163
+ | `logging` | `boolean \| object` | 请求日志(默认 `true`,`{ logBody: true }` 记录请求体) |
164
+ | `crypto` | `HookCryptoConfig` | 传输加密 + Cookie 加密 |
165
+ | `guards` | `GuardConfig[]` | 自定义守卫(在 auth 自动守卫之后执行) |
166
+ | `middleware` | `Middleware[]` | 自定义中间件(在内置中间件之后执行) |
167
+ | `a2a` | `HandleA2AOperations \| HandleA2AConfig` | A2A 协议集成(Agent Card + JSON-RPC) |
168
+ | `onError` | `function` | 自定义错误处理 |
169
+
170
+ ## 导出路径
171
+
172
+ | 路径 | 用途 |
173
+ | ------------------- | ---------------------------------------------- |
174
+ | `@h-ai/kit` | 主入口:`kit` 命名空间、类型、`defineEndpoint` |
175
+ | `@h-ai/kit/client` | 浏览器端客户端 |
176
+ | `@h-ai/kit/adapter` | 双构建 adapter(`createAdapter()`) |
177
+ | `@h-ai/kit/vite` | Vite 插件 |
178
+ | `@h-ai/kit/a2a` | A2A 协议集成 |
179
+ | `@h-ai/kit/crypto` | 加密模块集成 |
180
+
181
+ ## 错误处理
182
+
183
+ - 推荐使用 `kit.handler()` 包装 API 端点。
184
+ - `kit.validate.body` / `kit.guard.require` 会抛出 `Response`(SvelteKit 控制流)。
185
+ - 非控制流异常会由 `kit.handler()` 统一转换为 `500 INTERNAL_ERROR` 响应。
186
+
187
+ ## 测试
188
+
189
+ ```bash
190
+ pnpm --filter @h-ai/kit test
191
+ ```
192
+
193
+ ## License
194
+
195
+ Apache-2.0
@@ -0,0 +1,44 @@
1
+ import * as _sveltejs_kit from '@sveltejs/kit';
2
+
3
+ /**
4
+ * SvelteKit 双构建模式 — 适配器工厂
5
+ *
6
+ * 根据 `VITE_ADAPTER` 环境变量自动选择 adapter-node 或 adapter-static,
7
+ * 使同一个 SvelteKit 应用能同时产出 SSR(Web + API)和 SPA(H5/App)两种构建产物。
8
+ *
9
+ * @example
10
+ * ```js
11
+ * // svelte.config.js
12
+ * import { createAdapter } from '@h-ai/kit/adapter'
13
+ *
14
+ * export default {
15
+ * kit: {
16
+ * adapter: createAdapter(),
17
+ * },
18
+ * }
19
+ * ```
20
+ *
21
+ * @module kit-adapter
22
+ */
23
+ /** 双构建适配器配置 */
24
+ interface AdapterOptions {
25
+ /** adapter-node 输出目录,默认 `'build'` */
26
+ nodeBuildDir?: string;
27
+ /** adapter-static 输出目录,默认 `'build-static'` */
28
+ staticBuildDir?: string;
29
+ /** adapter-static 的 SPA fallback 页面,默认 `'index.html'` */
30
+ staticFallback?: string;
31
+ }
32
+ /**
33
+ * 根据环境变量 `VITE_ADAPTER` 选择 SvelteKit adapter
34
+ *
35
+ * - `VITE_ADAPTER=node` → `@sveltejs/adapter-node`(SSR + API)
36
+ * - `VITE_ADAPTER=static` → `@sveltejs/adapter-static`(SPA,可被 Capacitor 包装)
37
+ * - 未设置时默认使用 `node`
38
+ *
39
+ * **注意**:adapter-node / adapter-static 仍然需要在应用的 devDependencies 中声明。
40
+ * 本函数只做动态 import + 统一配置。
41
+ */
42
+ declare function createAdapter(options?: AdapterOptions): Promise<_sveltejs_kit.Adapter>;
43
+
44
+ export { type AdapterOptions, createAdapter };
@@ -0,0 +1,28 @@
1
+ import process from 'process';
2
+
3
+ // src/kit-adapter.ts
4
+ async function createAdapter(options) {
5
+ const {
6
+ nodeBuildDir = "build",
7
+ staticBuildDir = "build-static",
8
+ staticFallback = "index.html"
9
+ } = options ?? {};
10
+ const mode = process.env.VITE_ADAPTER ?? "node";
11
+ if (mode === "static") {
12
+ const { default: adapterStatic } = await import('@sveltejs/adapter-static');
13
+ return adapterStatic({
14
+ pages: staticBuildDir,
15
+ assets: staticBuildDir,
16
+ fallback: staticFallback,
17
+ precompress: false
18
+ });
19
+ }
20
+ const { default: adapterNode } = await import('@sveltejs/adapter-node');
21
+ return adapterNode({
22
+ out: nodeBuildDir
23
+ });
24
+ }
25
+
26
+ export { createAdapter };
27
+ //# sourceMappingURL=index.js.map
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/kit-adapter.ts"],"names":[],"mappings":";;;AA2CA,eAAsB,cAAc,OAAA,EAA0B;AAC5D,EAAA,MAAM;AAAA,IACJ,YAAA,GAAe,OAAA;AAAA,IACf,cAAA,GAAiB,cAAA;AAAA,IACjB,cAAA,GAAiB;AAAA,GACnB,GAAI,WAAW,EAAC;AAEhB,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,YAAA,IAAgB,MAAA;AAEzC,EAAA,IAAI,SAAS,QAAA,EAAU;AACrB,IAAA,MAAM,EAAE,OAAA,EAAS,aAAA,EAAc,GAAI,MAAM,OAAO,0BAA0B,CAAA;AAC1E,IAAA,OAAO,aAAA,CAAc;AAAA,MACnB,KAAA,EAAO,cAAA;AAAA,MACP,MAAA,EAAQ,cAAA;AAAA,MACR,QAAA,EAAU,cAAA;AAAA,MACV,WAAA,EAAa;AAAA,KACd,CAAA;AAAA,EACH;AAGA,EAAA,MAAM,EAAE,OAAA,EAAS,WAAA,EAAY,GAAI,MAAM,OAAO,wBAAwB,CAAA;AACtE,EAAA,OAAO,WAAA,CAAY;AAAA,IACjB,GAAA,EAAK;AAAA,GACN,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * SvelteKit 双构建模式 — 适配器工厂\n *\n * 根据 `VITE_ADAPTER` 环境变量自动选择 adapter-node 或 adapter-static,\n * 使同一个 SvelteKit 应用能同时产出 SSR(Web + API)和 SPA(H5/App)两种构建产物。\n *\n * @example\n * ```js\n * // svelte.config.js\n * import { createAdapter } from '@h-ai/kit/adapter'\n *\n * export default {\n * kit: {\n * adapter: createAdapter(),\n * },\n * }\n * ```\n *\n * @module kit-adapter\n */\n\nimport process from 'node:process'\n\n/** 双构建适配器配置 */\nexport interface AdapterOptions {\n /** adapter-node 输出目录,默认 `'build'` */\n nodeBuildDir?: string\n /** adapter-static 输出目录,默认 `'build-static'` */\n staticBuildDir?: string\n /** adapter-static 的 SPA fallback 页面,默认 `'index.html'` */\n staticFallback?: string\n}\n\n/**\n * 根据环境变量 `VITE_ADAPTER` 选择 SvelteKit adapter\n *\n * - `VITE_ADAPTER=node` → `@sveltejs/adapter-node`(SSR + API)\n * - `VITE_ADAPTER=static` → `@sveltejs/adapter-static`(SPA,可被 Capacitor 包装)\n * - 未设置时默认使用 `node`\n *\n * **注意**:adapter-node / adapter-static 仍然需要在应用的 devDependencies 中声明。\n * 本函数只做动态 import + 统一配置。\n */\nexport async function createAdapter(options?: AdapterOptions) {\n const {\n nodeBuildDir = 'build',\n staticBuildDir = 'build-static',\n staticFallback = 'index.html',\n } = options ?? {}\n\n const mode = process.env.VITE_ADAPTER ?? 'node'\n\n if (mode === 'static') {\n const { default: adapterStatic } = await import('@sveltejs/adapter-static')\n return adapterStatic({\n pages: staticBuildDir,\n assets: staticBuildDir,\n fallback: staticFallback,\n precompress: false,\n })\n }\n\n // 默认 node\n const { default: adapterNode } = await import('@sveltejs/adapter-node')\n return adapterNode({\n out: nodeBuildDir,\n })\n}\n"]}
@@ -0,0 +1,38 @@
1
+ import { c as createKitClient, s as setBrowserToken, a as clearBrowserToken, b as createTokenStore, d as createHandleFetch } from './index-BotXLTck.js';
2
+ export { C as ClientTransportConfig, K as KitClient, e as KitClientConfig } from './index-BotXLTck.js';
3
+ import { d as defineCrud, s as setAllModulesLocale } from './kit-i18n-CgpNTh9G.js';
4
+ export { A as ApiResponse, a as AuthOperations, b as AuthOperationsProvider, C as CorsConfig, F as FormError, c as FormValidationResult, G as GuardConfig, d as GuardResult, H as HaiRequestEvent, e as HandleA2AConfig, f as HandleA2AOperations, g as HandleAuthConfig, h as HandleConfig, i as HookCryptoConfig, M as Middleware, j as MiddlewareContext, R as RateLimitConfig, k as RouteGuard, S as SessionData, l as SessionLike, T as TransportEncryptionOptions } from './kit-types-BHlDNNpd.js';
5
+ import '@h-ai/core';
6
+ import '@h-ai/iam';
7
+ import '@sveltejs/kit';
8
+ import './kit-crypto-types-C-gEvx04.js';
9
+
10
+ /**
11
+ * @h-ai/kit — 浏览器入口
12
+ *
13
+ * 为客户端提供精简且安全的运行时导出,避免将服务端 Hook/A2A/IAM 运行时代码打入浏览器包。
14
+ * @module browser
15
+ */
16
+
17
+ /**
18
+ * 浏览器端 kit 对象(仅暴露 client-safe 能力)
19
+ */
20
+ declare const kit: {
21
+ client: {
22
+ create: typeof createKitClient;
23
+ };
24
+ crud: {
25
+ define: typeof defineCrud;
26
+ };
27
+ auth: {
28
+ setBrowserToken: typeof setBrowserToken;
29
+ clearBrowserToken: typeof clearBrowserToken;
30
+ createTokenStore: typeof createTokenStore;
31
+ createHandleFetch: typeof createHandleFetch;
32
+ };
33
+ i18n: {
34
+ setLocale: typeof setAllModulesLocale;
35
+ };
36
+ };
37
+
38
+ export { createKitClient, kit };
@@ -0,0 +1,26 @@
1
+ import { defineCrud } from './chunk-FRYJMRTP.js';
2
+ import { createHandleFetch, createTokenStore, clearBrowserToken, setBrowserToken, createKitClient } from './chunk-PHS7ZD5L.js';
3
+ import { setAllModulesLocale } from './chunk-6TMSXG7J.js';
4
+
5
+ // src/browser.ts
6
+ var kit = {
7
+ client: {
8
+ create: createKitClient
9
+ },
10
+ crud: {
11
+ define: defineCrud
12
+ },
13
+ auth: {
14
+ setBrowserToken,
15
+ clearBrowserToken,
16
+ createTokenStore,
17
+ createHandleFetch
18
+ },
19
+ i18n: {
20
+ setLocale: setAllModulesLocale
21
+ }
22
+ };
23
+
24
+ export { kit };
25
+ //# sourceMappingURL=browser.js.map
26
+ //# sourceMappingURL=browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/browser.ts"],"names":[],"mappings":";;;;;AAeO,IAAM,GAAA,GAAM;AAAA,EACjB,MAAA,EAAQ;AAAA,IACN,MAAA,EAAQ;AAAA,GACV;AAAA,EACA,IAAA,EAAM;AAAA,IACJ,MAAA,EAAQ;AAAA,GACV;AAAA,EACA,IAAA,EAAM;AAAA,IACJ,eAAA;AAAA,IACA,iBAAA;AAAA,IACA,gBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,IAAA,EAAM;AAAA,IACJ,SAAA,EAAW;AAAA;AAEf","file":"browser.js","sourcesContent":["/**\n * @h-ai/kit — 浏览器入口\n *\n * 为客户端提供精简且安全的运行时导出,避免将服务端 Hook/A2A/IAM 运行时代码打入浏览器包。\n * @module browser\n */\n\nimport { createKitClient } from './client/kit-client.js'\nimport { defineCrud } from './crud/kit-crud.js'\nimport { clearBrowserToken, createHandleFetch, createTokenStore, setBrowserToken } from './kit-auth.js'\nimport { setAllModulesLocale } from './kit-i18n.js'\n\n/**\n * 浏览器端 kit 对象(仅暴露 client-safe 能力)\n */\nexport const kit = {\n client: {\n create: createKitClient,\n },\n crud: {\n define: defineCrud,\n },\n auth: {\n setBrowserToken,\n clearBrowserToken,\n createTokenStore,\n createHandleFetch,\n },\n i18n: {\n setLocale: setAllModulesLocale,\n },\n}\n\nexport type * from './client/index.js'\nexport type * from './kit-types.js'\n"]}
@@ -0,0 +1,110 @@
1
+ import { iam } from '@h-ai/iam';
2
+
3
+ // src/modules/a2a/kit-a2a-auth.ts
4
+ function createA2AApiKeyAuthenticator(config) {
5
+ return async (event) => {
6
+ const rawKey = config.in === "header" ? event.request.headers.get(config.name) : event.url.searchParams.get(config.name);
7
+ if (!rawKey)
8
+ return null;
9
+ const result = await iam.apiKey.verifyApiKey(rawKey);
10
+ if (!result.success)
11
+ return null;
12
+ return {
13
+ agentId: result.data.userId,
14
+ apiKeyId: result.data.id,
15
+ scopes: result.data.scopes
16
+ };
17
+ };
18
+ }
19
+
20
+ // src/modules/a2a/kit-a2a-handle.ts
21
+ function resolveA2AConfig(input) {
22
+ if (!input)
23
+ return null;
24
+ if ("getAgentCard" in input && "handleRequest" in input) {
25
+ return {
26
+ operations: input,
27
+ cardPath: "/.well-known/agent.json",
28
+ rpcPath: "/a2a"
29
+ };
30
+ }
31
+ const cfg = input;
32
+ return {
33
+ operations: cfg.operations,
34
+ cardPath: cfg.cardPath ?? "/.well-known/agent.json",
35
+ rpcPath: cfg.rpcPath ?? "/a2a",
36
+ authenticate: resolveAuthenticate(cfg.authenticate, cfg.operations)
37
+ };
38
+ }
39
+ function resolveAuthenticate(authenticate, operations) {
40
+ if (!authenticate)
41
+ return void 0;
42
+ if (typeof authenticate === "function")
43
+ return authenticate;
44
+ const cardResult = operations.getAgentCard();
45
+ const security = cardResult.success && cardResult.data ? cardResult.data.security : void 0;
46
+ const apiKeyCfg = security?.apiKey;
47
+ return createA2AApiKeyAuthenticator({
48
+ in: apiKeyCfg?.in ?? "header",
49
+ name: apiKeyCfg?.name ?? "x-api-key"
50
+ });
51
+ }
52
+ async function handleA2ARequest(event, requestId, config) {
53
+ const { pathname } = event.url;
54
+ if (pathname === config.cardPath && event.request.method === "GET") {
55
+ const result = config.operations.getAgentCard();
56
+ if (result.success) {
57
+ return new Response(JSON.stringify(result.data), {
58
+ headers: { "Content-Type": "application/json", "X-Request-Id": requestId }
59
+ });
60
+ }
61
+ return new Response(
62
+ JSON.stringify({ error: { code: "A2A_NOT_CONFIGURED", message: "Agent card not available" } }),
63
+ { status: 503, headers: { "Content-Type": "application/json", "X-Request-Id": requestId } }
64
+ );
65
+ }
66
+ if (pathname === config.rpcPath && event.request.method === "POST") {
67
+ let context;
68
+ if (config.authenticate) {
69
+ const authResult = await config.authenticate(event);
70
+ if (authResult) {
71
+ context = authResult;
72
+ }
73
+ }
74
+ const body = await event.request.json();
75
+ const result = await config.operations.handleRequest(body, context);
76
+ if (result.streaming && result.stream) {
77
+ const stream = result.stream;
78
+ const readable = new ReadableStream({
79
+ async start(controller) {
80
+ const encoder = new TextEncoder();
81
+ try {
82
+ for await (const chunk of stream) {
83
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}
84
+
85
+ `));
86
+ }
87
+ } finally {
88
+ controller.close();
89
+ }
90
+ }
91
+ });
92
+ return new Response(readable, {
93
+ headers: {
94
+ "Content-Type": "text/event-stream",
95
+ "Cache-Control": "no-cache",
96
+ "Connection": "keep-alive",
97
+ "X-Request-Id": requestId
98
+ }
99
+ });
100
+ }
101
+ return new Response(JSON.stringify(result.body), {
102
+ headers: { "Content-Type": "application/json", "X-Request-Id": requestId }
103
+ });
104
+ }
105
+ return null;
106
+ }
107
+
108
+ export { createA2AApiKeyAuthenticator, handleA2ARequest, resolveA2AConfig };
109
+ //# sourceMappingURL=chunk-475WECWK.js.map
110
+ //# sourceMappingURL=chunk-475WECWK.js.map