@movk/nuxt 1.7.2 → 1.8.1

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.
Files changed (31) hide show
  1. package/dist/module.json +1 -1
  2. package/dist/module.mjs +1 -1
  3. package/dist/runtime/components/DataTable.vue +16 -24
  4. package/dist/runtime/composables/index.d.ts +1 -0
  5. package/dist/runtime/composables/index.js +1 -0
  6. package/dist/runtime/composables/useApiStream.d.ts +29 -0
  7. package/dist/runtime/composables/useApiStream.js +43 -0
  8. package/dist/runtime/domains/ai/chat-transport.d.ts +30 -0
  9. package/dist/runtime/domains/ai/chat-transport.js +31 -0
  10. package/dist/runtime/domains/ai/index.d.ts +4 -0
  11. package/dist/runtime/domains/ai/index.js +2 -0
  12. package/dist/runtime/domains/ai/types.d.ts +38 -0
  13. package/dist/runtime/domains/ai/types.js +0 -0
  14. package/dist/runtime/domains/ai/ui-message-lifecycle.d.ts +12 -0
  15. package/dist/runtime/domains/ai/ui-message-lifecycle.js +55 -0
  16. package/dist/runtime/domains/api/interceptors/response.d.ts +1 -0
  17. package/dist/runtime/domains/api/interceptors/response.js +8 -0
  18. package/dist/runtime/domains/api/stream.d.ts +46 -0
  19. package/dist/runtime/domains/api/stream.js +75 -0
  20. package/dist/runtime/domains/data-table/columns/constants.d.ts +6 -1
  21. package/dist/runtime/domains/data-table/columns/resolve-columns.d.ts +2 -2
  22. package/dist/runtime/domains/data-table/columns/resolve-columns.js +2 -1
  23. package/dist/runtime/domains/data-table/columns/resolve-data-column.js +4 -3
  24. package/dist/runtime/domains/data-table/columns/resolve-special-columns.js +3 -2
  25. package/dist/runtime/plugins/api.factory.js +3 -1
  26. package/dist/runtime/types/api/fetch.d.ts +6 -0
  27. package/dist/runtime/types/api/index.d.ts +1 -0
  28. package/dist/runtime/types/api/stream.d.ts +34 -0
  29. package/dist/runtime/types/api/stream.js +0 -0
  30. package/dist/runtime/types/data-table/component.d.ts +10 -2
  31. package/package.json +16 -1
package/dist/module.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@movk/nuxt",
3
- "version": "1.7.2",
3
+ "version": "1.8.1",
4
4
  "configKey": "movk",
5
5
  "compatibility": {
6
6
  "nuxt": ">=4.4.2"
package/dist/module.mjs CHANGED
@@ -15,7 +15,7 @@ import 'pathe';
15
15
  import 'tinyglobby';
16
16
 
17
17
  const name = "@movk/nuxt";
18
- const version = "1.7.2";
18
+ const version = "1.8.1";
19
19
 
20
20
  const MOVK_CSS_IMPORT = /@import\s+["']@movk\/nuxt["']/;
21
21
  async function checkMovkCss(nuxt) {
@@ -14,6 +14,8 @@ import { Tree, useInfiniteScrollBinding, separate } from "@movk/core";
14
14
  import theme from "#build/movk-ui/data-table";
15
15
  import tableTheme from "#build/ui/table";
16
16
  import DataTablePagination from "../domains/data-table/components/Pagination.vue";
17
+ const HEADER_SLOT_SUFFIX = "-header";
18
+ const PAGINATION_SLOTS = ["pagination", "pagination-summary", "pagination-actions"];
17
19
  const props = defineProps({
18
20
  rowKey: { type: [String, Object], required: false },
19
21
  columns: { type: Array, required: false },
@@ -76,8 +78,17 @@ const columnVisibilityKeysState = defineModel("columnVisibilityKeys", { type: Ar
76
78
  const columnVisibilityExcludeKeysState = defineModel("columnVisibilityExcludeKeys", { type: Array });
77
79
  const rowSelectionKeysState = defineModel("rowSelectionKeys", { type: Array });
78
80
  const expandedKeysState = defineModel("expandedKeys", { type: Array });
79
- defineSlots();
80
- const resolved = computed(() => resolveColumns(props.columns || [], props));
81
+ const slots = defineSlots();
82
+ const slotRecord = slots;
83
+ const headerSlots = Object.fromEntries(
84
+ Object.keys(slots).filter((name) => name.endsWith(HEADER_SLOT_SUFFIX)).map((name) => [name, (ctx) => slotRecord[name]?.(ctx) ?? []])
85
+ );
86
+ const resolved = computed(() => resolveColumns(props.columns || [], props, headerSlots));
87
+ const forwardSlots = computed(() => Object.keys(slots).filter((name) => {
88
+ if (PAGINATION_SLOTS.includes(name)) return false;
89
+ if (!name.endsWith(HEADER_SLOT_SUFFIX)) return true;
90
+ return !resolved.value.allColumnIds.includes(name.slice(0, -HEADER_SLOT_SUFFIX.length));
91
+ }));
81
92
  function hasEntries(v) {
82
93
  return typeof v === "object" && v !== null && Object.keys(v).length > 0;
83
94
  }
@@ -556,28 +567,9 @@ defineExpose({
556
567
  :style="borderedStyle"
557
568
  v-bind="uTableProps"
558
569
  >
559
- <template v-if="$slots.expanded" #expanded="{ row }">
560
- <slot name="expanded" :row="row" />
561
- </template>
562
-
563
- <template v-if="$slots.empty" #empty>
564
- <slot name="empty" />
565
- </template>
566
-
567
- <template v-if="$slots.loading" #loading>
568
- <slot name="loading" />
569
- </template>
570
-
571
- <template v-if="$slots.caption" #caption>
572
- <slot name="caption" />
573
- </template>
574
-
575
- <template v-if="$slots['body-top']" #body-top>
576
- <slot name="body-top" />
577
- </template>
578
-
579
- <template v-if="$slots['body-bottom']" #body-bottom>
580
- <slot name="body-bottom" />
570
+ <!-- 插槽名是联合类型,vue-tsc 会把作用域参数收敛成全部插槽 props 的交叉类型,转发时只能绕过 -->
571
+ <template v-for="name in forwardSlots" #[name]="slotProps" :key="name">
572
+ <slot :name="name" v-bind="slotProps ?? {}" />
581
573
  </template>
582
574
  </UTable>
583
575
 
@@ -1,6 +1,7 @@
1
1
  export * from './useApiFetch';
2
2
  export * from './useLazyApiFetch';
3
3
  export * from './useClientApiFetch';
4
+ export * from './useApiStream';
4
5
  export * from './useDownloadWithProgress';
5
6
  export * from './useUploadWithProgress';
6
7
  export * from './useAutoForm';
@@ -1,6 +1,7 @@
1
1
  export * from "./useApiFetch.js";
2
2
  export * from "./useLazyApiFetch.js";
3
3
  export * from "./useClientApiFetch.js";
4
+ export * from "./useApiStream.js";
4
5
  export * from "./useDownloadWithProgress.js";
5
6
  export * from "./useUploadWithProgress.js";
6
7
  export * from "./useAutoForm.js";
@@ -0,0 +1,29 @@
1
+ import type { Ref } from 'vue';
2
+ import type { ApiError, ApiStreamStatus, UseApiStreamOptions } from '../types/api';
3
+ /**
4
+ * SSE 流式请求 composable(仅客户端)
5
+ *
6
+ * @description `$api.stream()` 的响应式外壳,复用端点、鉴权、业务码校验与 toast:
7
+ * - 重新发起会自动中止上一条流,作用域销毁时同样中止
8
+ * - 主动中止不计入错误态(`status` 置 `'aborted'`,`error` 保持 null),其余错误在置态后继续抛出
9
+ * - 返回的是惰性生成器,开始迭代才真正发起请求
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const { status, error, stream, abort } = useApiStream<{ content: string }>()
14
+ *
15
+ * for await (const chunk of stream('/api/chat', { method: 'POST', body: { message: '你好' } })) {
16
+ * text.value += chunk.content
17
+ * }
18
+ * ```
19
+ */
20
+ export declare function useApiStream<T = unknown>(): {
21
+ /** 流式请求状态 */
22
+ status: Ref<ApiStreamStatus>;
23
+ /** 错误信息;主动中止不写入 */
24
+ error: Ref<ApiError | Error | null>;
25
+ /** 发起流式请求,逐条产出分片 */
26
+ stream: (url: string, options?: UseApiStreamOptions<T>) => AsyncGenerator<T>;
27
+ /** 中止当前流 */
28
+ abort: () => void;
29
+ };
@@ -0,0 +1,43 @@
1
+ import { onScopeDispose, ref } from "vue";
2
+ import { useNuxtApp } from "#app";
3
+ import { isAbortError } from "../domains/api/stream.js";
4
+ export function useApiStream() {
5
+ const { $api } = useNuxtApp();
6
+ const status = ref("idle");
7
+ const error = ref(null);
8
+ let controller = null;
9
+ const abort = () => {
10
+ controller?.abort();
11
+ controller = null;
12
+ };
13
+ async function* stream(url, options = {}) {
14
+ const { endpoint, onError, signal, ...streamOptions } = options;
15
+ abort();
16
+ controller = new AbortController();
17
+ signal?.addEventListener("abort", abort, { once: true });
18
+ status.value = "streaming";
19
+ error.value = null;
20
+ const api = endpoint ? $api.use(endpoint) : $api;
21
+ try {
22
+ const chunks = await api.stream(url, { ...streamOptions, signal: controller.signal });
23
+ for await (const chunk of chunks) {
24
+ yield chunk;
25
+ }
26
+ status.value = "success";
27
+ } catch (cause) {
28
+ if (isAbortError(cause)) {
29
+ status.value = "aborted";
30
+ return;
31
+ }
32
+ const streamError = cause instanceof Error ? cause : new Error("\u6D41\u5F0F\u8BF7\u6C42\u5931\u8D25");
33
+ error.value = streamError;
34
+ status.value = "error";
35
+ onError?.(streamError);
36
+ throw streamError;
37
+ } finally {
38
+ controller = null;
39
+ }
40
+ }
41
+ onScopeDispose(abort, true);
42
+ return { status, error, stream, abort };
43
+ }
@@ -0,0 +1,30 @@
1
+ import type { ChatTransport, HttpChatTransportInitOptions, UIMessage } from 'ai';
2
+ import type { EventStreamOptions, MovkApiEndpointName } from '../../types/api';
3
+ import type { UIChunkSelector } from './types';
4
+ /**
5
+ * 传输层选项:在 AI SDK 的 `HttpChatTransportInitOptions` 之上补两件事——走哪个端点、分片怎么映射
6
+ */
7
+ export type MovkChatTransportOptions<Raw, UI_MESSAGE extends UIMessage> = HttpChatTransportInitOptions<UI_MESSAGE> & EventStreamOptions<Raw> & {
8
+ /** 使用的端点名称,默认走 defaultEndpoint */
9
+ endpoint?: MovkApiEndpointName;
10
+ /** 后端分片 → UI 片段的纯映射 */
11
+ select: UIChunkSelector<Raw>;
12
+ };
13
+ /**
14
+ * 创建接 movk `$api` 的 AI SDK 传输层
15
+ *
16
+ * @description 请求编排(api/headers/body/credentials/prepareSendMessagesRequest/重连)全部继承
17
+ * AI SDK 的 `HttpChatTransport`,本工厂只补两处:默认 fetch 换成 `$api`,响应流按 `select` 映射成
18
+ * `UIMessageChunk`。需在 setup 作用域内调用(内部取 `$api`)。
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const transport = createChatTransport<BackendChunk>({
23
+ * api: '/chat/completions',
24
+ * select: raw => ({ id: raw.node, delta: raw.content, finished: raw.done })
25
+ * })
26
+ *
27
+ * const { messages, sendMessage } = useChat({ transport })
28
+ * ```
29
+ */
30
+ export declare function createChatTransport<Raw = unknown, UI_MESSAGE extends UIMessage = UIMessage>(options: MovkChatTransportOptions<Raw, UI_MESSAGE>): ChatTransport<UI_MESSAGE>;
@@ -0,0 +1,31 @@
1
+ import { HttpChatTransport } from "ai";
2
+ import { useNuxtApp } from "#app";
3
+ import { toEventStream, withStreamAccept } from "../api/stream.js";
4
+ import { createUIMessageLifecycle } from "./ui-message-lifecycle.js";
5
+ class MovkChatTransport extends HttpChatTransport {
6
+ select;
7
+ parse;
8
+ constructor(options) {
9
+ const { select, parse, endpoint: _endpoint, ...init } = options;
10
+ super(init);
11
+ this.select = select;
12
+ this.parse = parse;
13
+ }
14
+ processResponseStream(stream) {
15
+ return toEventStream(stream, { parse: this.parse }).pipeThrough(createUIMessageLifecycle(this.select));
16
+ }
17
+ }
18
+ function createApiFetch(api) {
19
+ return async (input, init) => await api.raw(String(input), {
20
+ ...init,
21
+ headers: withStreamAccept(init?.headers)
22
+ });
23
+ }
24
+ export function createChatTransport(options) {
25
+ const { $api } = useNuxtApp();
26
+ const api = options.endpoint ? $api.use(options.endpoint) : $api;
27
+ return new MovkChatTransport({
28
+ ...options,
29
+ fetch: options.fetch ?? createApiFetch(api)
30
+ });
31
+ }
@@ -0,0 +1,4 @@
1
+ export type { UIChunkData, UIChunkSelection, UIChunkSelector } from './types';
2
+ export type { MovkChatTransportOptions } from './chat-transport';
3
+ export { createChatTransport } from './chat-transport';
4
+ export { createUIMessageLifecycle } from './ui-message-lifecycle';
@@ -0,0 +1,2 @@
1
+ export { createChatTransport } from "./chat-transport.js";
2
+ export { createUIMessageLifecycle } from "./ui-message-lifecycle.js";
@@ -0,0 +1,38 @@
1
+ /**
2
+ * 一条后端分片映射出的 UI 片段意图
3
+ *
4
+ * @description 各字段互相独立,可同时给出(例如同一条分片既有增量文本、又是节点结束信号)
5
+ */
6
+ export interface UIChunkSelection {
7
+ /**
8
+ * 文本块 id,同 id 的增量并入同一块
9
+ * @defaultValue 'text-1'
10
+ */
11
+ id?: string;
12
+ /** 本片增量文本,为空则不产出 text-delta */
13
+ delta?: string;
14
+ /** 该文本块到此结束 */
15
+ end?: boolean;
16
+ /** 附带的自定义数据片 */
17
+ data?: UIChunkData;
18
+ /** 整条流到此结束 */
19
+ finished?: boolean;
20
+ }
21
+ /**
22
+ * 自定义数据片
23
+ */
24
+ export interface UIChunkData {
25
+ /** 片类型名,最终产出 `data-${type}` 片 */
26
+ type: string;
27
+ /** 片负载 */
28
+ value: unknown;
29
+ /**
30
+ * 只走 `onData` 回调、不写入消息历史
31
+ * @defaultValue false
32
+ */
33
+ transient?: boolean;
34
+ }
35
+ /**
36
+ * 后端分片 → UI 片段的纯映射,返回 undefined 表示该分片不产出任何片段
37
+ */
38
+ export type UIChunkSelector<Raw> = (raw: Raw) => UIChunkSelection | undefined;
File without changes
@@ -0,0 +1,12 @@
1
+ import type { UIMessageChunk } from 'ai';
2
+ import type { UIChunkSelector } from './types';
3
+ /**
4
+ * 后端分片流 → AI SDK 的 UIMessageChunk 流
5
+ *
6
+ * @description 领域侧只提供无状态的 `select`,生命周期全部由本转换器兜住:
7
+ * - `start` / `start-step` 只发一次
8
+ * - 按 id 开合文本块,同 id 的增量并入同一块
9
+ * - flush 时补齐所有未关闭的文本块与 `finish-step` / `finish`——后端不发结束信号或中途断流时,
10
+ * 消息也不会永远停在 streaming
11
+ */
12
+ export declare function createUIMessageLifecycle<Raw>(select: UIChunkSelector<Raw>): TransformStream<Raw, UIMessageChunk>;
@@ -0,0 +1,55 @@
1
+ const DEFAULT_TEXT_ID = "text-1";
2
+ export function createUIMessageLifecycle(select) {
3
+ const openTexts = /* @__PURE__ */ new Set();
4
+ let started = false;
5
+ let finished = false;
6
+ function start(controller) {
7
+ if (started) return;
8
+ started = true;
9
+ controller.enqueue({ type: "start" });
10
+ controller.enqueue({ type: "start-step" });
11
+ }
12
+ function finish(controller) {
13
+ if (finished) return;
14
+ finished = true;
15
+ for (const id of openTexts) {
16
+ controller.enqueue({ type: "text-end", id });
17
+ }
18
+ openTexts.clear();
19
+ controller.enqueue({ type: "finish-step" });
20
+ controller.enqueue({ type: "finish" });
21
+ }
22
+ return new TransformStream({
23
+ transform(raw, controller) {
24
+ if (finished) return;
25
+ const selection = select(raw);
26
+ if (!selection) return;
27
+ const { id = DEFAULT_TEXT_ID, delta, end, data } = selection;
28
+ start(controller);
29
+ if (data) {
30
+ controller.enqueue({
31
+ type: `data-${data.type}`,
32
+ data: data.value,
33
+ ...data.transient !== void 0 && { transient: data.transient }
34
+ });
35
+ }
36
+ if (delta) {
37
+ if (!openTexts.has(id)) {
38
+ openTexts.add(id);
39
+ controller.enqueue({ type: "text-start", id });
40
+ }
41
+ controller.enqueue({ type: "text-delta", id, delta });
42
+ }
43
+ if (end && openTexts.delete(id)) {
44
+ controller.enqueue({ type: "text-end", id });
45
+ }
46
+ if (selection.finished) {
47
+ finish(controller);
48
+ }
49
+ },
50
+ flush(controller) {
51
+ start(controller);
52
+ finish(controller);
53
+ }
54
+ });
55
+ }
@@ -12,6 +12,7 @@ type NuxtApp = ReturnType<typeof useNuxtApp>;
12
12
  *
13
13
  * **契约**:拦截器输出 = 业务数据。`movk:api:response` hook 收到的 `context.response._data` 已解包;
14
14
  * 调用方设置 `skipUnwrap: true` 时不重写 `_data`,保留原始响应。
15
+ * 响应体是可读流时整段短路,`_data` 原样保留,调用方无需再传 `skipUnwrap` / `skipBusinessCheck`。
15
16
  */
16
17
  export declare function createOnResponse(resolvedConfig: ResolvedEndpointConfig, publicConfig: MovkApiPublicConfig, nuxtApp: NuxtApp): (context: FetchContext) => Promise<void>;
17
18
  export {};
@@ -1,4 +1,5 @@
1
1
  import { extractData, extractMessage, isBusinessSuccess } from "../response.js";
2
+ import { isReadableStream } from "../stream.js";
2
3
  import { createApiError } from "../errors.js";
3
4
  import { showToast } from "../toast.js";
4
5
  function readApiContext(options) {
@@ -9,6 +10,13 @@ export function createOnResponse(resolvedConfig, publicConfig, nuxtApp) {
9
10
  return async function onResponse(context) {
10
11
  const raw = context.response?._data;
11
12
  const { toast, skipBusinessCheck, skipUnwrap } = readApiContext(context.options);
13
+ if (isReadableStream(raw)) {
14
+ if (publicConfig.debug) {
15
+ console.info("[@movk/nuxt] Response: <stream>");
16
+ }
17
+ await nuxtApp.callHook("movk:api:response", context);
18
+ return;
19
+ }
12
20
  if (publicConfig.debug) {
13
21
  console.info("[@movk/nuxt] Response:", raw);
14
22
  }
@@ -0,0 +1,46 @@
1
+ import type { $Fetch } from 'nitropack/types';
2
+ import type { ApiStreamOptions, EventStreamOptions } from '../../types/api/stream';
3
+ /**
4
+ * 是否可读流
5
+ *
6
+ * @description 鸭子判定而非 `instanceof`:SSR 运行时不保证有 `ReadableStream` 全局
7
+ */
8
+ export declare function isReadableStream(value: unknown): value is ReadableStream<Uint8Array>;
9
+ /**
10
+ * 中止判定
11
+ *
12
+ * @description 请求头到达前中止由 ofetch 包成 FetchError、原始错误落在 `cause` 上;
13
+ * 流读取途中中止则由 reader 直接抛出。按 `name` 认而非 `instanceof DOMException`,
14
+ * Node 与浏览器抛出的类型不一致。
15
+ */
16
+ export declare function isAbortError(error: unknown): boolean;
17
+ /**
18
+ * 字节流 → SSE 事件 → 分片流
19
+ *
20
+ * @description 行缓冲、`data:` 多行拼接、注释行、`\r\n` 全部交给 `eventsource-parser`;
21
+ * 本层只负责哨兵终止与 payload 解析,解析不了的事件静默丢弃(心跳、握手不该中断整条流)。
22
+ */
23
+ export declare function toEventStream<T>(body: ReadableStream<Uint8Array>, options?: EventStreamOptions<T>): ReadableStream<T>;
24
+ /**
25
+ * 流 → 异步迭代器
26
+ *
27
+ * @description 不依赖 `ReadableStream` 自身的异步迭代(浏览器支持参差);
28
+ * 消费方提前跳出时取消上游,连带断开底层请求。
29
+ */
30
+ export declare function iterateStream<T>(stream: ReadableStream<T>): AsyncGenerator<T>;
31
+ /**
32
+ * 补上 SSE 请求的 Accept
33
+ *
34
+ * @description ofetch 见到可 JSON 序列化的 body 就自动塞 `Accept: application/json`——
35
+ * 对一条要当流读的请求,这个声明本身就是错的,按 Accept 做内容协商的后端可能据此改走 JSON 渲染器。
36
+ * 但也不能反过来主动发 text/event-stream:实测 DRF 一类的内容协商会直接拒掉整个请求,
37
+ * 返回「无法满足 Accept HTTP 头的请求」。通配 Accept 两头都不踩,调用方传了就以调用方为准。
38
+ */
39
+ export declare function withStreamAccept(headers?: HeadersInit): Headers;
40
+ /**
41
+ * 发起请求并取出 SSE 分片流
42
+ *
43
+ * @description 走 `$fetch.raw` 而非原生 fetch:端点 baseURL、鉴权头、业务码校验、toast 与
44
+ * `movk:api:*` hook 全部复用。响应是流时拦截器已短路,不会拿流去做 `{ code, data }` 解包。
45
+ */
46
+ export declare function openEventStream<T>($fetch: $Fetch, url: string, options?: ApiStreamOptions<T>): Promise<AsyncGenerator<T>>;
@@ -0,0 +1,75 @@
1
+ import { EventSourceParserStream } from "eventsource-parser/stream";
2
+ const DONE_SENTINEL = "[DONE]";
3
+ function parseJson(data) {
4
+ try {
5
+ return JSON.parse(data);
6
+ } catch {
7
+ return void 0;
8
+ }
9
+ }
10
+ function describe(value) {
11
+ if (value === null || value === void 0) return String(value);
12
+ if (typeof value === "object") return value.constructor?.name || "Object";
13
+ return typeof value;
14
+ }
15
+ export function isReadableStream(value) {
16
+ return typeof value?.getReader === "function";
17
+ }
18
+ export function isAbortError(error) {
19
+ const cause = error instanceof Error ? error.cause : void 0;
20
+ return hasAbortName(error) || hasAbortName(cause);
21
+ }
22
+ function hasAbortName(value) {
23
+ return typeof value === "object" && value !== null && value.name === "AbortError";
24
+ }
25
+ export function toEventStream(body, options = {}) {
26
+ const parse = options.parse ?? parseJson;
27
+ const decoder = new TextDecoderStream();
28
+ return body.pipeThrough(decoder).pipeThrough(new EventSourceParserStream()).pipeThrough(new TransformStream({
29
+ transform(event, controller) {
30
+ if (event.data === DONE_SENTINEL) {
31
+ controller.terminate();
32
+ return;
33
+ }
34
+ const chunk = parse(event.data);
35
+ if (chunk !== void 0) {
36
+ controller.enqueue(chunk);
37
+ }
38
+ }
39
+ }));
40
+ }
41
+ export async function* iterateStream(stream) {
42
+ const reader = stream.getReader();
43
+ try {
44
+ while (true) {
45
+ const { done, value } = await reader.read();
46
+ if (done) break;
47
+ yield value;
48
+ }
49
+ } finally {
50
+ await reader.cancel().catch(() => {
51
+ });
52
+ reader.releaseLock();
53
+ }
54
+ }
55
+ export function withStreamAccept(headers) {
56
+ const merged = new Headers(headers);
57
+ if (!merged.has("accept")) {
58
+ merged.set("accept", "*/*");
59
+ }
60
+ return merged;
61
+ }
62
+ export async function openEventStream($fetch, url, options = {}) {
63
+ const { parse, headers, ...fetchOptions } = options;
64
+ const response = await $fetch.raw(url, {
65
+ ...fetchOptions,
66
+ headers: withStreamAccept(headers)
67
+ });
68
+ const body = response._data;
69
+ if (!isReadableStream(body)) {
70
+ throw new Error(
71
+ `[@movk/nuxt] \u671F\u671B SSE \u6D41\uFF0C\u5B9E\u9645\u6536\u5230 ${describe(body)}\u3002\u8BF7\u786E\u8BA4\u63A5\u53E3\u8FD4\u56DE text/event-stream\uFF0C\u6216\u663E\u5F0F\u4F20 responseType: 'stream'`
72
+ );
73
+ }
74
+ return iterateStream(toEventStream(body, { parse }));
75
+ }
@@ -1,4 +1,5 @@
1
- import type { ColumnDef, ColumnMeta, ColumnPinningState, ColumnSizingState, VisibilityState } from '@tanstack/vue-table';
1
+ import type { ColumnDef, ColumnMeta, ColumnPinningState, ColumnSizingState, HeaderContext, VisibilityState } from '@tanstack/vue-table';
2
+ import type { VNode } from 'vue';
2
3
  import type { DataTableDensityPreset, DataTableSizePreset, DataTableTreeSelectionStrategy } from '../../../types/data-table';
3
4
  import type { DataTableProps } from '../../../types/data-table/component';
4
5
  export declare const DENSITY_PRESETS: Record<DataTableDensityPreset, {
@@ -30,8 +31,12 @@ export interface ResolvedColumnState<T> {
30
31
  subRowSelection?: boolean;
31
32
  allColumnIds: string[];
32
33
  }
34
+ /** 列表头插槽渲染器,键为 `<columnId>-header` */
35
+ export type HeaderSlotMap<T> = Record<string, ((ctx: HeaderContext<T, unknown>) => VNode[]) | undefined>;
33
36
  export interface ResolveContext<T> {
34
37
  options: DataTableProps<T>;
38
+ /** 用户提供的表头插槽,命中列 id 时取代该列 header 标签 */
39
+ headerSlots?: HeaderSlotMap<T>;
35
40
  density: ColumnMeta<T, unknown>['class'] | null;
36
41
  pinning: ColumnPinningState;
37
42
  visibility: VisibilityState;
@@ -1,4 +1,4 @@
1
1
  import type { DataTableColumn } from '../../../types/data-table';
2
- import type { ResolvedColumnState } from './constants';
2
+ import type { HeaderSlotMap, ResolvedColumnState } from './constants';
3
3
  import type { DataTableProps } from '../../../types/data-table/component';
4
- export declare function resolveColumns<T>(columns: DataTableColumn<T>[], options: DataTableProps<T>): ResolvedColumnState<T>;
4
+ export declare function resolveColumns<T>(columns: DataTableColumn<T>[], options: DataTableProps<T>, headerSlots?: HeaderSlotMap<T>): ResolvedColumnState<T>;
@@ -29,10 +29,11 @@ function resolveColumn(col, ctx, inheritedFixed) {
29
29
  }
30
30
  return col;
31
31
  }
32
- export function resolveColumns(columns, options) {
32
+ export function resolveColumns(columns, options, headerSlots) {
33
33
  let groupCounter = 0;
34
34
  const ctx = {
35
35
  options,
36
+ headerSlots,
36
37
  density: options.density ? isString(options.density) ? DENSITY_PRESETS[options.density] : options.density : null,
37
38
  pinning: { left: [], right: [] },
38
39
  visibility: {},
@@ -1,4 +1,4 @@
1
- import { h, isVNode } from "vue";
1
+ import { Fragment, h, isVNode } from "vue";
2
2
  import { resolveCallbackValue, resolveColumnFlag, resolveTemplate } from "./utils.js";
3
3
  import DataTableCellTooltip from "../components/CellTooltip.vue";
4
4
  import { UButton } from "#components";
@@ -112,7 +112,7 @@ export function renderHeaderActions(ctx, col, options, label, sortable, pinable,
112
112
  const leading = actions.filter((a) => a.position === "leading").map((a) => a.render(ctx));
113
113
  const trailing = actions.filter((a) => a.position === "trailing").map((a) => a.render(ctx));
114
114
  const resizeHandle = resizable ? buildResizeHandle(ctx, options) : null;
115
- const labelNode = isVNode(label) ? label : h("span", { class: "truncate" }, String(label ?? ""));
115
+ const labelNode = Array.isArray(label) ? h(Fragment, label) : isVNode(label) ? label : h("span", { class: "truncate" }, String(label ?? ""));
116
116
  return h("div", { class: "flex items-center gap-1 group" }, [
117
117
  ...leading,
118
118
  labelNode,
@@ -133,9 +133,10 @@ export function resolveDataColumn(col, ctx, inheritedFixed) {
133
133
  if (col.visibility === false) ctx.visibility[id] = false;
134
134
  ctx.allColumnIds.push(id);
135
135
  const cellRenderer = buildDataCellRenderer(col, options);
136
+ const headerSlot = ctx.headerSlots?.[`${id}-header`];
136
137
  const def = {
137
138
  accessorKey: id,
138
- header: effectiveSortable || effectivePinable || effectiveResizable ? (hctx) => renderHeaderActions(hctx, col, options, col.header ?? id, effectiveSortable, effectivePinable, effectiveResizable) : col.header ?? id,
139
+ header: effectiveSortable || effectivePinable || effectiveResizable ? (hctx) => renderHeaderActions(hctx, col, options, headerSlot ? headerSlot(hctx) : col.header ?? id, effectiveSortable, effectivePinable, effectiveResizable) : headerSlot ? (hctx) => headerSlot(hctx) : col.header ?? id,
139
140
  ...col.minSize != null && { minSize: col.minSize },
140
141
  ...col.maxSize != null && { maxSize: col.maxSize },
141
142
  ...resolvedSize != null && { size: resolvedSize },
@@ -42,10 +42,11 @@ function buildSpecialColumnDef(col, type, ctx, render) {
42
42
  ctx.flags.hasResizing ||= effectiveResizable;
43
43
  const effectiveAlign = col.align ?? defaults.align;
44
44
  const alignClass = resolveAlignClass(effectiveAlign);
45
+ const headerSlot = ctx.headerSlots?.[`${id}-header`];
45
46
  const resolvedHeader = effectivePinable || effectiveResizable ? (hctx) => {
46
- const label = isFunction(render.header) ? render.header(hctx) : render.header ?? "";
47
+ const label = headerSlot ? headerSlot(hctx) : isFunction(render.header) ? render.header(hctx) : render.header ?? "";
47
48
  return renderHeaderActions(hctx, col, options, label, false, effectivePinable, effectiveResizable);
48
- } : render.header;
49
+ } : headerSlot ? (hctx) => headerSlot(hctx) : render.header;
49
50
  const classMeta = buildClassMeta(density, alignClass, effectiveResizable, defaults.tdClass);
50
51
  const checkboxClass = type === "selection" ? {
51
52
  td: [classMeta?.td, "[&:has([role=checkbox])]:px-0"].filter(Boolean).join(" "),
@@ -3,6 +3,7 @@ import { createOnRequest } from "../domains/api/interceptors/request.js";
3
3
  import { createOnResponse } from "../domains/api/interceptors/response.js";
4
4
  import { createOnResponseError } from "../domains/api/interceptors/error.js";
5
5
  import { attachInterceptors } from "../domains/api/interceptors/compose.js";
6
+ import { openEventStream } from "../domains/api/stream.js";
6
7
  import { defineNuxtPlugin, useNuxtApp, useRuntimeConfig } from "#imports";
7
8
  function createEndpointFetch(resolvedConfig, publicConfig, nuxtApp) {
8
9
  const interceptors = {
@@ -35,7 +36,8 @@ export default defineNuxtPlugin(() => {
35
36
  const resolved = resolveEndpointConfig(publicConfig, endpointName, privateEndpoints);
36
37
  const $fetchInstance = createEndpointFetch(resolved, publicConfig, nuxtApp);
37
38
  const apiInstance = Object.assign($fetchInstance, {
38
- use: (endpoint) => getOrCreateEndpoint(endpoint)
39
+ use: (endpoint) => getOrCreateEndpoint(endpoint),
40
+ stream: (url, options) => openEventStream($fetchInstance, url, options)
39
41
  });
40
42
  endpointCache.set(endpointName, apiInstance);
41
43
  return apiInstance;
@@ -2,6 +2,7 @@ import type { $Fetch } from 'nitropack/types';
2
2
  import type { FetchError } from 'ofetch';
3
3
  import type { UseFetchOptions as NuxtUseFetchOptions, AsyncData } from 'nuxt/app';
4
4
  import type { RequestToastOptions, ApiError } from './response';
5
+ import type { ApiStreamOptions } from './stream';
5
6
  /**
6
7
  * 端点名声明合并入口
7
8
  * @description 构建期由模块按 nuxt.config 的 movk.api.endpoints 自动注入;
@@ -21,6 +22,11 @@ export type MovkApiEndpointName = keyof MovkApiEndpoints & string;
21
22
  export type ApiInstance = $Fetch & {
22
23
  /** 切换到指定端点,返回该端点的 $fetch 实例 */
23
24
  use: (endpoint: MovkApiEndpointName) => ApiInstance;
25
+ /**
26
+ * 发起 SSE 流式请求,返回逐条产出分片的异步迭代器
27
+ * @description 复用当前端点的 baseURL、鉴权头、业务码校验与 hook
28
+ */
29
+ stream: <T = unknown>(url: string, options?: ApiStreamOptions<T>) => Promise<AsyncGenerator<T>>;
24
30
  };
25
31
  /**
26
32
  * useApiFetch 选项类型
@@ -3,3 +3,4 @@ export type { MovkApiPublicConfig } from './module';
3
3
  export type { ApiError, ApiResponse, RequestToastOptions } from './response';
4
4
  export type { ApiInstance, MovkApiEndpointName, MovkApiEndpoints, UseApiFetchOptions, UseApiFetchReturn } from './fetch';
5
5
  export type { TransferRequestOptions, TransferResult, TransferStatus } from './transfer';
6
+ export type { ApiStreamOptions, ApiStreamStatus, EventStreamOptions, UseApiStreamOptions } from './stream';
@@ -0,0 +1,34 @@
1
+ import type { FetchOptions } from 'ofetch';
2
+ import type { ApiError } from './response';
3
+ import type { MovkApiEndpointName } from './fetch';
4
+ /**
5
+ * SSE 事件解析选项
6
+ */
7
+ export interface EventStreamOptions<T> {
8
+ /**
9
+ * 把单条 SSE 事件的 data 解析成分片,返回 undefined 则丢弃该条
10
+ * @defaultValue 容错的 `JSON.parse`,解析失败静默丢弃
11
+ */
12
+ parse?: (data: string) => T | undefined;
13
+ }
14
+ /**
15
+ * `$api.stream()` 选项
16
+ *
17
+ * @description 刻意不预设 `Accept` 与 `responseType`:
18
+ * - 部分网关(如 DRF)按 `Accept` 做内容协商,收到 `text/event-stream` 会直接拒掉整个请求
19
+ * - 不强制 `responseType: 'stream'` 才能让 JSON 错误信封走完业务码校验;网关把流标成非 SSE 类型时再显式传
20
+ */
21
+ export type ApiStreamOptions<T = unknown> = FetchOptions & EventStreamOptions<T>;
22
+ /**
23
+ * 流式请求状态
24
+ */
25
+ export type ApiStreamStatus = 'idle' | 'streaming' | 'success' | 'error' | 'aborted';
26
+ /**
27
+ * `useApiStream()` 单次请求选项
28
+ */
29
+ export type UseApiStreamOptions<T = unknown> = ApiStreamOptions<T> & {
30
+ /** 使用的端点名称,默认走 defaultEndpoint */
31
+ endpoint?: MovkApiEndpointName;
32
+ /** 失败回调;主动中止不触发 */
33
+ onError?: (error: ApiError | Error) => void;
34
+ };
File without changes
@@ -1,4 +1,4 @@
1
- import type { CellContext, ColumnDefTemplate, ColumnMeta, PaginationState, Row, Table, TableMeta } from '@tanstack/vue-table';
1
+ import type { CellContext, ColumnDefTemplate, ColumnMeta, HeaderContext, PaginationState, Row, Table, TableMeta } from '@tanstack/vue-table';
2
2
  import type { ButtonProps, TableData, TableProps, TableRow, TooltipProps } from '@nuxt/ui';
3
3
  import type { FirstParameter, OmitByKey } from '@movk/core';
4
4
  import type { VNode } from 'vue';
@@ -180,7 +180,7 @@ export interface DataTablePaginationSlotProps<T extends TableData> {
180
180
  setPage: (page: number) => void;
181
181
  setPageSize: (pageSize: unknown) => void;
182
182
  }
183
- export interface DataTableSlots<T extends TableData> {
183
+ interface DataTableNamedSlots<T extends TableData> {
184
184
  'expanded'(props: {
185
185
  row: Row<T>;
186
186
  }): VNode[];
@@ -193,3 +193,11 @@ export interface DataTableSlots<T extends TableData> {
193
193
  'pagination-summary'(props: FirstParameter<DataTablePaginationSlots<T>['summary']>): VNode[];
194
194
  'pagination-actions'(props: FirstParameter<DataTablePaginationSlots<T>['actions']>): VNode[];
195
195
  }
196
+ /**
197
+ * 按列 id 命名的动态插槽,转发至 UTable:
198
+ * `<id>-header` 由 MDataTable 注入列表头标签位(排序/固定按钮与 resize 手柄保留),
199
+ * `<id>-cell` / `<id>-footer` 整体替换单元格与表尾内容
200
+ */
201
+ type DataTableColumnSlots<T extends TableData> = Record<`${string}-header` | `${string}-footer`, (props: HeaderContext<T, unknown>) => VNode[]> & Record<`${string}-cell`, (props: CellContext<T, unknown>) => VNode[]>;
202
+ export type DataTableSlots<T extends TableData> = DataTableNamedSlots<T> & Partial<DataTableColumnSlots<T>>;
203
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@movk/nuxt",
3
3
  "type": "module",
4
- "version": "1.7.2",
4
+ "version": "1.8.1",
5
5
  "packageManager": "pnpm@11.22.0",
6
6
  "description": "An engineering suite built on Nuxt UI: schema-driven AutoForm (Zod v4), a full-featured DataTable, standalone UI components and composables. Get the full capabilities — including API integration with auth & progress — in Nuxt 4, and use its UI, forms, tables and theming in plain Vue + Vite via the Vite plugin.",
7
7
  "author": "YiXuan <mhaibaraai@gmail.com>",
@@ -56,6 +56,10 @@
56
56
  "./vue-plugin": {
57
57
  "types": "./vue-plugin.d.ts"
58
58
  },
59
+ "./ai": {
60
+ "types": "./dist/runtime/domains/ai/index.d.ts",
61
+ "import": "./dist/runtime/domains/ai/index.js"
62
+ },
59
63
  "./runtime/*": "./dist/runtime/*",
60
64
  "./components/*": "./dist/runtime/components/*",
61
65
  "./composables": {
@@ -80,6 +84,9 @@
80
84
  "components/*": [
81
85
  "./dist/runtime/components/*"
82
86
  ],
87
+ "ai": [
88
+ "./dist/runtime/domains/ai/index.d.ts"
89
+ ],
83
90
  "composables": [
84
91
  "./dist/runtime/composables/index.d.ts"
85
92
  ],
@@ -103,8 +110,14 @@
103
110
  ],
104
111
  "peerDependencies": {
105
112
  "@nuxt/ui": ">=4.6.0",
113
+ "ai": "^6 || ^7",
106
114
  "zod": ">=4.3.6"
107
115
  },
116
+ "peerDependenciesMeta": {
117
+ "ai": {
118
+ "optional": true
119
+ }
120
+ },
108
121
  "scripts": {
109
122
  "prepack": "pnpm build",
110
123
  "build": "nuxt-module-build build",
@@ -133,6 +146,7 @@
133
146
  "@vueuse/nuxt": "^14.4.0",
134
147
  "colortranslator": "^6.1.1",
135
148
  "defu": "^6.1.7",
149
+ "eventsource-parser": "^4.0.0",
136
150
  "magic-string": "^1.2.0",
137
151
  "maska": "^3.2.0",
138
152
  "mlly": "^1.8.2",
@@ -156,6 +170,7 @@
156
170
  "@nuxt/module-builder": "^1.0.3",
157
171
  "@nuxt/schema": "^4.5.2",
158
172
  "@release-it/conventional-changelog": "^12.0.0",
173
+ "ai": "^7.0.68",
159
174
  "eslint": "^10.8.1",
160
175
  "happy-dom": "^20.11.2",
161
176
  "nuxt": "^4.5.2",