Преглед изворни кода

✨ (api-v13): search-suggest 迁成 /v3/search-suggestions

搜索框前缀补全(OpenSearch completion)按现行 v3 规范重写,路径复数化,旧路径删除。

- SearchSuggestController → V3\SearchSuggestionController,逻辑进 V3\SearchService::suggest
- 响应 {success, data:{query, suggestions, total}} → {data:[…], meta:{total}};空 q 400 → 422
- fields 按真实字段校验(title_pali / title_zh / content_pali / content_zh);
  旧注释写的 title / content / page_refs 一传就 400
- limit 从「每个字段各取」(最多 4 倍)改为总条数,并按词去重
- 去掉 language:completion suggester 忽略 query,从未生效
- completion 只取四个元数据字段,不再逐条带回整篇 _source
- 搜索集群不可用 → 503 search-unavailable
- Library 搜索框切到新路径,顺带修候选文本未转义直接进 innerHTML(XSS)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda пре 17 часа
родитељ
комит
ae4f0a501c

+ 1 - 0
CLAUDE.md

@@ -365,6 +365,7 @@ Resource / FormRequest / 测试同理;URL 只换版本前缀
 | `grammar-guide/{词_语言}` / `GrammarGuideController@show` | (无新端点)`glossaries/grammar` + `terms/{term}`,退回 `terms?word=` | 2026-11-17。语法点悬停说明(v6 `components/dict/GrammarPop.tsx`)。v2 在语法术语系统 channel 里按词查一条、返回 `# 释义\n正文` 的 markdown;v6 改为:启动时已加载的 `/v3/glossaries/grammar` 里按词找 id → `GET /v3/terms/{id}`(新渲染器的 body);表里没有就按词查 `GET /v3/terms?word=&with_body=true`,只认 `_System_Grammar_Term_{界面语言}_`、其次 en 那个 channel 的;都没有显示「暂无…的语法说明」。悬停查询失败不弹全局提示(quiet)。`api/Guide.ts` 已删。顺带修了 `terms?with_body=` 与 `studios/{s}/terms?general=` 收不了查询串 `true`/`false` 的 422 |
 | `nissaya-card/{ending}` / `NissayaCardController@show` | `nissaya-cards/{ending}` / `V3\NissayaCardController`(逻辑在 `V3\NissayaCardService`) | 2026-11-17。缅文 nissaya 词尾卡片(v6 `components/nissaya/NissayaCard`),只读、公开。只给结构化数据:去掉 mustache 渲染的 markdown 分支、写死在后端的表头文字、拼好的 dashboard 链接(前端自己拼);术语一次批量查(v2 逐格位 N+1);词尾说明是新渲染器的 `body` 节点树。字段 `row`→`relations`、`case`→`cases[{case,label}]`、`local_relation`→`relation_label`、`local_ending`(分号拼接)→`local_endings`(数组);查不到的词尾回空卡片(200)。语法术语 channel 没有该语言时回退 en,`lang` 是实际用到的语言。v6 已切;mobile、插件不用 |
 | (无对应 v2 端点;早期 v3)`search`(GET / POST / `{id}`)/ `V3\SearchPlusController` | `search`(不变)/ `V3\SearchController`(逻辑在 `V3\SearchService`) | 2026-11-19,按现行 v3 规范重写(v2 的 `SearchController` 是 PostgreSQL 全文检索,另一套,不受影响)。控制器改名 `SearchPlusController`→`SearchController`;入参走 `IndexSearchRequest`:`q` 必填(不再 `match_all` 全索引),`search_mode` / `resource_type`(`tipitaka`/`original_text`/`term`)/ `granularity`(`book`/`chapter`/`session`/`paragraph`)按索引真实值校验,`page_size`→`per_page`(≤100),`page × per_page` > 10000 时 422(原来 OpenSearch 报错变 500)。响应从 OpenSearch 原始结构 `{success, data:{took, hits, aggregations}, query_info}` 改成 `{data:[hit], meta:{current_page, per_page, total, total_relation, last_page}}`,hit 是扁平字段(`related_id`、`title`、`content`、`highlight`、`bold[]`、`score`…),不再透出 `_source`;分面聚合改为 `facets=true` 才算(`meta.facets`)。错误走 Problem Details:搜索集群连不上 / 超时 / 过载 → 503 `search-unavailable`(原来 catch 后把原始报错 + 500 吐给客户端、且不写日志);`{id}` 只有文档不存在才 404(原来任何异常都 404)。共享的 `OpenSearchService::search()` 加了 `aggregations` 开关(默认 true,Library 与 AITermService 不变),顺带修 `channel` 过滤(text 字段用 term 永远不中→`match_phrase`)与数组 `related_id`(term→terms)。POST 保留(用户定)。wikipali-plugins(`phrase` / `find`)、agent-poc 召回评测脚本已切;v6、mobile 不调用。`search-suggest` 未迁 |
+| (无对应 v2 端点;早期 v3)`search-suggest` / `V3\SearchSuggestController` | `search-suggestions` / `V3\SearchSuggestionController`(逻辑在 `V3\SearchService::suggest`) | 2026-11-19。搜索框前缀补全(OpenSearch completion)。路径复数化,旧路径删除(404);`{success, data:{query, suggestions, total}}`→`{data:[{text, source, score, doc_id, resource_type, language, granularity, category}], meta:{total}}`;空 q 从 400 改 422;`fields` 按真实字段校验(`title_pali`/`title_zh`/`content_pali`/`content_zh`,旧注释写的 title/content/page_refs 一传就 400);`limit` 从「每个字段各取」(实际最多 4 倍)改成总条数,并按词去重;`language` 去掉(completion 忽略 query,从未生效,用户定);completion 只取四个元数据字段,不再逐条带回整篇 `_source`;搜索集群不可用 503。Library 搜索框(`resources/js/search-suggest.js`)已切,顺带修了候选文本未转义直接进 `innerHTML`。v4 的 `ChatInput` 还指着旧路径(线上不可达,不改) |
 
 **注意**:`tipitaka-reading` **不是** v2 `paragraph-content` / `chapter-content` 的替代品。
 那两个 v2 端点支持多 channel(`channels=a,b,c`)与 edit 模式、返回 sentenceIds 供编辑器用;

+ 3 - 4
api-test/README.md

@@ -187,18 +187,17 @@ php run.php --username=<username> --password=<password> --server=staging
 
 | 端点                     | spec 说                                          | 实际                                                                        | 处理                                                                                   |
 | ------------------------ | ------------------------------------------------ | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
-| `GET /v3/search-suggest` | 200 `{data:数组, meta}`;空 q 422                | 200 `{success, data:{query,suggestions}}`;空 q 400 `{success:false,error}` | 同上修 schema;空 q 用例按实际 400 断言                                                |
 | `GET /v3/upgrade`        | 200 `{data:数组, meta}`                          | 200 `{data:{status:"ok"}}`                                                  | 修 schema 为 `{data:对象}`                                                             |
 
-根因是这两个控制器还没迁到 v3 的 Resource 信封(`{data}` 原生形状、错误体 RFC 9457
+根因是这个控制器还没迁到 v3 的 Resource 信封(`{data}` 原生形状、错误体 RFC 9457
 Problem Details、成败只看状态码)。正确的长期修法在 api-v13 侧,这里只让测试客户端能用、
-把漂移显式记录。`filter-v3.php` 里的 `applyDriftPatches()` 就是这两处补丁,改对齐后可删。(`/v3/search` 已于 2026-11-19 对齐,补丁已删。)
+把漂移显式记录。`filter-v3.php` 里的 `applyDriftPatches()` 就是这处补丁,改对齐后可删。(`/v3/search`、`/v3/search-suggestions` 已于 2026-11-19 对齐,补丁已删。)
 
 ## 环境注意
 
 - **pspell / xdebug 启动警告**:本机 PHP CLI 的 pspell 扩展与 PHP 版本不匹配,每次 `php`
   都会在 stderr 打警告,与测试无关,可忽略。
-- **staging 的 OpenSearch**:`/v3/search?facets=true`、`/v3/search-suggest` 在 staging 会 500
+- **staging 的 OpenSearch**:`/v3/search?facets=true`、`/v3/search-suggestions` 在 staging 会 500
   (索引 mapping 与代码不一致:`resource_type` 是 text 不能聚合、`content.suggest.pali` 不是 completion)。
   `/v3/search` 默认不再算聚合,不带 facets 时不受影响。
   这是 staging 环境问题,本地跑这几条是绿的。

+ 21 - 9
api-test/cases/02_search.php

@@ -1,7 +1,7 @@
 <?php
 
 use \WikipaliApi\Api\SearchApi;
-use \WikipaliApi\Api\SearchSuggestApi;
+use \WikipaliApi\Api\SearchSuggestionsApi;
 use \WikipaliApi\Model\PostApiV3SearchRequest;
 
 /** 一条命中必须有的字段(v3 归一化后的形状,不再透出 OpenSearch 的 _source) */
@@ -78,14 +78,26 @@ test('GET /v3/search/{id} → 404(不存在的文档)', function () {
     assert_problem($res, 'search show 404');
 });
 
-test('GET /v3/search-suggest?q=dukkha → 200', function () {
-    $res = request(fn () => api(SearchSuggestApi::class)->getApiV3SearchSuggestWithHttpInfo(fixtures()['search_q']));
-    assert_status(200, $res, 'search-suggest');
-    assert_has_key('data', $res['body'], 'search-suggest');
+test('GET /v3/search-suggestions?q=dukkha → 200 {data, meta}', function () {
+    $res = request(fn () => api(SearchSuggestionsApi::class)->getApiV3SearchSuggestionsWithHttpInfo(fixtures()['search_q'], null, 5));
+    assert_status(200, $res, 'search-suggestions');
+    assert_has_key('data', $res['body'], 'search-suggestions');
+    assert_has_key('total', $res['body']['meta'] ?? null, 'search-suggestions meta');
+    if (count($res['body']['data']) > 5) {
+        fail('search-suggestions:limit=5 却返回了 '.count($res['body']['data']).' 条');
+    }
+    $texts = array_map(fn ($s) => mb_strtolower($s['text']), $res['body']['data']);
+    if (count($texts) !== count(array_unique($texts))) {
+        fail('search-suggestions:同一个词出现了不止一次');
+    }
+    foreach ($res['body']['data'] as $s) {
+        foreach (['text', 'source', 'score', 'doc_id', 'resource_type', 'language', 'granularity', 'category'] as $key) {
+            assert_has_key($key, $s, 'search-suggestions 条目');
+        }
+    }
 });
 
-test('GET /v3/search-suggest?q= → 400(空查询)', function () {
-    // 描述里写明「q 为空返回 400」;spec 只登记了 422,这里按实际 400 断言。
-    $res = raw('GET', '/v3/search-suggest', ['q' => '']);
-    assert_status(400, $res, 'search-suggest 空 q');
+test('GET /v3/search-suggestions(缺 q / 未知字段)→ 422', function () {
+    assert_field_error('q', raw('GET', '/v3/search-suggestions', ['q' => '']), 'search-suggestions 空 q');
+    assert_field_error('fields', raw('GET', '/v3/search-suggestions', ['q' => 'd', 'fields' => 'title']), 'search-suggestions 未知字段');
 });

+ 12 - 6
api-test/client/.openapi-generator/FILES

@@ -27,7 +27,7 @@ docs/Api/ProgressApi.md
 docs/Api/ReactionsApi.md
 docs/Api/ReadingTimeApi.md
 docs/Api/SearchApi.md
-docs/Api/SearchSuggestApi.md
+docs/Api/SearchSuggestionsApi.md
 docs/Api/SessionsApi.md
 docs/Api/StudiosApi.md
 docs/Api/TermsApi.md
@@ -137,7 +137,9 @@ docs/Model/GetApiV3Search200ResponseDataInner.md
 docs/Model/GetApiV3Search200ResponseMeta.md
 docs/Model/GetApiV3Search200ResponseMetaFacetsValueInner.md
 docs/Model/GetApiV3SearchSearch200Response.md
-docs/Model/GetApiV3SearchSuggest200Response.md
+docs/Model/GetApiV3SearchSuggestions200Response.md
+docs/Model/GetApiV3SearchSuggestions200ResponseDataInner.md
+docs/Model/GetApiV3SearchSuggestions200ResponseMeta.md
 docs/Model/GetApiV3TipitakaChannels200Response.md
 docs/Model/GetApiV3TipitakaChannels200ResponseDataInner.md
 docs/Model/GetApiV3TipitakaChapterChannelsBookPara200Response.md
@@ -253,7 +255,7 @@ lib/Api/ProgressApi.php
 lib/Api/ReactionsApi.php
 lib/Api/ReadingTimeApi.php
 lib/Api/SearchApi.php
-lib/Api/SearchSuggestApi.php
+lib/Api/SearchSuggestionsApi.php
 lib/Api/SessionsApi.php
 lib/Api/StudiosApi.php
 lib/Api/TermsApi.php
@@ -367,7 +369,9 @@ lib/Model/GetApiV3Search200ResponseDataInner.php
 lib/Model/GetApiV3Search200ResponseMeta.php
 lib/Model/GetApiV3Search200ResponseMetaFacetsValueInner.php
 lib/Model/GetApiV3SearchSearch200Response.php
-lib/Model/GetApiV3SearchSuggest200Response.php
+lib/Model/GetApiV3SearchSuggestions200Response.php
+lib/Model/GetApiV3SearchSuggestions200ResponseDataInner.php
+lib/Model/GetApiV3SearchSuggestions200ResponseMeta.php
 lib/Model/GetApiV3TipitakaChannels200Response.php
 lib/Model/GetApiV3TipitakaChannels200ResponseDataInner.php
 lib/Model/GetApiV3TipitakaChapterChannelsBookPara200Response.php
@@ -485,7 +489,7 @@ test/Api/ProgressApiTest.php
 test/Api/ReactionsApiTest.php
 test/Api/ReadingTimeApiTest.php
 test/Api/SearchApiTest.php
-test/Api/SearchSuggestApiTest.php
+test/Api/SearchSuggestionsApiTest.php
 test/Api/SessionsApiTest.php
 test/Api/StudiosApiTest.php
 test/Api/TermsApiTest.php
@@ -595,7 +599,9 @@ test/Model/GetApiV3Search200ResponseMetaFacetsValueInnerTest.php
 test/Model/GetApiV3Search200ResponseMetaTest.php
 test/Model/GetApiV3Search200ResponseTest.php
 test/Model/GetApiV3SearchSearch200ResponseTest.php
-test/Model/GetApiV3SearchSuggest200ResponseTest.php
+test/Model/GetApiV3SearchSuggestions200ResponseDataInnerTest.php
+test/Model/GetApiV3SearchSuggestions200ResponseMetaTest.php
+test/Model/GetApiV3SearchSuggestions200ResponseTest.php
 test/Model/GetApiV3TipitakaChannels200ResponseDataInnerTest.php
 test/Model/GetApiV3TipitakaChannels200ResponseTest.php
 test/Model/GetApiV3TipitakaChapterChannelsBookPara200ResponseDataInnerChannelTest.php

+ 64 - 65
api-test/client/lib/Api/SearchSuggestApi.php → api-test/client/lib/Api/SearchSuggestionsApi.php

@@ -1,6 +1,6 @@
 <?php
 /**
- * SearchSuggestApi
+ * SearchSuggestionsApi
  * PHP version 8.1
  *
  * @category Class
@@ -43,14 +43,14 @@ use WikipaliApi\HeaderSelector;
 use WikipaliApi\ObjectSerializer;
 
 /**
- * SearchSuggestApi Class Doc Comment
+ * SearchSuggestionsApi Class Doc Comment
  *
  * @category Class
  * @package  WikipaliApi
  * @author   OpenAPI Generator team
  * @link     https://openapi-generator.tech
  */
-class SearchSuggestApi
+class SearchSuggestionsApi
 {
     /**
      * @var ClientInterface
@@ -74,7 +74,7 @@ class SearchSuggestApi
 
     /** @var string[] $contentTypes **/
     public const contentTypes = [
-        'getApiV3SearchSuggest' => [
+        'getApiV3SearchSuggestions' => [
             'application/json',
         ],
     ];
@@ -126,44 +126,42 @@ class SearchSuggestApi
     }
 
     /**
-     * Operation getApiV3SearchSuggest
+     * Operation getApiV3SearchSuggestions
      *
-     * 搜索建议(自动补全)
+     * 搜索建议
      *
-     * @param  string $q 已输入的查询文本 (required)
-     * @param  string|null $fields 在哪些字段上补全,逗号分隔;不传则全查 (optional)
-     * @param  string|null $language 语言过滤 (optional)
-     * @param  int|null $limit 每个字段返回的建议数,上限 50 (optional, default to 10)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggest'] to see the possible values for this operation
+     * @param  string $q 已输入的前缀 (required)
+     * @param  string|null $fields 在哪些字段上补全,逗号分隔,可选 title_pali、title_zh、content_pali、content_zh;不传则全部 (optional)
+     * @param  int|null $limit 最多返回几条,上限 50 (optional, default to 10)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggestions'] to see the possible values for this operation
      *
      * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
      * @throws \InvalidArgumentException
-     * @return \WikipaliApi\Model\GetApiV3SearchSuggest200Response|\WikipaliApi\Model\ProblemDetails
+     * @return \WikipaliApi\Model\GetApiV3SearchSuggestions200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
      */
-    public function getApiV3SearchSuggest($q, $fields = null, $language = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggest'][0])
+    public function getApiV3SearchSuggestions($q, $fields = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggestions'][0])
     {
-        list($response) = $this->getApiV3SearchSuggestWithHttpInfo($q, $fields, $language, $limit, $contentType);
+        list($response) = $this->getApiV3SearchSuggestionsWithHttpInfo($q, $fields, $limit, $contentType);
         return $response;
     }
 
     /**
-     * Operation getApiV3SearchSuggestWithHttpInfo
+     * Operation getApiV3SearchSuggestionsWithHttpInfo
      *
-     * 搜索建议(自动补全)
+     * 搜索建议
      *
-     * @param  string $q 已输入的查询文本 (required)
-     * @param  string|null $fields 在哪些字段上补全,逗号分隔;不传则全查 (optional)
-     * @param  string|null $language 语言过滤 (optional)
-     * @param  int|null $limit 每个字段返回的建议数,上限 50 (optional, default to 10)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggest'] to see the possible values for this operation
+     * @param  string $q 已输入的前缀 (required)
+     * @param  string|null $fields 在哪些字段上补全,逗号分隔,可选 title_pali、title_zh、content_pali、content_zh;不传则全部 (optional)
+     * @param  int|null $limit 最多返回几条,上限 50 (optional, default to 10)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggestions'] to see the possible values for this operation
      *
      * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
      * @throws \InvalidArgumentException
-     * @return array of \WikipaliApi\Model\GetApiV3SearchSuggest200Response|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     * @return array of \WikipaliApi\Model\GetApiV3SearchSuggestions200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
      */
-    public function getApiV3SearchSuggestWithHttpInfo($q, $fields = null, $language = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggest'][0])
+    public function getApiV3SearchSuggestionsWithHttpInfo($q, $fields = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggestions'][0])
     {
-        $request = $this->getApiV3SearchSuggestRequest($q, $fields, $language, $limit, $contentType);
+        $request = $this->getApiV3SearchSuggestionsRequest($q, $fields, $limit, $contentType);
 
         try {
             $options = $this->createHttpClientOption();
@@ -191,7 +189,7 @@ class SearchSuggestApi
             switch($statusCode) {
                 case 200:
                     return $this->handleResponseWithDataType(
-                        '\WikipaliApi\Model\GetApiV3SearchSuggest200Response',
+                        '\WikipaliApi\Model\GetApiV3SearchSuggestions200Response',
                         $request,
                         $response,
                     );
@@ -201,6 +199,12 @@ class SearchSuggestApi
                         $request,
                         $response,
                     );
+                case 503:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
             }
 
             
@@ -219,7 +223,7 @@ class SearchSuggestApi
             }
 
             return $this->handleResponseWithDataType(
-                '\WikipaliApi\Model\GetApiV3SearchSuggest200Response',
+                '\WikipaliApi\Model\GetApiV3SearchSuggestions200Response',
                 $request,
                 $response,
             );
@@ -228,7 +232,7 @@ class SearchSuggestApi
                 case 200:
                     $data = ObjectSerializer::deserialize(
                         $e->getResponseBody(),
-                        '\WikipaliApi\Model\GetApiV3SearchSuggest200Response',
+                        '\WikipaliApi\Model\GetApiV3SearchSuggestions200Response',
                         $e->getResponseHeaders()
                     );
                     $e->setResponseObject($data);
@@ -241,6 +245,14 @@ class SearchSuggestApi
                     );
                     $e->setResponseObject($data);
                     throw $e;
+                case 503:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
             }
         
 
@@ -249,22 +261,21 @@ class SearchSuggestApi
     }
 
     /**
-     * Operation getApiV3SearchSuggestAsync
+     * Operation getApiV3SearchSuggestionsAsync
      *
-     * 搜索建议(自动补全)
+     * 搜索建议
      *
-     * @param  string $q 已输入的查询文本 (required)
-     * @param  string|null $fields 在哪些字段上补全,逗号分隔;不传则全查 (optional)
-     * @param  string|null $language 语言过滤 (optional)
-     * @param  int|null $limit 每个字段返回的建议数,上限 50 (optional, default to 10)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggest'] to see the possible values for this operation
+     * @param  string $q 已输入的前缀 (required)
+     * @param  string|null $fields 在哪些字段上补全,逗号分隔,可选 title_pali、title_zh、content_pali、content_zh;不传则全部 (optional)
+     * @param  int|null $limit 最多返回几条,上限 50 (optional, default to 10)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggestions'] to see the possible values for this operation
      *
      * @throws \InvalidArgumentException
      * @return \GuzzleHttp\Promise\PromiseInterface
      */
-    public function getApiV3SearchSuggestAsync($q, $fields = null, $language = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggest'][0])
+    public function getApiV3SearchSuggestionsAsync($q, $fields = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggestions'][0])
     {
-        return $this->getApiV3SearchSuggestAsyncWithHttpInfo($q, $fields, $language, $limit, $contentType)
+        return $this->getApiV3SearchSuggestionsAsyncWithHttpInfo($q, $fields, $limit, $contentType)
             ->then(
                 function ($response) {
                     return $response[0];
@@ -273,23 +284,22 @@ class SearchSuggestApi
     }
 
     /**
-     * Operation getApiV3SearchSuggestAsyncWithHttpInfo
+     * Operation getApiV3SearchSuggestionsAsyncWithHttpInfo
      *
-     * 搜索建议(自动补全)
+     * 搜索建议
      *
-     * @param  string $q 已输入的查询文本 (required)
-     * @param  string|null $fields 在哪些字段上补全,逗号分隔;不传则全查 (optional)
-     * @param  string|null $language 语言过滤 (optional)
-     * @param  int|null $limit 每个字段返回的建议数,上限 50 (optional, default to 10)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggest'] to see the possible values for this operation
+     * @param  string $q 已输入的前缀 (required)
+     * @param  string|null $fields 在哪些字段上补全,逗号分隔,可选 title_pali、title_zh、content_pali、content_zh;不传则全部 (optional)
+     * @param  int|null $limit 最多返回几条,上限 50 (optional, default to 10)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggestions'] to see the possible values for this operation
      *
      * @throws \InvalidArgumentException
      * @return \GuzzleHttp\Promise\PromiseInterface
      */
-    public function getApiV3SearchSuggestAsyncWithHttpInfo($q, $fields = null, $language = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggest'][0])
+    public function getApiV3SearchSuggestionsAsyncWithHttpInfo($q, $fields = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggestions'][0])
     {
-        $returnType = '\WikipaliApi\Model\GetApiV3SearchSuggest200Response';
-        $request = $this->getApiV3SearchSuggestRequest($q, $fields, $language, $limit, $contentType);
+        $returnType = '\WikipaliApi\Model\GetApiV3SearchSuggestions200Response';
+        $request = $this->getApiV3SearchSuggestionsRequest($q, $fields, $limit, $contentType);
 
         return $this->client
             ->sendAsync($request, $this->createHttpClientOption())
@@ -328,32 +338,30 @@ class SearchSuggestApi
     }
 
     /**
-     * Create request for operation 'getApiV3SearchSuggest'
+     * Create request for operation 'getApiV3SearchSuggestions'
      *
-     * @param  string $q 已输入的查询文本 (required)
-     * @param  string|null $fields 在哪些字段上补全,逗号分隔;不传则全查 (optional)
-     * @param  string|null $language 语言过滤 (optional)
-     * @param  int|null $limit 每个字段返回的建议数,上限 50 (optional, default to 10)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggest'] to see the possible values for this operation
+     * @param  string $q 已输入的前缀 (required)
+     * @param  string|null $fields 在哪些字段上补全,逗号分隔,可选 title_pali、title_zh、content_pali、content_zh;不传则全部 (optional)
+     * @param  int|null $limit 最多返回几条,上限 50 (optional, default to 10)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3SearchSuggestions'] to see the possible values for this operation
      *
      * @throws \InvalidArgumentException
      * @return \GuzzleHttp\Psr7\Request
      */
-    public function getApiV3SearchSuggestRequest($q, $fields = null, $language = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggest'][0])
+    public function getApiV3SearchSuggestionsRequest($q, $fields = null, $limit = 10, string $contentType = self::contentTypes['getApiV3SearchSuggestions'][0])
     {
 
         // verify the required parameter 'q' is set
         if ($q === null || (is_array($q) && count($q) === 0)) {
             throw new \InvalidArgumentException(
-                'Missing the required parameter $q when calling getApiV3SearchSuggest'
+                'Missing the required parameter $q when calling getApiV3SearchSuggestions'
             );
         }
 
 
 
 
-
-        $resourcePath = '/v3/search-suggest';
+        $resourcePath = '/v3/search-suggestions';
         $formParams = [];
         $queryParams = [];
         $headerParams = [];
@@ -379,15 +387,6 @@ class SearchSuggestApi
             false // required
         ) ?? []);
         // query params
-        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
-            $language,
-            'language', // param base name
-            'string', // openApiType
-            'form', // style
-            true, // explode
-            false // required
-        ) ?? []);
-        // query params
         $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
             $limit,
             'limit', // param base name

+ 37 - 37
api-test/client/lib/Model/GetApiV3SearchSuggest200Response.php → api-test/client/lib/Model/GetApiV3SearchSuggestions200Response.php

@@ -1,6 +1,6 @@
 <?php
 /**
- * GetApiV3SearchSuggest200Response
+ * GetApiV3SearchSuggestions200Response
  *
  * PHP version 8.1
  *
@@ -32,7 +32,7 @@ use \ArrayAccess;
 use \WikipaliApi\ObjectSerializer;
 
 /**
- * GetApiV3SearchSuggest200Response Class Doc Comment
+ * GetApiV3SearchSuggestions200Response Class Doc Comment
  *
  * @category Class
  * @package  WikipaliApi
@@ -40,7 +40,7 @@ use \WikipaliApi\ObjectSerializer;
  * @link     https://openapi-generator.tech
  * @implements \ArrayAccess<string, mixed>
  */
-class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \JsonSerializable
+class GetApiV3SearchSuggestions200Response implements ModelInterface, ArrayAccess, \JsonSerializable
 {
     public const DISCRIMINATOR = null;
 
@@ -49,7 +49,7 @@ class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \
      *
      * @var string
      */
-    protected static $openAPIModelName = 'get_api_v3_search_suggest_200_response';
+    protected static $openAPIModelName = 'get_api_v3_search_suggestions_200_response';
 
     /**
      * Array of property to type mappings. Used for (de)serialization
@@ -57,8 +57,8 @@ class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \
      * @var string[]
      */
     protected static $openAPITypes = [
-        'success' => 'bool',
-        'data' => 'object'
+        'data' => '\WikipaliApi\Model\GetApiV3SearchSuggestions200ResponseDataInner[]',
+        'meta' => '\WikipaliApi\Model\GetApiV3SearchSuggestions200ResponseMeta'
     ];
 
     /**
@@ -69,8 +69,8 @@ class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \
      * @psalm-var array<string, string|null>
      */
     protected static $openAPIFormats = [
-        'success' => null,
-        'data' => null
+        'data' => null,
+        'meta' => null
     ];
 
     /**
@@ -79,8 +79,8 @@ class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \
      * @var boolean[]
      */
     protected static array $openAPINullables = [
-        'success' => false,
-        'data' => false
+        'data' => false,
+        'meta' => false
     ];
 
     /**
@@ -169,8 +169,8 @@ class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \
      * @var string[]
      */
     protected static $attributeMap = [
-        'success' => 'success',
-        'data' => 'data'
+        'data' => 'data',
+        'meta' => 'meta'
     ];
 
     /**
@@ -179,8 +179,8 @@ class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \
      * @var string[]
      */
     protected static $setters = [
-        'success' => 'setSuccess',
-        'data' => 'setData'
+        'data' => 'setData',
+        'meta' => 'setMeta'
     ];
 
     /**
@@ -189,8 +189,8 @@ class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \
      * @var string[]
      */
     protected static $getters = [
-        'success' => 'getSuccess',
-        'data' => 'getData'
+        'data' => 'getData',
+        'meta' => 'getMeta'
     ];
 
     /**
@@ -250,8 +250,8 @@ class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \
      */
     public function __construct(?array $data = null)
     {
-        $this->setIfExists('success', $data ?? [], null);
         $this->setIfExists('data', $data ?? [], null);
+        $this->setIfExists('meta', $data ?? [], null);
     }
 
     /**
@@ -297,55 +297,55 @@ class GetApiV3SearchSuggest200Response implements ModelInterface, ArrayAccess, \
 
 
     /**
-     * Gets success
+     * Gets data
      *
-     * @return bool|null
+     * @return \WikipaliApi\Model\GetApiV3SearchSuggestions200ResponseDataInner[]|null
      */
-    public function getSuccess()
+    public function getData()
     {
-        return $this->container['success'];
+        return $this->container['data'];
     }
 
     /**
-     * Sets success
+     * Sets data
      *
-     * @param bool|null $success success
+     * @param \WikipaliApi\Model\GetApiV3SearchSuggestions200ResponseDataInner[]|null $data data
      *
      * @return self
      */
-    public function setSuccess($success)
+    public function setData($data)
     {
-        if (is_null($success)) {
-            throw new \InvalidArgumentException('non-nullable success cannot be null');
+        if (is_null($data)) {
+            throw new \InvalidArgumentException('non-nullable data cannot be null');
         }
-        $this->container['success'] = $success;
+        $this->container['data'] = $data;
 
         return $this;
     }
 
     /**
-     * Gets data
+     * Gets meta
      *
-     * @return object|null
+     * @return \WikipaliApi\Model\GetApiV3SearchSuggestions200ResponseMeta|null
      */
-    public function getData()
+    public function getMeta()
     {
-        return $this->container['data'];
+        return $this->container['meta'];
     }
 
     /**
-     * Sets data
+     * Sets meta
      *
-     * @param object|null $data data
+     * @param \WikipaliApi\Model\GetApiV3SearchSuggestions200ResponseMeta|null $meta meta
      *
      * @return self
      */
-    public function setData($data)
+    public function setMeta($meta)
     {
-        if (is_null($data)) {
-            throw new \InvalidArgumentException('non-nullable data cannot be null');
+        if (is_null($meta)) {
+            throw new \InvalidArgumentException('non-nullable meta cannot be null');
         }
-        $this->container['data'] = $data;
+        $this->container['meta'] = $meta;
 
         return $this;
     }

+ 675 - 0
api-test/client/lib/Model/GetApiV3SearchSuggestions200ResponseDataInner.php

@@ -0,0 +1,675 @@
+<?php
+/**
+ * GetApiV3SearchSuggestions200ResponseDataInner
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * GetApiV3SearchSuggestions200ResponseDataInner Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class GetApiV3SearchSuggestions200ResponseDataInner implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'get_api_v3_search_suggestions_200_response_data_inner';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'text' => 'string',
+        'source' => 'string',
+        'score' => 'float',
+        'doc_id' => 'string',
+        'resource_type' => 'string',
+        'language' => 'string',
+        'granularity' => 'string',
+        'category' => 'string[]'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'text' => null,
+        'source' => null,
+        'score' => null,
+        'doc_id' => null,
+        'resource_type' => null,
+        'language' => null,
+        'granularity' => null,
+        'category' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'text' => false,
+        'source' => false,
+        'score' => false,
+        'doc_id' => true,
+        'resource_type' => true,
+        'language' => true,
+        'granularity' => true,
+        'category' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'text' => 'text',
+        'source' => 'source',
+        'score' => 'score',
+        'doc_id' => 'doc_id',
+        'resource_type' => 'resource_type',
+        'language' => 'language',
+        'granularity' => 'granularity',
+        'category' => 'category'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'text' => 'setText',
+        'source' => 'setSource',
+        'score' => 'setScore',
+        'doc_id' => 'setDocId',
+        'resource_type' => 'setResourceType',
+        'language' => 'setLanguage',
+        'granularity' => 'setGranularity',
+        'category' => 'setCategory'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'text' => 'getText',
+        'source' => 'getSource',
+        'score' => 'getScore',
+        'doc_id' => 'getDocId',
+        'resource_type' => 'getResourceType',
+        'language' => 'getLanguage',
+        'granularity' => 'getGranularity',
+        'category' => 'getCategory'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('text', $data ?? [], null);
+        $this->setIfExists('source', $data ?? [], null);
+        $this->setIfExists('score', $data ?? [], null);
+        $this->setIfExists('doc_id', $data ?? [], null);
+        $this->setIfExists('resource_type', $data ?? [], null);
+        $this->setIfExists('language', $data ?? [], null);
+        $this->setIfExists('granularity', $data ?? [], null);
+        $this->setIfExists('category', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets text
+     *
+     * @return string|null
+     */
+    public function getText()
+    {
+        return $this->container['text'];
+    }
+
+    /**
+     * Sets text
+     *
+     * @param string|null $text text
+     *
+     * @return self
+     */
+    public function setText($text)
+    {
+        if (is_null($text)) {
+            throw new \InvalidArgumentException('non-nullable text cannot be null');
+        }
+        $this->container['text'] = $text;
+
+        return $this;
+    }
+
+    /**
+     * Gets source
+     *
+     * @return string|null
+     */
+    public function getSource()
+    {
+        return $this->container['source'];
+    }
+
+    /**
+     * Sets source
+     *
+     * @param string|null $source source
+     *
+     * @return self
+     */
+    public function setSource($source)
+    {
+        if (is_null($source)) {
+            throw new \InvalidArgumentException('non-nullable source cannot be null');
+        }
+        $this->container['source'] = $source;
+
+        return $this;
+    }
+
+    /**
+     * Gets score
+     *
+     * @return float|null
+     */
+    public function getScore()
+    {
+        return $this->container['score'];
+    }
+
+    /**
+     * Sets score
+     *
+     * @param float|null $score score
+     *
+     * @return self
+     */
+    public function setScore($score)
+    {
+        if (is_null($score)) {
+            throw new \InvalidArgumentException('non-nullable score cannot be null');
+        }
+        $this->container['score'] = $score;
+
+        return $this;
+    }
+
+    /**
+     * Gets doc_id
+     *
+     * @return string|null
+     */
+    public function getDocId()
+    {
+        return $this->container['doc_id'];
+    }
+
+    /**
+     * Sets doc_id
+     *
+     * @param string|null $doc_id doc_id
+     *
+     * @return self
+     */
+    public function setDocId($doc_id)
+    {
+        if (is_null($doc_id)) {
+            array_push($this->openAPINullablesSetToNull, 'doc_id');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('doc_id', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['doc_id'] = $doc_id;
+
+        return $this;
+    }
+
+    /**
+     * Gets resource_type
+     *
+     * @return string|null
+     */
+    public function getResourceType()
+    {
+        return $this->container['resource_type'];
+    }
+
+    /**
+     * Sets resource_type
+     *
+     * @param string|null $resource_type resource_type
+     *
+     * @return self
+     */
+    public function setResourceType($resource_type)
+    {
+        if (is_null($resource_type)) {
+            array_push($this->openAPINullablesSetToNull, 'resource_type');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('resource_type', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['resource_type'] = $resource_type;
+
+        return $this;
+    }
+
+    /**
+     * Gets language
+     *
+     * @return string|null
+     */
+    public function getLanguage()
+    {
+        return $this->container['language'];
+    }
+
+    /**
+     * Sets language
+     *
+     * @param string|null $language language
+     *
+     * @return self
+     */
+    public function setLanguage($language)
+    {
+        if (is_null($language)) {
+            array_push($this->openAPINullablesSetToNull, 'language');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('language', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['language'] = $language;
+
+        return $this;
+    }
+
+    /**
+     * Gets granularity
+     *
+     * @return string|null
+     */
+    public function getGranularity()
+    {
+        return $this->container['granularity'];
+    }
+
+    /**
+     * Sets granularity
+     *
+     * @param string|null $granularity granularity
+     *
+     * @return self
+     */
+    public function setGranularity($granularity)
+    {
+        if (is_null($granularity)) {
+            array_push($this->openAPINullablesSetToNull, 'granularity');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('granularity', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['granularity'] = $granularity;
+
+        return $this;
+    }
+
+    /**
+     * Gets category
+     *
+     * @return string[]|null
+     */
+    public function getCategory()
+    {
+        return $this->container['category'];
+    }
+
+    /**
+     * Sets category
+     *
+     * @param string[]|null $category category
+     *
+     * @return self
+     */
+    public function setCategory($category)
+    {
+        if (is_null($category)) {
+            throw new \InvalidArgumentException('non-nullable category cannot be null');
+        }
+        $this->container['category'] = $category;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 409 - 0
api-test/client/lib/Model/GetApiV3SearchSuggestions200ResponseMeta.php

@@ -0,0 +1,409 @@
+<?php
+/**
+ * GetApiV3SearchSuggestions200ResponseMeta
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * GetApiV3SearchSuggestions200ResponseMeta Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class GetApiV3SearchSuggestions200ResponseMeta implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'get_api_v3_search_suggestions_200_response_meta';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'total' => 'int'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'total' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'total' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'total' => 'total'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'total' => 'setTotal'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'total' => 'getTotal'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('total', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets total
+     *
+     * @return int|null
+     */
+    public function getTotal()
+    {
+        return $this->container['total'];
+    }
+
+    /**
+     * Sets total
+     *
+     * @param int|null $total 本次返回的条数
+     *
+     * @return self
+     */
+    public function setTotal($total)
+    {
+        if (is_null($total)) {
+            throw new \InvalidArgumentException('non-nullable total cannot be null');
+        }
+        $this->container['total'] = $total;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 1 - 5
api-test/tools/filter-v3.php

@@ -137,16 +137,12 @@ function normalizeArraySchemas(mixed &$node): void
     unset($value);
 }
 
-/** 修正 search-suggest / upgrade 的 200 响应 schema,使其与实现一致(/v3/search 已于 2026-11-19 对齐,不再打补丁) */
+/** 修正 upgrade 的 200 响应 schema,使其与实现一致(/v3/search 与 search-suggestions 已于 2026-11-19 对齐,不再打补丁) */
 function applyDriftPatches(array &$spec): void
 {
     $object = ['type' => 'object'];
     $dataObject = ['type' => 'object', 'properties' => ['data' => $object]];
-    $successData = ['type' => 'object', 'properties' => ['success' => ['type' => 'boolean'], 'data' => $object]];
 
-    if (isset($spec['paths']['/v3/search-suggest']['get']['responses']['200']['content']['application/json']['schema'])) {
-        $spec['paths']['/v3/search-suggest']['get']['responses']['200']['content']['application/json']['schema'] = $successData;
-    }
     if (isset($spec['paths']['/v3/upgrade']['get']['responses']['200']['content']['application/json']['schema'])) {
         $spec['paths']['/v3/upgrade']['get']['responses']['200']['content']['application/json']['schema'] = $dataObject;
     }

+ 0 - 195
api-v13/app/Http/Controllers/V3/SearchSuggestController.php

@@ -1,195 +0,0 @@
-<?php
-
-// api-v8/app/Http/Controllers/SearchSuggestController.php
-
-namespace App\Http\Controllers\V3;
-
-use App\Http\Controllers\Controller;
-use App\Services\OpenSearchService;
-use Illuminate\Http\Request;
-
-/**
- * 搜索自动建议控制器
- *
- * 返回示例:
- *
- * 请求:GET /api/v3/search-suggest?q=dhamma&fields=title,content&limit=10
- *
- * 返回:
- * {
- *   "success": true,
- *   "data": {
- *     "query": "dhamma",
- *     "suggestions": [
-      {
-        "text": "dhammacakkapavattanasutta",
-        "source": "content",
-        "score": 1,
-        "resource_type": "term",
-        "language": "zh",
-        "doc_id": "term_69258244-bccd-40ed-bfaa-ddef4ae5ae4c",
-        "category": [],
-        "granularity": null
-      },
-      {
-        "text": "dhammacakkappavattanasutta",
-        "source": "content",
-        "score": 1,
-        "resource_type": "term",
-        "language": "zh-hans",
-        "doc_id": "term_bcb14399-ea80-4a8a-aeab-a4c927e45fdd",
-        "category": [],
-        "granularity": null
-      }
- *     ],
- *     "total": 2
- *   }
- * }
- */
-class SearchSuggestController extends Controller
-{
-    protected $searchService;
-
-    /**
-     * 构造函数,注入 OpenSearchService
-     */
-    public function __construct(OpenSearchService $searchService)
-    {
-        $this->searchService = $searchService;
-    }
-
-    /**
-     * # 1. 查询所有字段(默认)
-GET /api/v2/suggest?q=dhamma&limit=10
-
-# 2. 只查询标题
-GET /api/v2/suggest?q=dhamma&fields=title&limit=10
-
-# 3. 查询标题和内容
-GET /api/v2/suggest?q=dhamma&fields=title,content&limit=10
-
-# 4. 查询页面引用,带语言过滤
-GET /api/v2/suggest?q=M.1&fields=page_refs&language=pali&limit=5
-
-# 5. 数组形式传递多个字段
-GET /api/v2/suggest?q=dhamma&fields[]=title&fields[]=content&limit=10
-     */
-    /**
-     * 搜索建议(自动补全)
-     *
-     * 按前缀给出补全候选,供搜索框实时提示。每个字段各自返回一组建议。
-     * q 为空时返回 400。
-     *
-     * @unauthenticated
-     *
-     * @queryParam q string required 已输入的查询文本
-     * @queryParam fields string 在哪些字段上补全,逗号分隔;不传则全查。
-     *             Enum: title,content,page_refs
-     * @queryParam language string 语言过滤。Example: pali
-     * @queryParam limit integer 每个字段返回的建议数,上限 50。Default: 10
-     */
-    public function index(Request $request)
-    {
-        // 验证必填参数
-        $query = $request->input('q', '');
-        if (empty($query)) {
-            return response()->json([
-                'success' => false,
-                'error' => '缺少参数 q(查询文本)',
-            ], 400);
-        }
-
-        // 解析 fields 参数
-        $fields = $this->parseFields($request->input('fields'));
-
-        // 获取其他参数
-        $language = $request->input('language', null);
-        $limit = min(50, max(1, (int) $request->input('limit', 10)));
-
-        try {
-            // 调用搜索服务
-            $rawSuggestions = $this->searchService->suggest(
-                $query,
-                $fields,
-                $language,
-                $limit
-            );
-
-            // 格式化返回结果
-            $suggestions = $this->formatSuggestions($rawSuggestions);
-
-            return response()->json([
-                'success' => true,
-                'data' => [
-                    'query' => $query,
-                    'suggestions' => $suggestions,
-                    'total' => count($suggestions),
-                ],
-            ]);
-        } catch (\InvalidArgumentException $e) {
-            return response()->json([
-                'success' => false,
-                'error' => '无效的字段参数:'.$e->getMessage(),
-                'hint' => '有效的字段值:title, content, page_refs',
-            ], 400);
-        } catch (\Exception $e) {
-            return response()->json([
-                'success' => false,
-                'error' => '搜索建议失败:'.$e->getMessage(),
-            ], 500);
-        }
-    }
-
-    /**
-     * 解析 fields 参数
-     *
-     * @param  mixed  $fields
-     * @return string|array|null
-     */
-    protected function parseFields($fields)
-    {
-        if ($fields === null) {
-            return null;  // 查询所有字段
-        }
-
-        if (is_string($fields)) {
-            // 如果是逗号分隔的字符串,转换为数组
-            if (strpos($fields, ',') !== false) {
-                $fieldsArray = array_map('trim', explode(',', $fields));
-
-                return $fieldsArray;
-            }
-
-            // 单个字段
-            return $fields;
-        }
-
-        if (is_array($fields)) {
-            return $fields;
-        }
-
-        return null;
-    }
-
-    /**
-     * 格式化建议结果
-     */
-    protected function formatSuggestions(array $rawSuggestions): array
-    {
-        return collect($rawSuggestions)->map(function ($item) {
-            $docSource = $item['doc_source'] ?? [];
-
-            return [
-                'text' => $item['text'] ?? '',
-                'source' => $item['source'] ?? null,
-                'score' => round($item['score'] ?? 0, 2),
-                'resource_type' => $docSource['resource_type'] ?? null,
-                'language' => $docSource['language'] ?? null,
-                'doc_id' => $item['doc_id'] ?? null,
-                // 可选:添加更多元数据
-                'category' => $docSource['category'] ?? null,
-                'granularity' => $docSource['granularity'] ?? null,
-            ];
-        })->all();
-    }
-}

+ 44 - 0
api-v13/app/Http/Controllers/V3/SearchSuggestionController.php

@@ -0,0 +1,44 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\IndexSearchSuggestionRequest;
+use App\Http\Resources\V3\SearchSuggestionResource;
+use App\Services\V3\SearchService;
+
+/**
+ * 搜索建议(搜索框的前缀补全,OpenSearch completion suggester)
+ *
+ * 取代早期的 `GET /v3/search-suggest`(`V3\SearchSuggestController`,2026-11-19 删除):
+ * 路径复数化;`{success, data:{query, suggestions, total}}` 改成 `{data, meta}`;空 q 从 400 改 422;
+ * `limit` 从「每个字段各取」改成总条数并去重;去掉从未生效的 `language` 参数。
+ * 无对应的 v2 端点。
+ */
+class SearchSuggestionController extends Controller
+{
+    public function __construct(private readonly SearchService $search) {}
+
+    /**
+     * 搜索建议
+     *
+     * 按已输入的前缀给出补全候选,各字段合并后按分数排序、同一个词只出现一次。
+     * 搜索服务连不上或超时回 503(`search-unavailable`)。
+     *
+     * @unauthenticated
+     *
+     * @queryParam q string required 已输入的前缀
+     * @queryParam fields string 在哪些字段上补全,逗号分隔,可选 title_pali、title_zh、content_pali、content_zh;不传则全部。Example: title_pali,content_pali
+     * @queryParam limit integer 最多返回几条,上限 50。Default: 10
+     *
+     * @responseStatus 503 搜索服务暂不可用
+     *
+     * @meta total integer 本次返回的条数
+     */
+    public function __invoke(IndexSearchSuggestionRequest $request)
+    {
+        $items = $this->search->suggest($request->validated());
+
+        return SearchSuggestionResource::collection($items)->additional(['meta' => ['total' => count($items)]]);
+    }
+}

+ 50 - 0
api-v13/app/Http/Requests/V3/IndexSearchSuggestionRequest.php

@@ -0,0 +1,50 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Closure;
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `GET /v3/search-suggestions`:搜索框的前缀补全。
+ */
+class IndexSearchSuggestionRequest extends FormRequest
+{
+    /** 可补全的字段(OpenSearchService::suggest 的字段标识符) */
+    public const FIELDS = ['title_pali', 'title_zh', 'content_pali', 'content_zh'];
+
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'q' => ['required', 'string', 'max:100'],
+            'fields' => ['sometimes', 'string', 'max:100', function (string $attribute, mixed $value, Closure $fail): void {
+                $unknown = array_diff(self::splitFields((string) $value), self::FIELDS);
+                if ($unknown !== [] || self::splitFields((string) $value) === []) {
+                    $fail(__('validation.in', ['attribute' => $attribute]));
+                }
+            }],
+            'limit' => ['sometimes', 'integer', 'min:1', 'max:50'],
+        ];
+    }
+
+    /**
+     * 逗号分隔的字段列表,去空白、去空项、去重。
+     *
+     * @return list<string>
+     */
+    public static function splitFields(string $value): array
+    {
+        return array_values(array_unique(array_filter(
+            array_map('trim', explode(',', $value)),
+            fn (string $field) => $field !== '',
+        )));
+    }
+}

+ 30 - 0
api-v13/app/Http/Resources/V3/SearchSuggestionResource.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use Illuminate\Http\Request;
+
+/**
+ * 一条搜索建议(OpenSearch completion 候选,见 `App\Services\V3\SearchService::suggest()`)。
+ *
+ * `source` 是候选来自哪个补全字段;`doc_id` 是候选所在的检索文档,可直接 `GET /v3/search/{doc_id}`。
+ */
+class SearchSuggestionResource extends BaseResource
+{
+    /**
+     * @return array{
+     *     text: string,
+     *     source: string,
+     *     score: float,
+     *     doc_id: string|null,
+     *     resource_type: string|null,
+     *     language: string|null,
+     *     granularity: string|null,
+     *     category: list<string>
+     * }
+     */
+    public function toArray(Request $request): array
+    {
+        return $this->resource;
+    }
+}

+ 7 - 1
api-v13/app/Services/OpenSearchService.php

@@ -1363,8 +1363,14 @@ class OpenSearchService
             ];
         }
 
-        $dsl = ['suggest' => $suggests];
+        // 每条候选只带出处的元数据,不把整篇文档(正文、向量)拉回来
+        $dsl = [
+            '_source' => ['resource_type', 'language', 'granularity', 'category'],
+            'suggest' => $suggests,
+        ];
 
+        // FIXME: completion suggester 会忽略 query,这个语言过滤从来没生效过(v3 已不再传)。
+        // 真要按语言过滤得给 *.suggest.* 字段配 completion context 并重建索引。
         if ($language) {
             $dsl['query'] = ['term' => ['language' => $language]];
         }

+ 46 - 1
api-v13/app/Services/V3/SearchService.php

@@ -4,6 +4,7 @@ namespace App\Services\V3;
 
 use App\Exceptions\BusinessException;
 use App\Http\Requests\V3\IndexSearchRequest;
+use App\Http\Requests\V3\IndexSearchSuggestionRequest;
 use App\Services\OpenSearchService;
 use Closure;
 use OpenSearch\Exception\NotFoundHttpException;
@@ -13,7 +14,7 @@ use OpenSearch\Exception\TooManyRequestsHttpException;
 use Psr\Http\Client\ClientExceptionInterface;
 
 /**
- * v3 全文检索:把 OpenSearch 的原始命中归一化成对外的扁平结构。
+ * v3 全文检索与搜索建议:把 OpenSearch 的原始结果归一化成对外的扁平结构。
  *
  * 查询 DSL 仍由共享的 OpenSearchService 构造(Library 检索页与 AITermService 也在用),
  * 这里只负责入参映射、异常分类和输出形状——不暴露 `_source` / `hits.hits` 这类 OpenSearch 内部结构。
@@ -108,6 +109,50 @@ class SearchService
         return self::hit($raw);
     }
 
+    /**
+     * 搜索框的前缀补全。
+     *
+     * 各字段的候选合在一起按分数排,同一个词只留分数最高的一条,最多 limit 条
+     * (共享 Service 的 size 是按字段算的,这里每个字段取满 limit 再统一截断)。
+     *
+     * @param  array<string, mixed>  $input  IndexSearchSuggestionRequest::validated()
+     * @return list<array{text: string, source: string, score: float, doc_id: string|null, resource_type: string|null, language: string|null, granularity: string|null, category: list<string>}>
+     */
+    public function suggest(array $input): array
+    {
+        $limit = (int) ($input['limit'] ?? 10);
+        $fields = isset($input['fields'])
+            ? IndexSearchSuggestionRequest::splitFields($input['fields'])
+            : IndexSearchSuggestionRequest::FIELDS;
+
+        $raw = $this->call(fn () => $this->search->suggest($input['q'], $fields, null, $limit));
+
+        $items = [];
+        foreach ($raw as $option) {
+            $text = (string) ($option['text'] ?? '');
+            $key = mb_strtolower($text);
+            if ($text === '' || isset($items[$key])) {
+                continue;   // 已按分数降序,先到的分数最高
+            }
+            $source = $option['doc_source'] ?? [];
+            $items[$key] = [
+                'text' => $text,
+                'source' => (string) $option['source'],
+                'score' => round((float) ($option['score'] ?? 0), 2),
+                'doc_id' => isset($option['doc_id']) ? (string) $option['doc_id'] : null,
+                'resource_type' => isset($source['resource_type']) ? (string) $source['resource_type'] : null,
+                'language' => isset($source['language']) ? (string) $source['language'] : null,
+                'granularity' => isset($source['granularity']) ? (string) $source['granularity'] : null,
+                'category' => array_values((array) ($source['category'] ?? [])),
+            ];
+            if (count($items) >= $limit) {
+                break;
+            }
+        }
+
+        return array_values($items);
+    }
+
     /**
      * 调 OpenSearch,把「服务不可用」类异常转成 503。
      *

+ 24 - 4
api-v13/resources/js/search-suggest.js

@@ -1,3 +1,15 @@
+// 搜索框的前缀补全,调 GET /api/v3/search-suggestions({data: [{text, resource_type, …}], meta})
+
+/** 候选文本来自索引内容,插进 HTML 前必须转义 */
+const escapeHtml = (value) =>
+    String(value ?? "").replace(/[&<>"']/g, (ch) => ({
+        "&": "&amp;",
+        "<": "&lt;",
+        ">": "&gt;",
+        '"': "&quot;",
+        "'": "&#39;",
+    })[ch]);
+
 document.addEventListener("DOMContentLoaded", () => {
     const inputs = document.querySelectorAll(".search-input");
 
@@ -29,11 +41,18 @@ document.addEventListener("DOMContentLoaded", () => {
 
                 const res = await fetch(url, {
                     signal: controller.signal,
+                    headers: { Accept: "application/json" },
                 });
 
+                // 补全只是辅助:失败(422 / 503 …)就不显示下拉,不打断输入
+                if (!res.ok) {
+                    dropdown.classList.remove("show");
+                    return;
+                }
+
                 const json = await res.json();
 
-                renderSuggestions(json.data.suggestions || []);
+                renderSuggestions(json.data || []);
             } catch (e) {
                 if (e.name !== "AbortError") {
                     console.error(e);
@@ -49,14 +68,15 @@ document.addEventListener("DOMContentLoaded", () => {
 
             dropdown.innerHTML = list
                 .map((item) => {
+                    const text = escapeHtml(item.text);
                     return `
                     <button type="button"
                         class="dropdown-item"
-                        data-text="${item.text}">
+                        data-text="${text}">
 
                         <div class="d-flex justify-content-between">
-                            <span>${item.text}</span>
-                            <small class="text-muted">${item.resource_type}</small>
+                            <span>${text}</span>
+                            <small class="text-muted">${escapeHtml(item.resource_type)}</small>
                         </div>
                     </button>
                 `;

+ 1 - 1
api-v13/resources/views/components/ui/search-input.blade.php

@@ -32,7 +32,7 @@
                 value="{{ $value }}"
                 placeholder="{{ $placeholder }}"
                 autocomplete="off"
-                data-suggest-url="/api/v3/search-suggest"
+                data-suggest-url="/api/v3/search-suggestions"
                 {{ $autofocus ? 'autofocus' : '' }} />
         </div>
 

+ 2 - 2
api-v13/routes/v3/search.php

@@ -10,9 +10,9 @@
 */
 
 use App\Http\Controllers\V3\SearchController;
-use App\Http\Controllers\V3\SearchSuggestController;
+use App\Http\Controllers\V3\SearchSuggestionController;
 use Illuminate\Support\Facades\Route;
 
 // 只注册真正实现了的动作——空方法会在 OpenAPI 里变成幽灵端点
 Route::apiResource('search', SearchController::class)->only(['index', 'store', 'show']);
-Route::apiResource('search-suggest', SearchSuggestController::class)->only(['index']);
+Route::get('search-suggestions', SearchSuggestionController::class)->name('search-suggestions.index');

+ 94 - 0
api-v13/tests/Feature/SearchSuggestionV3Test.php

@@ -0,0 +1,94 @@
+<?php
+
+use App\Services\OpenSearchService;
+use GuzzleHttp\Exception\ConnectException;
+use GuzzleHttp\Psr7\Request as PsrRequest;
+
+/*
+ * /v3/search-suggestions(搜索框前缀补全)。
+ *
+ * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。OpenSearch 一律 mock。
+ */
+
+/** OpenSearchService::suggest 的一条原始结果 */
+function rawSuggestion(string $text, string $field, float $score, string $docId = 'doc'): array
+{
+    return [
+        'text' => $text, 'source' => $field, 'score' => $score, 'doc_id' => $docId,
+        'doc_source' => ['resource_type' => 'tipitaka', 'language' => 'pi', 'granularity' => 'paragraph', 'category' => ['sutta']],
+    ];
+}
+
+/** 让 suggest 返回给定结果,收到的参数记进 $captured */
+function fakeSuggestions(array $rows, ?array &$captured = null): void
+{
+    test()->mock(OpenSearchService::class)
+        ->shouldReceive('suggest')
+        ->andReturnUsing(function (...$args) use ($rows, &$captured) {
+            $captured = $args;
+
+            return $rows;
+        });
+}
+
+it('merges fields, drops duplicate words and caps the total', function () {
+    $captured = null;
+    fakeSuggestions([
+        rawSuggestion('dukkhasutta', 'title_pali', 3.0, 'a'),
+        rawSuggestion('Dukkhasutta', 'content_pali', 2.5, 'b'),   // 同一个词,分数低的丢掉
+        rawSuggestion('dukkha', 'content_pali', 2.0, 'c'),
+        rawSuggestion('dukkhatā', 'content_pali', 1.0, 'd'),
+    ], $captured);
+
+    $res = $this->getJson('/api/v3/search-suggestions?q=dukkha&limit=2')->assertSuccessful();
+
+    expect($res->json('data'))->toHaveCount(2)
+        ->and($res->json('data.0'))->toBe([
+            'text' => 'dukkhasutta', 'source' => 'title_pali', 'score' => 3, 'doc_id' => 'a',
+            'resource_type' => 'tipitaka', 'language' => 'pi', 'granularity' => 'paragraph', 'category' => ['sutta'],
+        ])
+        ->and($res->json('data.1.text'))->toBe('dukkha')
+        ->and($res->json('meta.total'))->toBe(2);
+    // 默认查全部四个字段,每个字段取满 limit 再统一截断
+    expect($captured)->toBe(['dukkha', ['title_pali', 'title_zh', 'content_pali', 'content_zh'], null, 2]);
+});
+
+it('passes only the requested fields', function () {
+    $captured = null;
+    fakeSuggestions([], $captured);
+
+    $this->getJson('/api/v3/search-suggestions?q=nibb&fields=title_pali, content_pali')
+        ->assertSuccessful()
+        ->assertJsonPath('data', [])
+        ->assertJsonPath('meta.total', 0);
+    expect($captured[1])->toBe(['title_pali', 'content_pali'])
+        ->and($captured[3])->toBe(10);
+});
+
+it('rejects invalid parameters', function (array $query, string $field) {
+    $this->getJson('/api/v3/search-suggestions?'.http_build_query($query))
+        ->assertUnprocessable()
+        ->assertJsonValidationErrors($field)
+        ->assertHeader('Content-Type', 'application/problem+json');
+})->with([
+    'missing q' => [[], 'q'],
+    'empty q' => [['q' => ''], 'q'],
+    'unknown field' => [['q' => 'd', 'fields' => 'title'], 'fields'],
+    'only commas' => [['q' => 'd', 'fields' => ',,'], 'fields'],
+    'limit too large' => [['q' => 'd', 'limit' => 51], 'limit'],
+]);
+
+it('answers 503 when the search cluster is unreachable', function () {
+    test()->mock(OpenSearchService::class)
+        ->shouldReceive('suggest')
+        ->andThrow(new ConnectException('Connection refused', new PsrRequest('POST', 'http://opensearch')));
+
+    $res = $this->getJson('/api/v3/search-suggestions?q=dukkha')
+        ->assertServiceUnavailable()
+        ->assertJsonPath('type', 'urn:problem:search-unavailable');
+    expect($res->getContent())->not->toContain('Connection refused');
+});
+
+it('no longer serves the old search-suggest path', function () {
+    $this->getJson('/api/v3/search-suggest?q=dukkha')->assertNotFound();
+});

+ 35 - 16
dashboard-v6/src/api/schema.d.ts

@@ -9065,7 +9065,7 @@ export interface paths {
         patch?: never;
         trace?: never;
     };
-    "/v3/search-suggest": {
+    "/v3/search-suggestions": {
         parameters: {
             query?: never;
             header?: never;
@@ -9073,13 +9073,13 @@ export interface paths {
             cookie?: never;
         };
         /**
-         * 搜索建议(自动补全)
-         * @description 按前缀给出补全候选,供搜索框实时提示。每个字段各自返回一组建议。
-         *     q 为空时返回 400。
+         * 搜索建议
+         * @description 按已输入的前缀给出补全候选,各字段合并后按分数排序、同一个词只出现一次。
+         *     搜索服务连不上或超时回 503(`search-unavailable`)。
          *
-         *     实现:`V3\SearchSuggestController@index`
+         *     实现:`V3\SearchSuggestionController@__invoke`
          */
-        get: operations["get_api_v3_search_suggest"];
+        get: operations["get_api_v3_search_suggestions"];
         put?: never;
         post?: never;
         delete?: never;
@@ -40476,19 +40476,17 @@ export interface operations {
             };
         };
     };
-    get_api_v3_search_suggest: {
+    get_api_v3_search_suggestions: {
         parameters: {
             query: {
-                /** @description 已输入的查询文本 */
+                /** @description 已输入的前缀 */
                 q: string;
-                /** @description 在哪些字段上补全,逗号分隔;不传则全查 */
-                fields?: "title" | "content" | "page_refs";
                 /**
-                 * @description 语言过滤
-                 * @example pali
+                 * @description 在哪些字段上补全,逗号分隔,可选 title_pali、title_zh、content_pali、content_zh;不传则全部
+                 * @example title_pali,content_pali
                  */
-                language?: string;
-                /** @description 每个字段返回的建议数,上限 50 */
+                fields?: string;
+                /** @description 最多返回几条,上限 50 */
                 limit?: number;
             };
             header?: never;
@@ -40504,12 +40502,33 @@ export interface operations {
                 };
                 content: {
                     "application/json": {
-                        data?: Record<string, never>[];
-                        meta?: components["schemas"]["PaginationMeta"];
+                        data?: {
+                            text?: string;
+                            source?: string;
+                            score?: number;
+                            doc_id?: string | null;
+                            resource_type?: string | null;
+                            language?: string | null;
+                            granularity?: string | null;
+                            category?: string[];
+                        }[];
+                        meta?: {
+                            /** @description 本次返回的条数 */
+                            total?: number;
+                        };
                     };
                 };
             };
             422: components["responses"]["ProblemValidation"];
+            /** @description 搜索服务暂不可用 */
+            503: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/problem+json": components["schemas"]["ProblemDetails"];
+                };
+            };
         };
     };
     get_api_v3_search_search_: {

+ 2 - 2
openapi/public/assets/protocol/main.yaml

@@ -853,8 +853,8 @@ paths:
     $ref: ./resources/auto/v3-reactions-tally.yaml
   /v3/search:
     $ref: ./resources/auto/v3-search.yaml
-  /v3/search-suggest:
-    $ref: ./resources/auto/v3-search-suggest.yaml
+  /v3/search-suggestions:
+    $ref: ./resources/auto/v3-search-suggestions.yaml
   '/v3/search/{search}':
     $ref: ./resources/auto/v3-search-search.yaml
   /v3/sessions:

+ 0 - 64
openapi/public/assets/protocol/resources/auto/v3-search-suggest.yaml

@@ -1,64 +0,0 @@
-# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/v3-search-suggest.yaml
-get:
-  summary: 搜索建议(自动补全)
-  tags:
-    - search-suggest
-  operationId: get_api_v3_search_suggest
-  description: |-
-    按前缀给出补全候选,供搜索框实时提示。每个字段各自返回一组建议。
-    q 为空时返回 400。
-
-    实现:`V3\SearchSuggestController@index`
-  security:
-    - {  }
-    -
-      bearerAuth: []
-  parameters:
-    -
-      name: q
-      in: query
-      schema:
-        type: string
-        default: ''
-      description: 已输入的查询文本
-      required: true
-    -
-      name: fields
-      in: query
-      schema:
-        type: string
-        enum:
-          - title
-          - content
-          - page_refs
-      description: 在哪些字段上补全,逗号分隔;不传则全查
-    -
-      name: language
-      in: query
-      schema:
-        type: string
-      description: 语言过滤
-      example: pali
-    -
-      name: limit
-      in: query
-      schema:
-        type: integer
-        default: 10
-      description: '每个字段返回的建议数,上限 50'
-  responses:
-    200:
-      description: 成功
-      content:
-        application/json:
-          schema:
-            type: object
-            properties:
-              data:
-                type: array
-                items:
-                  type: object
-              meta:
-                $ref: '../../main.yaml#/components/schemas/PaginationMeta'
-    422:
-      $ref: '../../main.yaml#/components/responses/ProblemValidation'

+ 85 - 0
openapi/public/assets/protocol/resources/auto/v3-search-suggestions.yaml

@@ -0,0 +1,85 @@
+# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/v3-search-suggestions.yaml
+get:
+  summary: 搜索建议
+  tags:
+    - search-suggestions
+  operationId: get_api_v3_search_suggestions
+  description: |-
+    按已输入的前缀给出补全候选,各字段合并后按分数排序、同一个词只出现一次。
+    搜索服务连不上或超时回 503(`search-unavailable`)。
+
+    实现:`V3\SearchSuggestionController@__invoke`
+  security:
+    - {  }
+    -
+      bearerAuth: []
+  parameters:
+    -
+      name: q
+      in: query
+      schema:
+        type: string
+      description: 已输入的前缀
+      required: true
+    -
+      name: fields
+      in: query
+      schema:
+        type: string
+      description: '在哪些字段上补全,逗号分隔,可选 title_pali、title_zh、content_pali、content_zh;不传则全部'
+      example: 'title_pali,content_pali'
+    -
+      name: limit
+      in: query
+      schema:
+        type: integer
+        default: 10
+      description: '最多返回几条,上限 50'
+  responses:
+    200:
+      description: 成功
+      content:
+        application/json:
+          schema:
+            type: object
+            properties:
+              data:
+                type: array
+                items:
+                  type: object
+                  properties:
+                    text:
+                      type: string
+                    source:
+                      type: string
+                    score:
+                      type: number
+                    doc_id:
+                      type: string
+                      nullable: true
+                    resource_type:
+                      type: string
+                      nullable: true
+                    language:
+                      type: string
+                      nullable: true
+                    granularity:
+                      type: string
+                      nullable: true
+                    category:
+                      type: array
+                      items: { type: string }
+              meta:
+                type: object
+                properties:
+                  total:
+                    type: integer
+                    description: 本次返回的条数
+    422:
+      $ref: '../../main.yaml#/components/responses/ProblemValidation'
+    503:
+      description: 搜索服务暂不可用
+      content:
+        application/problem+json:
+          schema:
+            $ref: '../../main.yaml#/components/schemas/ProblemDetails'