From b997de44a2c5afc24ffb29e6234a6c794d51b6f1 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Fri, 23 Oct 2026 13:04:33 +0800 Subject: [PATCH] fix(sdk): restore native ESM imports and action exports --- AGENTS.md | 1 + packages/onebot/tests/sdk-actions.test.ts | 22 ++ packages/sdk/CHANGELOG.md | 2 + packages/sdk/VERSIONING.md | 6 +- packages/sdk/src/actions.ts | 222 ++++++++++++++++++++ packages/sdk/src/client/api-client.ts | 6 +- packages/sdk/src/client/http-client.ts | 10 +- packages/sdk/src/client/index.ts | 10 +- packages/sdk/src/client/websocket-client.ts | 20 +- packages/sdk/src/client/websocket-types.ts | 2 +- packages/sdk/src/client/websocket-utils.ts | 4 +- packages/sdk/src/errors.ts | 2 +- packages/sdk/src/events/command.ts | 4 +- packages/sdk/src/events/context.ts | 8 +- packages/sdk/src/events/guards.ts | 4 +- packages/sdk/src/events/index.ts | 8 +- packages/sdk/src/events/types.ts | 4 +- packages/sdk/src/index.ts | 22 +- packages/sdk/src/internal/abort.ts | 2 +- packages/sdk/src/internal/json.ts | 2 +- packages/sdk/src/messages/chain.ts | 6 +- packages/sdk/src/messages/cq-format.ts | 2 +- packages/sdk/src/messages/cq.ts | 8 +- packages/sdk/src/messages/index.ts | 10 +- packages/sdk/src/messages/segments.ts | 2 +- packages/sdk/src/types/actions.ts | 6 +- packages/sdk/src/types/events.ts | 2 +- packages/sdk/src/types/index.ts | 12 +- packages/sdk/src/types/messages.ts | 2 +- packages/sdk/src/types/params.ts | 2 +- packages/sdk/src/types/results.ts | 2 +- packages/sdk/tests/package.test.ts | 146 +++++++++++++ packages/sdk/tsconfig.json | 2 + 33 files changed, 482 insertions(+), 81 deletions(-) create mode 100644 packages/onebot/tests/sdk-actions.test.ts create mode 100644 packages/sdk/src/actions.ts create mode 100644 packages/sdk/tests/package.test.ts diff --git a/AGENTS.md b/AGENTS.md index cb21372e..623661e2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,6 +74,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful - **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose. - **Shared types or actions:** run workspace typechecking as well as behavior tests. A passing Vitest run does not prove type correctness. +- **SDK packaging:** keep the SDK's `NodeNext` build and explicit `.js` relative imports, including type-only exports. Its package tests compile fresh output and check native Node.js imports and consumer declarations. The SDK action catalog must match OneBot's executable names; `packages/onebot/tests/sdk-actions.test.ts` checks this without adding a runtime dependency on server code. - **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test. - **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check. - **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client. diff --git a/packages/onebot/tests/sdk-actions.test.ts b/packages/onebot/tests/sdk-actions.test.ts new file mode 100644 index 00000000..18ed13a6 --- /dev/null +++ b/packages/onebot/tests/sdk-actions.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest'; +import { SNOWLUMA_ACTIONS, isSnowLumaAction } from '../../sdk/src/actions.js'; +import { ACTION_REGISTRY } from '../src/actions'; + +describe('SDK action catalog compatibility', () => { + it('covers every executable name, including aliases and raw actions, exactly once', () => { + const registered = ACTION_REGISTRY.executableNames.map(({ name }) => name); + expect([...SNOWLUMA_ACTIONS].sort()).toEqual(registered.sort()); + expect(new Set(SNOWLUMA_ACTIONS).size).toBe(SNOWLUMA_ACTIONS.length); + + for (const name of registered) { + expect(isSnowLumaAction(name), name).toBe(true); + } + }); + + it.each(['', 'consumer_extension', 'SEND_GROUP_MSG', 'send_group_msg '])( + 'does not recognize unregistered name %j', + (name) => { + expect(isSnowLumaAction(name)).toBe(false); + }, + ); +}); diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md index ef1df81d..bb07adee 100644 --- a/packages/sdk/CHANGELOG.md +++ b/packages/sdk/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Fix native Node.js ESM imports for the package root and all supported subpaths without requiring a bundler. +- Restore `@snowluma/sdk/actions` and the root exports `SNOWLUMA_ACTIONS`, `isSnowLumaAction`, and `SnowLumaKnownAction`, including current action names and compatibility aliases. - Require patched Node.js releases: 24.22.1 or newer in the 24.x line, or 26.12.1 and newer. ## 2.0.0 diff --git a/packages/sdk/VERSIONING.md b/packages/sdk/VERSIONING.md index 081c21b6..78519083 100644 --- a/packages/sdk/VERSIONING.md +++ b/packages/sdk/VERSIONING.md @@ -13,6 +13,8 @@ SDK and application versions are synchronized by `pnpm bump ` from the The current Node.js requirement is `^24.22.1 || >=26.12.1`. Use the repository's `.node-version` for development and builds. +The SDK is an ES module package that supports native Node.js imports and bundler consumers. Its build uses `NodeNext`; relative source imports and re-exports must use `.js` specifiers so both emitted JavaScript and declarations resolve without a bundler. Package tests compile fresh output, load every runtime entry point with Node.js, and typecheck consumers with both NodeNext and bundler resolution. + - Major: removes or changes a public export, changes runtime behavior incompatibly, changes supported Node version, or changes package subpaths. - Minor: adds new public API, supports new SnowLuma actions, adds optional parameters, or adds error subclasses. - Patch: fixes bugs, improves docs, narrows implementation details without breaking public types, or updates action metadata without changing call signatures. @@ -37,4 +39,6 @@ If the package version already exists on npm, the workflow skips publishing that ## Action Compatibility -SnowLuma action coverage is synchronized from `packages/onebot/src/actions/*.ts`. Adding an action type is a minor change unless it changes an existing method signature or return type. +`SNOWLUMA_ACTIONS`, `isSnowLumaAction`, and `SnowLumaKnownAction` are available from both `@snowluma/sdk` and `@snowluma/sdk/actions`. The catalog includes this release's executable action names, compatibility aliases, and raw actions. OneBot's registry tests verify that the SDK catalog stays aligned with the server; the published SDK does not import server code. + +This local catalog is not a capability check against a connected server. Detailed parameter and result types remain in `SnowLumaActionMap`; knowing an action name does not imply it has a specialized type mapping. Custom actions remain supported through `raw()`. Adding an action type is a minor change unless it changes an existing method signature or return type. diff --git a/packages/sdk/src/actions.ts b/packages/sdk/src/actions.ts new file mode 100644 index 00000000..983b8d1e --- /dev/null +++ b/packages/sdk/src/actions.ts @@ -0,0 +1,222 @@ +/** + * Action names shipped with this SDK version, including compatibility aliases. + * This is a local catalog, not a capability check against a connected server. + */ +export const SNOWLUMA_ACTIONS = [ + 'get_login_info', + 'get_status', + 'get_version_info', + 'can_send_image', + 'can_send_record', + 'send_msg', + 'send_private_msg', + 'send_group_msg', + 'get_msg', + 'delete_msg', + 'get_friend_list', + 'get_stranger_info', + 'delete_friend', + 'get_group_list', + 'get_group_info', + 'get_group_member_list', + 'get_group_member_info', + 'get_group_honor_info', + 'get_group_system_msg', + 'set_group_kick', + 'set_group_kick_members', + 'set_group_ban', + 'set_group_whole_ban', + 'set_group_add_option', + 'set_group_search', + 'set_group_admin', + 'set_group_card', + 'set_group_name', + 'set_group_leave', + 'set_group_special_title', + 'set_group_anonymous', + 'set_group_anonymous_ban', + 'set_group_portrait', + 'upload_group_file', + 'upload_private_file', + 'get_group_file_url', + 'get_group_root_files', + 'get_group_files_by_folder', + 'delete_group_file', + 'move_group_file', + 'create_group_file_folder', + 'delete_group_file_folder', + 'rename_group_file_folder', + 'get_private_file_url', + 'set_friend_add_request', + 'set_group_add_request', + 'send_like', + 'friend_poke', + 'group_poke', + 'send_poke', + 'set_essence_msg', + 'delete_essence_msg', + 'get_essence_msg_list', + 'set_group_reaction', + 'get_group_msg_history', + 'get_friend_msg_history', + 'mark_group_msg_as_read', + 'mark_private_msg_as_read', + 'mark_msg_as_read', + 'get_rkey', + 'ocr_image', + '.ocr_image', + '_send_group_notice', + '_get_group_notice', + '_del_group_notice', + 'upload_forward_msg', + 'upload_foward_msg', + 'send_forward_msg', + 'send_group_forward_msg', + 'send_private_forward_msg', + 'get_forward_msg', + 'get_image', + 'get_record', + 'get_cookies', + 'get_csrf_token', + 'get_credentials', + 'set_restart', + 'clean_cache', + '.handle_quick_operation', + 'set_friend_remark', + 'set_group_remark', + 'set_msg_emoji_like', + '_mark_all_as_read', + 'get_group_file_system_info', + 'check_url_safely', + 'download_file', + 'set_qq_profile', + 'set_online_status', + 'get_group_ignored_notifies', + 'get_group_shut_list', + 'forward_friend_single_msg', + 'forward_group_single_msg', + 'get_recent_contact', + 'get_profile_like', + 'fetch_custom_face', + 'get_emoji_likes', + 'fetch_emoji_like', + 'get_friends_with_category', + 'get_online_clients', + '_get_model_show', + '_set_model_show', + '.get_word_slices', + 'get_group_at_all_remain', + 'get_unidirectional_friend_list', + 'set_self_longnick', + 'get_collection_list', + 'create_collection', + 'set_qq_avatar', + 'set_input_status', + 'translate_en2zh', + 'get_clientkey', + 'get_mini_app_ark', + 'click_inline_keyboard_button', + 'set_group_sign', + 'send_group_sign', + 'get_group_info_ex', + 'get_group_detail_info', + 'trans_group_file', + 'rename_group_file', + 'get_file', + '.send_packet', + 'send_packet', + 'bot_exit', + 'nc_get_packet_status', + 'nc_get_rkey', + 'nc_get_user_status', + 'get_group_ignore_add_request', + 'delete_group_folder', + 'set_group_todo', + 'complete_group_todo', + 'cancel_group_todo', + 'set_diy_online_status', + 'get_ai_characters', + 'get_ai_record', + 'send_group_ai_record', + '_get_friend_dress', + 'add_custom_face', + 'add_group_tag', + 'cancel_group_album_media_like', + 'clean_stream_temp_file', + 'comment_qzone', + 'create_flash_task', + 'del_group_album_media', + 'delete_custom_face', + 'delete_flash_file', + 'delete_group_tag', + 'delete_qzone_msg', + 'do_group_album_comment', + 'download_file_image_stream', + 'download_file_record_stream', + 'download_file_stream', + 'download_fileset', + 'fetch_custom_face_detail', + 'fetch_face_entity', + 'fetch_ptt_text', + 'get_ptt_text', + 'get_record_text', + 'fetch_super_face_id', + 'fetch_sys_faces', + 'get_doubt_friends_add_request', + 'get_fileset_id', + 'get_fileset_info', + 'get_flash_file_list', + 'get_flash_file_url', + 'get_group_admin_settings', + 'get_group_album_list', + 'get_group_album_media_list', + 'get_group_share_link', + 'get_group_signed_list', + 'get_group_tags', + 'get_group_todo_list', + 'get_msg_emoji_likes', + 'get_qun_album_list', + 'get_qzone_feeds', + 'get_qzone_msg_detail', + 'get_qzone_msg_list', + 'get_rkey_server', + 'get_share_link', + 'like_qzone', + 'list_filesets', + 'modify_custom_face', + 'move_custom_face_to_front', + 'rename_flash_file', + 'request_decrypt_key', + 'search_sys_faces', + 'send_ark_share', + 'send_custom_face', + 'send_flash_msg', + 'send_group_ark_share', + 'send_qzone_msg', + 'send_tuwen_ark', + 'set_doubt_friends_add_request', + 'set_friends_category', + 'set_group_album_media_like', + 'set_group_member_invite_policy', + 'set_group_member_permissions', + 'set_group_new_member_history_visibility', + 'set_group_robot_add_option', + 'set_qzone_ban', + 'set_qzone_msg_right', + 'share_group_ex', + 'share_peer', + 'test_download_stream', + 'unlike_qzone', + 'upload_file_stream', + 'upload_image_to_qun_album', + 'upload_video_to_qun_album', + '.handle_quick_operation_async', +] as const; + +export type SnowLumaKnownAction = (typeof SNOWLUMA_ACTIONS)[number]; + +const ACTION_SET = new Set(SNOWLUMA_ACTIONS); + +export function isSnowLumaAction(action: string): action is SnowLumaKnownAction { + return ACTION_SET.has(action); +} diff --git a/packages/sdk/src/client/api-client.ts b/packages/sdk/src/client/api-client.ts index b7e46bf0..f2bf8dfe 100644 --- a/packages/sdk/src/client/api-client.ts +++ b/packages/sdk/src/client/api-client.ts @@ -1,5 +1,5 @@ -import { createSnowLumaApiError } from '../errors'; -import { normalizeMessage } from '../messages/index'; +import { createSnowLumaApiError } from '../errors.js'; +import { normalizeMessage } from '../messages/index.js'; import type { ActionParams, ActionResult, @@ -19,7 +19,7 @@ import type { SendMsgParams, SetGroupReactionParams, SnowLumaAction, -} from '../types/index'; +} from '../types/index.js'; /** * Base class for SnowLuma API clients. diff --git a/packages/sdk/src/client/http-client.ts b/packages/sdk/src/client/http-client.ts index 1c51d0f1..522c07ba 100644 --- a/packages/sdk/src/client/http-client.ts +++ b/packages/sdk/src/client/http-client.ts @@ -4,10 +4,10 @@ import { SnowLumaParseError, SnowLumaTimeoutError, SnowLumaTransportError, -} from '../errors'; -import { SnowLumaApiClient, toJsonObject } from './api-client'; -import { createRequestAbortState, isAbortError } from '../internal/abort'; -import { assertApiResponse } from '../internal/json'; +} from '../errors.js'; +import { SnowLumaApiClient, toJsonObject } from './api-client.js'; +import { createRequestAbortState, isAbortError } from '../internal/abort.js'; +import { assertApiResponse } from '../internal/json.js'; import type { ActionParams, ActionResult, @@ -16,7 +16,7 @@ import type { RequestOptions, SnowLumaAction, SnowLumaClientOptions, -} from '../types/index'; +} from '../types/index.js'; /** Options for the HTTP transport client. */ export interface SnowLumaHttpClientOptions extends SnowLumaClientOptions { diff --git a/packages/sdk/src/client/index.ts b/packages/sdk/src/client/index.ts index 72bb88ae..20d07bfe 100644 --- a/packages/sdk/src/client/index.ts +++ b/packages/sdk/src/client/index.ts @@ -1,12 +1,12 @@ -export { SnowLumaApiClient } from './api-client'; -export { SnowLumaHttpClient, createHttpClient } from './http-client'; -export { SnowLumaWebSocketClient, createWebSocketClient } from './websocket-client'; +export { SnowLumaApiClient } from './api-client.js'; +export { SnowLumaHttpClient, createHttpClient } from './http-client.js'; +export { SnowLumaWebSocketClient, createWebSocketClient } from './websocket-client.js'; -export type { SnowLumaHttpClientOptions } from './http-client'; +export type { SnowLumaHttpClientOptions } from './http-client.js'; export type { ReconnectOptions, SnowLumaWebSocketClientOptions, SnowLumaWebSocketEvents, WebSocketCloseInfo, WebSocketConstructor, -} from './websocket-client'; +} from './websocket-client.js'; diff --git a/packages/sdk/src/client/websocket-client.ts b/packages/sdk/src/client/websocket-client.ts index 2dc9af57..e9d6a193 100644 --- a/packages/sdk/src/client/websocket-client.ts +++ b/packages/sdk/src/client/websocket-client.ts @@ -3,8 +3,8 @@ import { SnowLumaConnectionError, SnowLumaParseError, SnowLumaTimeoutError, -} from '../errors'; -import { Emitter } from '../emitter'; +} from '../errors.js'; +import { Emitter } from '../emitter.js'; import { createEventContext, isBotStatusEvent, @@ -22,16 +22,16 @@ import { type EventHandler, type EventMiddleware, type EventPredicate, -} from '../events/index'; -import { SnowLumaApiClient, toJsonObject } from './api-client'; -import { raceWithAbort, throwIfAborted } from '../internal/abort'; +} from '../events/index.js'; +import { SnowLumaApiClient, toJsonObject } from './api-client.js'; +import { raceWithAbort, throwIfAborted } from '../internal/abort.js'; import { appendAccessToken, assertApiResponse, createEcho, echoKey, isJsonObject, -} from '../internal/json'; +} from '../internal/json.js'; import { addSocketListener, closeInfo, @@ -41,7 +41,7 @@ import { unwrapMessagePayload, WEBSOCKET_CLOSED, WEBSOCKET_OPEN, -} from './websocket-utils'; +} from './websocket-utils.js'; import type { ActionParams, ActionResult, @@ -57,14 +57,14 @@ import type { SnowLumaAction, SnowLumaEvent, WsRole, -} from '../types/index'; +} from '../types/index.js'; import type { ReconnectOptions, SnowLumaWebSocketClientOptions, SnowLumaWebSocketEvents, WebSocketConstructor, WebSocketLike, -} from './websocket-types'; +} from './websocket-types.js'; export type { ReconnectOptions, @@ -72,7 +72,7 @@ export type { SnowLumaWebSocketEvents, WebSocketCloseInfo, WebSocketConstructor, -} from './websocket-types'; +} from './websocket-types.js'; interface SocketConnection { socket: WebSocketLike; diff --git a/packages/sdk/src/client/websocket-types.ts b/packages/sdk/src/client/websocket-types.ts index 6f73f62a..b67636c2 100644 --- a/packages/sdk/src/client/websocket-types.ts +++ b/packages/sdk/src/client/websocket-types.ts @@ -1,4 +1,4 @@ -import type { ApiResponse, SnowLumaClientOptions, SnowLumaEvent, WsRole } from '../types/index'; +import type { ApiResponse, SnowLumaClientOptions, SnowLumaEvent, WsRole } from '../types/index.js'; export interface WebSocketLike { readyState: number; diff --git a/packages/sdk/src/client/websocket-utils.ts b/packages/sdk/src/client/websocket-utils.ts index 1513f68c..f9313823 100644 --- a/packages/sdk/src/client/websocket-utils.ts +++ b/packages/sdk/src/client/websocket-utils.ts @@ -1,5 +1,5 @@ -import { isJsonObject } from '../internal/json'; -import type { ReconnectOptions, WebSocketCloseInfo, WebSocketLike } from './websocket-types'; +import { isJsonObject } from '../internal/json.js'; +import type { ReconnectOptions, WebSocketCloseInfo, WebSocketLike } from './websocket-types.js'; export const WEBSOCKET_OPEN = 1; export const WEBSOCKET_CLOSED = 3; diff --git a/packages/sdk/src/errors.ts b/packages/sdk/src/errors.ts index c6bfe79b..054f25d1 100644 --- a/packages/sdk/src/errors.ts +++ b/packages/sdk/src/errors.ts @@ -1,4 +1,4 @@ -import type { ApiResponse } from './types/index'; +import type { ApiResponse } from './types/index.js'; /** Base error for every exception intentionally thrown by the SnowLuma SDK. */ export class SnowLumaError extends Error { diff --git a/packages/sdk/src/events/command.ts b/packages/sdk/src/events/command.ts index 1f9c517a..907aa4cd 100644 --- a/packages/sdk/src/events/command.ts +++ b/packages/sdk/src/events/command.ts @@ -1,5 +1,5 @@ -import type { OneBotMessageEvent } from '../types/index'; -import type { CommandMatch, CommandOptions } from './types'; +import type { OneBotMessageEvent } from '../types/index.js'; +import type { CommandMatch, CommandOptions } from './types.js'; export function matchCommand( event: OneBotMessageEvent, diff --git a/packages/sdk/src/events/context.ts b/packages/sdk/src/events/context.ts index 718e8acf..6f1f8795 100644 --- a/packages/sdk/src/events/context.ts +++ b/packages/sdk/src/events/context.ts @@ -1,7 +1,7 @@ -import type { SnowLumaApiClient } from '../client/api-client'; -import type { SnowLumaEvent } from '../types/index'; -import { isGroupMessageEvent, isPrivateMessageEvent, isRequestEvent } from './guards'; -import type { SnowLumaEventContext } from './types'; +import type { SnowLumaApiClient } from '../client/api-client.js'; +import type { SnowLumaEvent } from '../types/index.js'; +import { isGroupMessageEvent, isPrivateMessageEvent, isRequestEvent } from './guards.js'; +import type { SnowLumaEventContext } from './types.js'; export function createEventContext( event: TEvent, diff --git a/packages/sdk/src/events/guards.ts b/packages/sdk/src/events/guards.ts index e149c920..25833d58 100644 --- a/packages/sdk/src/events/guards.ts +++ b/packages/sdk/src/events/guards.ts @@ -7,8 +7,8 @@ import type { OneBotPrivateMessageEvent, OneBotRequestEvent, SnowLumaEvent, -} from '../types/index'; -import type { EventPredicate } from './types'; +} from '../types/index.js'; +import type { EventPredicate } from './types.js'; export function isMessageEvent(event: SnowLumaEvent): event is OneBotMessageEvent { return ( diff --git a/packages/sdk/src/events/index.ts b/packages/sdk/src/events/index.ts index 41a5a1a0..70d95024 100644 --- a/packages/sdk/src/events/index.ts +++ b/packages/sdk/src/events/index.ts @@ -1,4 +1,4 @@ -export * from './types'; -export * from './guards'; -export * from './context'; -export * from './command'; +export * from './types.js'; +export * from './guards.js'; +export * from './context.js'; +export * from './command.js'; diff --git a/packages/sdk/src/events/types.ts b/packages/sdk/src/events/types.ts index ac3e0821..c2ecb6e0 100644 --- a/packages/sdk/src/events/types.ts +++ b/packages/sdk/src/events/types.ts @@ -1,11 +1,11 @@ -import type { SnowLumaApiClient } from '../client/api-client'; +import type { SnowLumaApiClient } from '../client/api-client.js'; import type { JsonObject, OneBotMessageEvent, OutgoingMessage, RequestOptions, SnowLumaEvent, -} from '../types/index'; +} from '../types/index.js'; export type MaybePromise = T | Promise; export type EventNext = () => Promise; diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index 33eea5b8..2d6e4811 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -1,7 +1,9 @@ -export { SnowLumaApiClient } from './client/api-client'; -export { createHttpClient, SnowLumaHttpClient } from './client/http-client'; -export type { SnowLumaHttpClientOptions } from './client/http-client'; -export { createWebSocketClient, SnowLumaWebSocketClient } from './client/websocket-client'; +export { SNOWLUMA_ACTIONS, isSnowLumaAction } from './actions.js'; +export type { SnowLumaKnownAction } from './actions.js'; +export { SnowLumaApiClient } from './client/api-client.js'; +export { createHttpClient, SnowLumaHttpClient } from './client/http-client.js'; +export type { SnowLumaHttpClientOptions } from './client/http-client.js'; +export { createWebSocketClient, SnowLumaWebSocketClient } from './client/websocket-client.js'; export { createSnowLumaApiError, SnowLumaAbortError, @@ -12,7 +14,7 @@ export { SnowLumaParseError, SnowLumaTimeoutError, SnowLumaTransportError, -} from './errors'; +} from './errors.js'; export { createEventContext, isBotStatusEvent, @@ -25,7 +27,7 @@ export { matchCommand, noticeType, requestType, -} from './events/index'; +} from './events/index.js'; export { at, atAll, @@ -55,7 +57,7 @@ export { toCQString, video, xml, -} from './messages/index'; +} from './messages/index.js'; export type { ReconnectOptions, @@ -63,7 +65,7 @@ export type { SnowLumaWebSocketEvents, WebSocketCloseInfo, WebSocketConstructor, -} from './client/websocket-client'; +} from './client/websocket-client.js'; export type { CommandHandler, @@ -76,6 +78,6 @@ export type { MaybePromise, RequestDecisionOptions, SnowLumaEventContext, -} from './events/index'; +} from './events/index.js'; -export type * from './types/index'; +export type * from './types/index.js'; diff --git a/packages/sdk/src/internal/abort.ts b/packages/sdk/src/internal/abort.ts index 6f6519bb..a705728c 100644 --- a/packages/sdk/src/internal/abort.ts +++ b/packages/sdk/src/internal/abort.ts @@ -1,4 +1,4 @@ -import { SnowLumaAbortError } from '../errors'; +import { SnowLumaAbortError } from '../errors.js'; export interface RequestAbortState { signal: AbortSignal; diff --git a/packages/sdk/src/internal/json.ts b/packages/sdk/src/internal/json.ts index 18c972ee..c0e14756 100644 --- a/packages/sdk/src/internal/json.ts +++ b/packages/sdk/src/internal/json.ts @@ -1,4 +1,4 @@ -import type { ApiResponse, JsonObject, JsonValue } from '../types/index'; +import type { ApiResponse, JsonObject, JsonValue } from '../types/index.js'; export function isJsonObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); diff --git a/packages/sdk/src/messages/chain.ts b/packages/sdk/src/messages/chain.ts index db287423..f7f9fec9 100644 --- a/packages/sdk/src/messages/chain.ts +++ b/packages/sdk/src/messages/chain.ts @@ -13,9 +13,9 @@ import type { ShareSegment, VideoSegment, XmlSegment, -} from '../types/index'; -import { segmentsToCQString } from './cq-format'; -import { segments } from './segments'; +} from '../types/index.js'; +import { segmentsToCQString } from './cq-format.js'; +import { segments } from './segments.js'; export interface MessageChainSender { sendGroupMessage( diff --git a/packages/sdk/src/messages/cq-format.ts b/packages/sdk/src/messages/cq-format.ts index e15790bc..90af6d4f 100644 --- a/packages/sdk/src/messages/cq-format.ts +++ b/packages/sdk/src/messages/cq-format.ts @@ -1,4 +1,4 @@ -import type { AnyMessageSegment } from '../types/index'; +import type { AnyMessageSegment } from '../types/index.js'; export function escapeCqText(text: string): string { return text.replaceAll('&', '&').replaceAll('[', '[').replaceAll(']', ']'); diff --git a/packages/sdk/src/messages/cq.ts b/packages/sdk/src/messages/cq.ts index 645b438f..809cbd91 100644 --- a/packages/sdk/src/messages/cq.ts +++ b/packages/sdk/src/messages/cq.ts @@ -1,7 +1,7 @@ -import { normalizeMessage, chain } from './chain'; -import { escapeCqText, segmentsToCQString } from './cq-format'; -import { segments } from './segments'; -import type { AnyMessageSegment, FaceSegment, OutgoingMessage } from '../types/index'; +import { normalizeMessage, chain } from './chain.js'; +import { escapeCqText, segmentsToCQString } from './cq-format.js'; +import { segments } from './segments.js'; +import type { AnyMessageSegment, FaceSegment, OutgoingMessage } from '../types/index.js'; const CQ_REGEX = /\[CQ:([a-zA-Z0-9_.-]+)(?:,([^\]]*))?\]/g; diff --git a/packages/sdk/src/messages/index.ts b/packages/sdk/src/messages/index.ts index 04c20035..76c19569 100644 --- a/packages/sdk/src/messages/index.ts +++ b/packages/sdk/src/messages/index.ts @@ -1,6 +1,6 @@ -import { segments } from './segments'; +import { segments } from './segments.js'; -export { MessageChain } from './chain'; +export { MessageChain } from './chain.js'; export { at, atAll, @@ -23,9 +23,9 @@ export { text, video, xml, -} from './chain'; -export { escapeCqParam, escapeCqText } from './cq-format'; -export { fromCQString, parseSegments, toCQString } from './cq'; +} from './chain.js'; +export { escapeCqParam, escapeCqText } from './cq-format.js'; +export { fromCQString, parseSegments, toCQString } from './cq.js'; export { segments }; export const message = { diff --git a/packages/sdk/src/messages/segments.ts b/packages/sdk/src/messages/segments.ts index e2df1b19..38bf5b71 100644 --- a/packages/sdk/src/messages/segments.ts +++ b/packages/sdk/src/messages/segments.ts @@ -19,7 +19,7 @@ import type { TextSegment, VideoSegment, XmlSegment, -} from '../types/index'; +} from '../types/index.js'; function seg>( type: TType, diff --git a/packages/sdk/src/types/actions.ts b/packages/sdk/src/types/actions.ts index ea930409..6146a3e5 100644 --- a/packages/sdk/src/types/actions.ts +++ b/packages/sdk/src/types/actions.ts @@ -1,4 +1,4 @@ -import type { JsonArray, JsonObject, JsonValue } from './json'; +import type { JsonArray, JsonObject, JsonValue } from './json.js'; import type { CreateGroupFileFolderParams, DeleteFriendParams, @@ -79,7 +79,7 @@ import type { SendPacketParams, SearchSysFacesParams, GetQzoneMsgDetailParams, -} from './params'; +} from './params.js'; import type { CapabilityInfo, ClientKeyInfo, @@ -117,7 +117,7 @@ import type { SystemFaceInfo, SystemFaceSearchInfo, QzoneMsgDetailResult, -} from './results'; +} from './results.js'; export type ActionData = JsonValue; diff --git a/packages/sdk/src/types/events.ts b/packages/sdk/src/types/events.ts index 3205d90b..45184c29 100644 --- a/packages/sdk/src/types/events.ts +++ b/packages/sdk/src/types/events.ts @@ -1,4 +1,4 @@ -import type { JsonObject, JsonValue } from './json'; +import type { JsonObject, JsonValue } from './json.js'; export interface OneBotBaseEvent extends JsonObject { time: number; diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts index 2fd63d12..71c4107d 100644 --- a/packages/sdk/src/types/index.ts +++ b/packages/sdk/src/types/index.ts @@ -1,6 +1,6 @@ -export * from './json'; -export * from './messages'; -export * from './results'; -export * from './params'; -export * from './actions'; -export * from './events'; +export * from './json.js'; +export * from './messages.js'; +export * from './results.js'; +export * from './params.js'; +export * from './actions.js'; +export * from './events.js'; diff --git a/packages/sdk/src/types/messages.ts b/packages/sdk/src/types/messages.ts index f422f152..e650f1aa 100644 --- a/packages/sdk/src/types/messages.ts +++ b/packages/sdk/src/types/messages.ts @@ -1,4 +1,4 @@ -import type { JsonObject } from './json'; +import type { JsonObject } from './json.js'; export interface MessageSegment< TType extends string = string, diff --git a/packages/sdk/src/types/params.ts b/packages/sdk/src/types/params.ts index d16968c2..ed336346 100644 --- a/packages/sdk/src/types/params.ts +++ b/packages/sdk/src/types/params.ts @@ -1,4 +1,4 @@ -import type { JsonObject, JsonValue } from './json'; +import type { JsonObject, JsonValue } from './json.js'; export interface SendMsgParams extends JsonObject { message_type?: 'private' | 'group' | string; diff --git a/packages/sdk/src/types/results.ts b/packages/sdk/src/types/results.ts index 60d07c8d..6d6c6819 100644 --- a/packages/sdk/src/types/results.ts +++ b/packages/sdk/src/types/results.ts @@ -1,4 +1,4 @@ -import type { JsonArray, JsonObject, JsonValue } from './json'; +import type { JsonArray, JsonObject, JsonValue } from './json.js'; export interface QzoneCommentReply { uin: number; diff --git a/packages/sdk/tests/package.test.ts b/packages/sdk/tests/package.test.ts new file mode 100644 index 00000000..fa0c1876 --- /dev/null +++ b/packages/sdk/tests/package.test.ts @@ -0,0 +1,146 @@ +import { spawnSync } from 'node:child_process'; +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterAll, beforeAll, describe, it } from 'vitest'; + +const sdkRoot = fileURLToPath(new URL('..', import.meta.url)); +const compiler = createRequire(import.meta.url).resolve('typescript/bin/tsc'); +const manifest = JSON.parse(readFileSync(path.join(sdkRoot, 'package.json'), 'utf8')) as { + name: string; + exports: Record; +}; +const entrypoints = Object.entries(manifest.exports) + .filter(([, target]) => typeof target !== 'string') + .map(([entry]) => `${manifest.name}${entry === '.' ? '' : entry.slice(1)}`); +let consumerRoot: string; + +function node(args: string[]): void { + const result = spawnSync(process.execPath, args, { + cwd: consumerRoot, + encoding: 'utf8', + stdio: 'pipe', + timeout: 30_000, + }); + + if (result.error) { + throw result.error; + } + + if (result.status !== 0) { + throw new Error( + `Node exited with status ${result.status} (signal ${result.signal}):\n${result.stdout}\n${result.stderr}`, + ); + } +} + +beforeAll(() => { + consumerRoot = mkdtempSync(path.join(tmpdir(), 'snowluma-sdk-package-')); + const installed = path.join(consumerRoot, 'node_modules', '@snowluma', 'sdk'); + mkdirSync(installed, { recursive: true }); + copyFileSync(path.join(sdkRoot, 'package.json'), path.join(installed, 'package.json')); + + // Compile fresh output outside the workspace so neither stale dist files nor + // Vitest's source resolver can hide a broken published entry point. + node([ + compiler, + '--project', + path.join(sdkRoot, 'tsconfig.json'), + '--outDir', + path.join(installed, 'dist'), + ]); + writeFileSync( + path.join(consumerRoot, 'consumer.mts'), + `import { SnowLumaHttpClient, text, type SnowLumaKnownAction as RootKnownAction } from '@snowluma/sdk'; +import { SnowLumaWebSocketClient, type SnowLumaHttpClientOptions } from '@snowluma/sdk/client'; +import { MessageChain } from '@snowluma/sdk/messages'; +import { isMessageEvent, type EventMiddleware } from '@snowluma/sdk/events'; +import { SnowLumaApiError } from '@snowluma/sdk/errors'; +import { SNOWLUMA_ACTIONS, isSnowLumaAction, type SnowLumaKnownAction } from '@snowluma/sdk/actions'; +import type { ActionParams, StatusInfo } from '@snowluma/sdk/types'; + +const options: SnowLumaHttpClientOptions = { baseUrl: 'http://127.0.0.1:3000/' }; +const client = new SnowLumaHttpClient(options); +const status: Promise = client.getStatus(); +const message: MessageChain = text('hello').reply(-42); +const params: ActionParams<'send_group_msg'> = { group_id: 123, message: [] }; +client.raw('send_group_msg', params); +client.raw('consumer_extension', { custom: true }); +client.sendGroupMessage(123, message); +const middleware: EventMiddleware = async (event, context, next) => { + if (isMessageEvent(event)) await context.reply(text('received')); + await next(); +}; +new SnowLumaWebSocketClient().use(middleware); +const action: RootKnownAction = SNOWLUMA_ACTIONS[0]; +function known(value: string): SnowLumaKnownAction | null { + return isSnowLumaAction(value) ? value : null; +} +const error = new SnowLumaApiError({ status: 'failed', retcode: 1, data: null }); +export { status, action, known, error }; +`, + ); +}, 30_000); + +afterAll(() => { + if (consumerRoot) { + rmSync(consumerRoot, { recursive: true, force: true }); + } +}); + +describe('SDK package entry points', () => { + it.each(entrypoints)('loads %s in native Node without a bundler', (entrypoint) => { + node(['--input-type=module', '--eval', `await import(${JSON.stringify(entrypoint)});`]); + }); + + it('preserves runtime identities across the root and subpath exports', () => { + node([ + '--input-type=module', + '--eval', + `import assert from 'node:assert/strict'; +import * as sdk from '@snowluma/sdk'; +import * as client from '@snowluma/sdk/client'; +import * as messages from '@snowluma/sdk/messages'; +import * as events from '@snowluma/sdk/events'; +import * as errors from '@snowluma/sdk/errors'; +import * as actions from '@snowluma/sdk/actions'; +assert.equal(sdk.SnowLumaHttpClient, client.SnowLumaHttpClient); +assert.equal(sdk.SnowLumaWebSocketClient, client.SnowLumaWebSocketClient); +assert.equal(sdk.MessageChain, messages.MessageChain); +assert.equal(sdk.isMessageEvent, events.isMessageEvent); +assert.equal(sdk.SnowLumaApiError, errors.SnowLumaApiError); +assert.equal(sdk.SNOWLUMA_ACTIONS, actions.SNOWLUMA_ACTIONS); +assert.equal(sdk.isSnowLumaAction, actions.isSnowLumaAction); +assert.ok(sdk.text('hello') instanceof messages.MessageChain); +assert.equal(actions.isSnowLumaAction('send_group_msg'), true); +assert.equal(actions.isSnowLumaAction('consumer_extension'), false); +`, + ]); + }); + + it.each([ + ['NodeNext', 'NodeNext'], + ['ESNext', 'Bundler'], + ])( + 'typechecks a consumer using %s / %s', + (module, resolution) => { + node([ + compiler, + '--noEmit', + '--strict', + '--target', + 'ES2022', + '--lib', + 'ES2022,DOM', + '--module', + module, + '--moduleResolution', + resolution, + path.join(consumerRoot, 'consumer.mts'), + ]); + }, + 30_000, + ); +}); diff --git a/packages/sdk/tsconfig.json b/packages/sdk/tsconfig.json index 17639fc0..a2e3f6a5 100644 --- a/packages/sdk/tsconfig.json +++ b/packages/sdk/tsconfig.json @@ -1,6 +1,8 @@ { "extends": "../../tsconfig.base.json", "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", "outDir": "./dist", "rootDir": "./src", "declaration": true,