dsh-querit 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +169 -169
  2. package/cordis.patch.yml +24 -24
  3. package/lib/card.js +870 -816
  4. package/package.json +136 -137
  5. package/README-zh.md +0 -128
package/lib/card.js CHANGED
@@ -1,817 +1,871 @@
1
- /**
2
- * dsh-querit browser bundle — Querit settings card.
3
- *
4
- * Built by scripts/build-client.mjs into lib/card.js (do not edit the
5
- * generated file). The browser loader wraps this module; the node-side unit
6
- * tests cover the form model definitions in src/form-model.js, which this
7
- * bundle inlines below.
8
- *
9
- * Plain JavaScript only: no TS, no JSX, no imports — `require` resolves
10
- * against the browser module loader, and React comes from the shared kernel.
11
- */
12
- (function (root, factory) {
13
- if (root && typeof root.__ModuleLoader__ === 'object' && typeof root.__ModuleLoader__.load === 'function') {
14
- root.__ModuleLoader__.load({ id: 'dsh-querit', factory: factory });
15
- return;
16
- }
17
- if (typeof module !== 'undefined' && module.exports) {
18
- module.exports = factory(require);
19
- }
20
- })(typeof window !== 'undefined' ? window : globalThis, function (require) {
21
- 'use strict';
22
- var module = { exports: {} };
23
- var exports = module.exports;
24
- var React = require('react');
25
-
26
- /**
27
- * Pure form model behind the dsh-querit settings card.
28
- *
29
- * This file is the SINGLE SOURCE of truth for the card's field conversions and
30
- * save planning. The browser bundle inlines these exact definitions (see
31
- * scripts/build-client.mjs); the node-side unit tests import them through the
32
- * exports at the bottom. Keep everything here free of DOM, React, and window
33
- * references so both consumers can run it.
34
- */
35
-
36
- /**
37
- * A whole-number field. An empty draft clears the field; any other draft that
38
- * is not a finite number blocks the save.
39
- * @param {string} field - field name inside the namespace section.
40
- * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
41
- */
42
- function numberField(field) {
43
- return {
44
- field,
45
- format: (value) => (typeof value === 'number' ? String(value) : ''),
46
- parse: (text) => {
47
- const trimmed = text.trim();
48
- if (trimmed === '') return { kind: 'clear' };
49
- const parsed = Number(trimmed);
50
- return Number.isFinite(parsed)
51
- ? { kind: 'set', value: parsed }
52
- : undefined;
53
- },
54
- };
55
- }
56
-
57
- /**
58
- * A free-text field. An empty draft clears the field, so emptying the control
59
- * and saving is the same gesture as resetting it.
60
- * @param {string} field - field name inside the namespace section.
61
- * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
62
- */
63
- function textField(field) {
64
- return {
65
- field,
66
- format: (value) => (typeof value === 'string' ? value : ''),
67
- parse: (text) => {
68
- const trimmed = text.trim();
69
- return trimmed === '' ? { kind: 'clear' } : { kind: 'set', value: trimmed };
70
- },
71
- };
72
- }
73
-
74
- /**
75
- * A comma-separated list field (string[] ↔ "a, b, c"). An empty draft clears
76
- * the field; duplicates and blank entries are dropped.
77
- * @param {string} field - field name inside the namespace section.
78
- * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
79
- */
80
- function listField(field) {
81
- return {
82
- field,
83
- format: (value) => (Array.isArray(value) ? value.join(', ') : ''),
84
- parse: (text) => {
85
- const trimmed = text.trim();
86
- if (trimmed === '') return { kind: 'clear' };
87
- const seen = new Set();
88
- const items = [];
89
- for (const raw of trimmed.split(',')) {
90
- const item = raw.trim();
91
- if (item === '' || seen.has(item)) continue;
92
- seen.add(item);
93
- items.push(item);
94
- }
95
- return { kind: 'set', value: items };
96
- },
97
- };
98
- }
99
-
100
- /**
101
- * A boolean toggle field. It always writes a value; there is no "clear".
102
- * @param {string} field - field name inside the namespace section.
103
- * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
104
- */
105
- function booleanField(field) {
106
- return {
107
- field,
108
- format: (value) => (typeof value === 'boolean' ? String(value) : 'false'),
109
- parse: (text) => ({ kind: 'set', value: text === 'true' }),
110
- choices: ['true', 'false'],
111
- };
112
- }
113
-
114
- /**
115
- * A single-choice field over a fixed set of strings.
116
- * @param {string} field - field name inside the namespace section.
117
- * @param {readonly string[]} choices - acceptable values.
118
- * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
119
- */
120
- function enumField(field, choices) {
121
- return {
122
- field,
123
- format: (value) => (typeof value === 'string' && choices.includes(value) ? value : ''),
124
- parse: (text) => {
125
- const trimmed = text.trim();
126
- if (trimmed === '') return { kind: 'clear' };
127
- return choices.includes(trimmed) ? { kind: 'set', value: trimmed } : undefined;
128
- },
129
- choices,
130
- };
131
- }
132
-
133
- /**
134
- * A write-only control staged outside the settings section (the API key is
135
- * stored in the credentials domain, never in the settings document).
136
- * @param {string} field - field name this control stages under.
137
- * @param {(value: string) => Promise<boolean>} write - persist the literal.
138
- * @returns {import('./client-types.js').SecretSpec} the secret's spec.
139
- */
140
- function secretSpec(field, write) {
141
- return { field, write };
142
- }
143
-
144
- /**
145
- * The staged form model one settings card runs on.
146
- *
147
- * A card stages what the user types and writes it only when they save. Each
148
- * settings write is a durable, revision-fenced document mutation, so nothing
149
- * commits as the user types. A field shows its effective value — the user
150
- * layer over the composition layer over the schema default — and whether the
151
- * user layer carries it; that presence, not a value comparison, is what marks
152
- * a field overridden.
153
- */
154
- class QueritFormModel {
155
- /** @param {import('./client-types.js').SettingsScope} scope - bound settings scope for the namespace. */
156
- constructor(scope, specs, secrets = []) {
157
- this.scope = scope;
158
- this.specs = new Map(specs.map((spec) => [spec.field, spec]));
159
- this.secretSpecs = new Map(secrets.map((spec) => [spec.field, spec]));
160
- this.staged = new Map();
161
- this.listeners = new Set();
162
- this.saving = false;
163
- this.failed = false;
164
- scope.subscribe(() => this.publish());
165
- }
166
-
167
- /**
168
- * Publish a projection of this form rebuilt whenever the scope or a draft
169
- * changes.
170
- * @param {() => object} project - build the card's state from the form reads.
171
- * @returns {import('./client-types.js').SnapshotStore} the store the component reads.
172
- */
173
- bind(project) {
174
- const store = makeStore(project());
175
- this.listeners.add(() => {
176
- store.set(project());
177
- });
178
- return store;
179
- }
180
-
181
- /** Read the card-level state: what the Host serves, and what a save would do. */
182
- shell() {
183
- const snapshot = this.scope.getSnapshot();
184
- const plan = this.plan();
185
- return {
186
- available: snapshot.status === 'ready',
187
- writable: snapshot.writable === true,
188
- dirty: plan.length > 0,
189
- invalid: plan.some((item) => item.run === undefined),
190
- saving: this.saving,
191
- failed: this.failed,
192
- };
193
- }
194
-
195
- /** Read one control's state. */
196
- field(field) {
197
- const staged = this.staged.get(field);
198
- if (this.secretSpecs.has(field)) {
199
- return { text: staged?.text ?? '', overridden: false, invalid: false };
200
- }
201
- const spec = this.spec(field);
202
- if (staged === undefined) {
203
- return {
204
- text: spec.format(this.sectionValue(field)),
205
- overridden: this.stored(field),
206
- invalid: false,
207
- };
208
- }
209
- const write = staged.clear ? { kind: 'clear' } : spec.parse(staged.text);
210
- return {
211
- text: staged.text,
212
- overridden: write?.kind === 'set',
213
- invalid: write === undefined,
214
- };
215
- }
216
-
217
- /** The actions a card's slot entry injects. */
218
- actions() {
219
- return {
220
- edit: (field, text) => {
221
- this.stage(field, { text, clear: false });
222
- },
223
- resetField: (field) => {
224
- if (this.secretSpecs.has(field)) return;
225
- this.stage(field, { text: this.spec(field).format(this.baseValue(field)), clear: true });
226
- },
227
- save: () => {
228
- return this.save();
229
- },
230
- discard: () => {
231
- if (this.staged.size === 0 && !this.failed) return;
232
- this.staged.clear();
233
- this.failed = false;
234
- this.publish();
235
- },
236
- };
237
- }
238
-
239
- /**
240
- * Write every staged edit, then re-seed from what the Host accepted. The Host
241
- * is the only authority on whether a value was accepted, so the outcome is
242
- * read back from the scope rather than predicted here.
243
- */
244
- async save() {
245
- const plan = this.plan();
246
- const writes = plan.flatMap((item) => (item.run === undefined ? [] : [item.run]));
247
- if (plan.length === 0 || this.saving || writes.length !== plan.length) return;
248
- this.saving = true;
249
- this.failed = false;
250
- this.publish();
251
- let landed = true;
252
- for (const write of writes) landed = (await write()) && landed;
253
- if (landed) this.staged.clear();
254
- this.saving = false;
255
- this.failed = !landed;
256
- this.publish();
257
- }
258
-
259
- /** Every staged edit a save would write, in the order the fields were staged. */
260
- plan() {
261
- const plan = [];
262
- for (const [field, staged] of this.staged) {
263
- const secret = this.secretSpecs.get(field);
264
- if (secret !== undefined) {
265
- const value = staged.text.trim();
266
- if (value !== '') {
267
- plan.push({ field, run: () => secret.write(value).then((ok) => !!ok) });
268
- }
269
- continue;
270
- }
271
- const spec = this.spec(field);
272
- if (staged.clear) {
273
- if (this.stored(field)) plan.push({ field, run: () => this.clear(field) });
274
- continue;
275
- }
276
- if (staged.text === spec.format(this.sectionValue(field))) continue;
277
- const write = spec.parse(staged.text);
278
- if (write === undefined) plan.push({ field, run: undefined });
279
- else if (write.kind === 'clear') plan.push({ field, run: () => this.clear(field) });
280
- else plan.push({ field, run: () => this.store(field, write.value) });
281
- }
282
- return plan;
283
- }
284
-
285
- stage(field, draft) {
286
- this.staged.set(field, draft);
287
- this.publish();
288
- }
289
-
290
- publish() {
291
- for (const listener of this.listeners) listener();
292
- }
293
-
294
- spec(field) {
295
- const spec = this.specs.get(field);
296
- if (spec === undefined) throw new Error(`querit card: unknown field "${field}"`);
297
- return spec;
298
- }
299
-
300
- sectionValue(field) {
301
- return this.scope.getSnapshot().value?.[field];
302
- }
303
-
304
- stored(field) {
305
- const user = this.scope.getSnapshot().user;
306
- return typeof user === 'object' && user !== null && Object.prototype.hasOwnProperty.call(user, field);
307
- }
308
-
309
- baseValue(field) {
310
- return this.scope.getSnapshot().base?.[field];
311
- }
312
-
313
- clear(field) {
314
- return this.scope.unset(field);
315
- }
316
-
317
- store(field, value) {
318
- return this.scope.set(field, value);
319
- }
320
- }
321
-
322
- /** Minimal snapshot store: stable state object, getSnapshot, subscribe, set. */
323
- function makeStore(initial) {
324
- let state = initial;
325
- const listeners = new Set();
326
- return {
327
- getSnapshot: () => state,
328
- subscribe: (listener) => {
329
- listeners.add(listener);
330
- return () => listeners.delete(listener);
331
- },
332
- set: (next) => {
333
- state = next;
334
- for (const listener of listeners) listener();
335
- },
336
- };
337
- }
338
-
339
- var NS = 'dsh-querit';
340
- var NAMESPACE = 'web-search-querit';
341
- var DEFAULT_API_KEY_REF = 'QUERIT_API_KEY';
342
- var FETCH_FORMATS = ['markdown', 'text', 'html'];
343
-
344
- /* Card styles: scoped classes over the theme's alias tokens. */
345
- (function injectCardCss() {
346
- if (typeof document === 'undefined') return;
347
- var tagId = NS + '/card.css';
348
- if (document.querySelector('style[data-plugin-css="' + tagId + '"]') !== null) return;
349
- var css = [
350
- '.qr-card{list-style:none;border:1px solid var(--dsw-alias-border-l2);border-radius:12px;background:var(--dsw-alias-bg-layer-2)}',
351
- '.qr-header{display:flex;align-items:center;gap:8px;width:100%;padding:12px 16px;background:none;border:0;cursor:pointer;color:inherit;font:inherit;text-align:left}',
352
- '.qr-head{flex:1;min-width:0}',
353
- '.qr-name{display:block;color:var(--dsw-alias-label-primary);font-size:14px;font-weight:600;line-height:1.5}',
354
- '.qr-desc{display:block;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:1.5}',
355
- '.qr-badge{white-space:nowrap;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary);border-radius:999px;padding:1px 8px;font-size:11px;line-height:17px}',
356
- '.qr-chev{color:var(--dsw-alias-label-tertiary);font-size:14px;line-height:1}',
357
- '.qr-body{border-top:1px solid var(--dsw-alias-border-l2);padding:0 16px 12px}',
358
- '.qr-readonly{color:var(--dsw-alias-label-tertiary);margin:8px 0 0;font-size:12px}',
359
- '.qr-field{display:flex;flex-direction:column;gap:6px;padding:12px 0;border-bottom:1px solid var(--dsw-alias-border-l1)}',
360
- '.qr-field:last-child{border-bottom:0}',
361
- '.qr-fhead{display:flex;align-items:center;gap:8px}',
362
- '.qr-grow{flex:1}',
363
- '.qr-label{flex:1;min-width:0;color:var(--dsw-alias-label-primary);font-size:13px;font-weight:500;line-height:1.5}',
364
- '.qr-tag{white-space:nowrap;color:var(--dsw-alias-label-tertiary);border-radius:999px;padding:1px 8px;font-size:11px;line-height:17px}',
365
- '.qr-tagOver{white-space:nowrap;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary);border-radius:999px;padding:1px 8px;font-size:11px;line-height:17px}',
366
- '.qr-reset{font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;background:none;border:none;padding:0;font-size:12px;line-height:1.5}',
367
- '.qr-reset:hover:not(:disabled){color:var(--dsw-alias-label-primary)}',
368
- '.qr-reset:disabled{cursor:default}',
369
- '.qr-input{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);height:34px;font:inherit;color:var(--dsw-alias-label-primary);border-radius:8px;padding:0 12px;font-size:13px;line-height:1.5;box-sizing:border-box}',
370
- '.qr-input:focus-visible{border-color:var(--dsw-alias-brand-primary);outline:none}',
371
- '.qr-input:disabled{color:var(--dsw-alias-label-tertiary);cursor:default}',
372
- '.qr-check{width:16px;height:16px;accent-color:var(--dsw-alias-brand-primary);cursor:pointer;flex:none}',
373
- '.qr-check:disabled{cursor:default}',
374
- '.qr-invalid{border-color:var(--dsw-alias-label-error)}',
375
- '.qr-err{color:var(--dsw-alias-label-error);margin:0;font-size:12px;line-height:1.5}',
376
- '.qr-hint{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}',
377
- '.qr-keybadge{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.5}',
378
- '.qr-foot{display:flex;align-items:center;justify-content:flex-end;gap:8px;padding-top:12px}',
379
- '.qr-failed{color:var(--dsw-alias-label-error);margin:0;font-size:12px;line-height:1.5;flex:1}',
380
- '.qr-btn{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-primary);border-radius:8px;padding:6px 14px;font:inherit;font-size:13px;cursor:pointer}',
381
- '.qr-btn:hover:not(:disabled){border-color:var(--dsw-alias-label-secondary)}',
382
- '.qr-save{border-color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-primary);font-weight:600}',
383
- '.qr-btn:disabled{opacity:.5;cursor:default}'
384
- ].join('');
385
- var tag = document.createElement('style');
386
- tag.dataset.plugin = NS;
387
- tag.dataset.pluginCss = tagId;
388
- tag.textContent = css;
389
- document.head.appendChild(tag);
390
- })();
391
-
392
- var en = {
393
- title: 'Querit web search',
394
- description: 'Querit-backed search and fetch provider.',
395
- readOnly: 'This deployment stores settings read-only.',
396
- pass: 'Password',
397
- save: 'Save',
398
- saving: 'Saving\u2026',
399
- discard: 'Discard',
400
- unsaved: 'Unsaved',
401
- overridden: 'Overridden',
402
- reset: 'Reset to default',
403
- saveFailed: 'The deployment did not accept these values; they were left for you to correct.',
404
- invalidNumber: 'Enter a number, or leave blank to use the default.',
405
- keyLabel: 'API key',
406
- keyHint: 'Stored outside the settings file. Leave blank to keep the current key.',
407
- keySet: 'A key is configured for',
408
- keyUnset: 'No key is configured; search fails until one is set via the credentials file or here.',
409
- refLabel: 'Credential reference',
410
- refHint: 'Environment variable / credentials-store name the provider resolves per call.',
411
- countLabel: 'Result count',
412
- countHint: 'Results per search when no explicit bound is given (1\u201320).',
413
- timeRangeLabel: 'Time range',
414
- timeRangeHint: 'Relative (d7, w2, m3, y1, \u2026) or YYYY-MM-DDtoYYYY-MM-DD.',
415
- languagesLabel: 'Languages',
416
- languagesHint: 'Comma-separated: english, japanese, korean, german, french, spanish, portuguese.',
417
- countriesLabel: 'Countries',
418
- countriesHint: 'Comma-separated country bias (argentina, australia, brazil, \u2026).',
419
- includeLabel: 'Include domains',
420
- includeHint: 'Whitelist hostnames; only these domains return results.',
421
- excludeLabel: 'Exclude domains',
422
- excludeHint: 'Blacklist hostnames; these domains never return results.',
423
- contentLabel: 'Include content excerpts',
424
- contentHint: 'Request sentence-level content excerpts alongside snippets.',
425
- formatLabel: 'Fetch format',
426
- formatHint: 'Format requested from /v1/contents for fetch calls.'
427
- };
428
- var zh = {
429
- title: 'Querit 网页搜索',
430
- description: '基于 Querit 的搜索与抓取提供方。',
431
- readOnly: '本部署的设置为只读。',
432
- pass: '密码',
433
- save: '保存',
434
- saving: '保存中\u2026',
435
- discard: '放弃修改',
436
- unsaved: '未保存',
437
- overridden: '已覆盖',
438
- reset: '恢复默认',
439
- saveFailed: '本部署没有接受这些值,已保留供你修改。',
440
- invalidNumber: '请填数字;留空表示使用默认值。',
441
- keyLabel: 'API Key',
442
- keyHint: '不写入设置文件。留空表示保持当前密钥。',
443
- keySet: '已为',
444
- keyUnset: '未配置密钥;请在凭据文件或此处配置后搜索才可用。',
445
- refLabel: '凭据引用名',
446
- refHint: '每次调用解析的环境变量 / 凭据存储键名。',
447
- countLabel: '结果数量',
448
- countHint: '未指定上限时每次搜索返回的结果数(1–20)。',
449
- timeRangeLabel: '时间范围',
450
- timeRangeHint: '相对(d7、w2、m3、y1…)或 YYYY-MM-DDtoYYYY-MM-DD。',
451
- languagesLabel: '语言',
452
- languagesHint: '逗号分隔:english、japanese、korean、german、french、spanish、portuguese。',
453
- countriesLabel: '国家',
454
- countriesHint: '逗号分隔的国家偏好(argentina、australia、brazil…)。',
455
- includeLabel: '仅限域名',
456
- includeHint: '白名单主机名;只返回这些域的结果。',
457
- excludeLabel: '排除域名',
458
- excludeHint: '黑名单主机名;这些域永不返回结果。',
459
- contentLabel: '包含内容摘要',
460
- contentHint: '在摘要旁请求句子级内容摘录。',
461
- formatLabel: '抓取格式',
462
- formatHint: '/v1/contents 抓取请求的格式。'
463
- };
464
-
465
- /** The credential reference the section names, or the provider default. */
466
- function refOf(snapshot) {
467
- var declared = snapshot.value && snapshot.value.apiKeyEnv;
468
- return declared !== undefined && declared.length > 0 ? declared : DEFAULT_API_KEY_REF;
469
- }
470
-
471
- /** Bridges the web-search-querit scope and the credentials domain onto the card. */
472
- function QueritCardController(scope, api) {
473
- this.scope = scope;
474
- this.api = api;
475
- this.credential = { ref: '', configured: false, writable: true };
476
- this.form = new QueritFormModel(
477
- scope,
478
- [
479
- textField('apiKeyEnv'),
480
- numberField('count'),
481
- textField('timeRange'),
482
- listField('languages'),
483
- listField('countries'),
484
- listField('includeDomains'),
485
- listField('excludeDomains'),
486
- booleanField('includeContent'),
487
- enumField('fetchFormat', FETCH_FORMATS)
488
- ],
489
- [secretSpec('apiKey', (value) => this.writeKey(value))]
490
- );
491
- this.store = this.form.bind(() => this.projection());
492
- var self = this;
493
- scope.subscribe(() => {
494
- self.readCredential();
495
- });
496
- this.readCredential();
497
- }
498
-
499
- QueritCardController.prototype.projection = function () {
500
- return {
501
- ...this.form.shell(),
502
- apiKeyEnv: this.form.field('apiKeyEnv'),
503
- count: this.form.field('count'),
504
- timeRange: this.form.field('timeRange'),
505
- languages: this.form.field('languages'),
506
- countries: this.form.field('countries'),
507
- includeDomains: this.form.field('includeDomains'),
508
- excludeDomains: this.form.field('excludeDomains'),
509
- includeContent: this.form.field('includeContent'),
510
- fetchFormat: this.form.field('fetchFormat'),
511
- apiKey: this.form.field('apiKey'),
512
- apiKeyConfigured: this.credential.configured,
513
- apiKeyWritable: this.credential.writable,
514
- apiKeyRef: this.credential.ref
515
- };
516
- };
517
-
518
- QueritCardController.prototype.readCredential = function () {
519
- var self = this;
520
- var ref = refOf(this.scope.getSnapshot());
521
- if (ref !== this.credential.ref) {
522
- this.credential = { ref: ref, configured: false, writable: true };
523
- this.store.set(this.projection());
524
- }
525
- this.api.credentials
526
- .describe({ refs: [ref] })
527
- .then(function (response) {
528
- if (!response || !response.result || !response.result.ok) return;
529
- if (ref !== refOf(self.scope.getSnapshot())) return;
530
- var view = response.result.value.credentials[ref];
531
- var next = {
532
- ref: ref,
533
- configured: view && view.configured === true,
534
- writable: !view || view.writable !== false
535
- };
536
- if (next.configured === self.credential.configured && next.writable === self.credential.writable) return;
537
- self.credential = next;
538
- self.store.set(self.projection());
539
- })
540
- .catch(function () {});
541
- };
542
-
543
- QueritCardController.prototype.refreshCredential = function (ref) {
544
- if (ref !== this.credential.ref) return;
545
- this.readCredential();
546
- };
547
-
548
- QueritCardController.prototype.writeKey = function (value) {
549
- var self = this;
550
- return this.api.credentials
551
- .set({ ref: refOf(this.scope.getSnapshot()), value: value })
552
- .then(function () {
553
- return self.readCredential();
554
- })
555
- .catch(function () {
556
- return self.readCredential();
557
- })
558
- .then(function () {
559
- return self.credential.configured;
560
- });
561
- };
562
-
563
- QueritCardController.prototype.inject = function () {
564
- return {
565
- hooks: { queritCard: this.store },
566
- ...this.form.actions()
567
- };
568
- };
569
-
570
- /** One labeled control row. `inline` puts the control on the label line (toggle rows). */
571
- function FieldRow(props) {
572
- var inline = props.inline === true;
573
- return React.createElement(
574
- 'div',
575
- { className: 'qr-field' },
576
- React.createElement(
577
- 'div',
578
- { className: 'qr-fhead' },
579
- React.createElement('span', { className: 'qr-label' }, props.label),
580
- props.state && props.state.overridden
581
- ? React.createElement('span', { className: 'qr-tagOver' }, props.overriddenLabel)
582
- : null,
583
- props.state && props.onReset
584
- ? React.createElement(
585
- 'button',
586
- { type: 'button', className: 'qr-reset', disabled: props.disabled || !props.state.overridden, onClick: props.onReset },
587
- props.resetLabel
588
- )
589
- : null,
590
- inline ? React.createElement('span', { className: 'qr-grow' }) : null,
591
- inline ? props.children : null
592
- ),
593
- inline ? null : props.children,
594
- props.state && props.state.invalid ? React.createElement('p', { className: 'qr-err' }, props.invalidLabel) : null,
595
- props.hint ? React.createElement('p', { className: 'qr-hint' }, props.hint) : null
596
- );
597
- }
598
-
599
- /** Render one plugin card: header naming the provider, disclosing its controls in place. */
600
- function QueritCard(props) {
601
- var t = props.t || function (key) {
602
- return zh[key] || en[key] || key;
603
- };
604
- var state = props.useQueritCard(function (snapshot) {
605
- return snapshot;
606
- });
607
- var openState = React.useState(props.defaultOpen === true);
608
- var open = openState[0];
609
- var setOpen = openState[1];
610
- if (!state.available) return null;
611
- var disabled = !state.writable;
612
- var blocked = !state.dirty || state.invalid || state.saving;
613
- var text = function (control) {
614
- return control.text;
615
- };
616
- return React.createElement(
617
- 'li',
618
- { className: 'qr-card' + (open ? ' qr-open' : '') },
619
- React.createElement(
620
- 'button',
621
- { type: 'button', className: 'qr-header', 'aria-expanded': open ? 'true' : 'false', onClick: function () { setOpen(!open); } },
622
- React.createElement(
623
- 'span',
624
- { className: 'qr-head' },
625
- React.createElement('span', { className: 'qr-name' }, t('title')),
626
- React.createElement('span', { className: 'qr-desc' }, t('description'))
627
- ),
628
- state.dirty ? React.createElement('span', { className: 'qr-badge' }, t('unsaved')) : null,
629
- React.createElement('span', { className: 'qr-chev' }, open ? '\u2212' : '+')
630
- ),
631
- open
632
- ? React.createElement(
633
- 'div',
634
- { className: 'qr-body' },
635
- disabled ? React.createElement('p', { className: 'qr-readonly' }, t('readOnly')) : null,
636
- React.createElement(
637
- FieldRow,
638
- {
639
- label: t('keyLabel'),
640
- hint: t('keyHint'),
641
- state: state.apiKey,
642
- disabled: disabled || !state.apiKeyWritable,
643
- invalidLabel: t('invalidNumber')
644
- },
645
- React.createElement('input', {
646
- className: 'qr-input',
647
- type: 'password',
648
- autoComplete: 'new-password',
649
- disabled: disabled || !state.apiKeyWritable,
650
- placeholder: state.apiKeyConfigured ? '\u2022\u2022\u2022\u2022\u2022\u2022' : '',
651
- value: text(state.apiKey),
652
- onChange: function (event) { props.edit('apiKey', event.target.value); }
653
- })
654
- ),
655
- React.createElement(
656
- 'p',
657
- { className: 'qr-keybadge' },
658
- state.apiKeyConfigured ? t('keySet') + ' ' + state.apiKeyRef + '.' : t('keyUnset')
659
- ),
660
- field(
661
- props,
662
- t('refLabel'),
663
- t('refHint'),
664
- state.apiKeyEnv,
665
- 'apiKeyEnv',
666
- disabled
667
- ),
668
- field(props, t('countLabel'), t('countHint'), state.count, 'count', disabled),
669
- field(props, t('timeRangeLabel'), t('timeRangeHint'), state.timeRange, 'timeRange', disabled),
670
- field(props, t('languagesLabel'), t('languagesHint'), state.languages, 'languages', disabled),
671
- field(props, t('countriesLabel'), t('countriesHint'), state.countries, 'countries', disabled),
672
- field(props, t('includeLabel'), t('includeHint'), state.includeDomains, 'includeDomains', disabled),
673
- field(props, t('excludeLabel'), t('excludeHint'), state.excludeDomains, 'excludeDomains', disabled),
674
- React.createElement(
675
- FieldRow,
676
- {
677
- label: t('contentLabel'),
678
- hint: t('contentHint'),
679
- state: state.includeContent,
680
- disabled: disabled,
681
- inline: true,
682
- overriddenLabel: t('overridden'),
683
- resetLabel: t('reset'),
684
- onReset: function () { props.resetField('includeContent'); }
685
- },
686
- React.createElement('input', {
687
- className: 'qr-check',
688
- type: 'checkbox',
689
- disabled: disabled,
690
- checked: state.includeContent.text === 'true',
691
- onChange: function (event) { props.edit('includeContent', event.target.checked ? 'true' : 'false'); }
692
- })
693
- ),
694
- React.createElement(
695
- FieldRow,
696
- {
697
- label: t('formatLabel'),
698
- hint: t('formatHint'),
699
- state: state.fetchFormat,
700
- disabled: disabled,
701
- overriddenLabel: t('overridden'),
702
- resetLabel: t('reset'),
703
- onReset: function () { props.resetField('fetchFormat'); }
704
- },
705
- React.createElement(
706
- 'select',
707
- {
708
- className: 'qr-input',
709
- disabled: disabled,
710
- value: text(state.fetchFormat),
711
- onChange: function (event) { props.edit('fetchFormat', event.target.value); }
712
- },
713
- FETCH_FORMATS.map(function (format) {
714
- return React.createElement('option', { key: format, value: format }, format);
715
- })
716
- )
717
- ),
718
- React.createElement(
719
- 'div',
720
- { className: 'qr-foot' },
721
- state.failed ? React.createElement('p', { className: 'qr-failed' }, t('saveFailed')) : null,
722
- React.createElement(
723
- 'button',
724
- { type: 'button', className: 'qr-btn', disabled: (!state.dirty && !state.failed) || state.saving, onClick: props.discard },
725
- t('discard')
726
- ),
727
- React.createElement(
728
- 'button',
729
- { type: 'button', className: 'qr-btn qr-save', disabled: blocked, onClick: props.save },
730
- t(state.saving ? 'saving' : 'save')
731
- )
732
- )
733
- )
734
- : null
735
- );
736
- }
737
-
738
- /** Extract one section field's row into a shared control render. */
739
- function field(props, label, hint, state, name, disabled) {
740
- return React.createElement(
741
- FieldRow,
742
- {
743
- label: label,
744
- hint: hint,
745
- state: state,
746
- disabled: disabled,
747
- invalidLabel: name === 'count' ? props.t('invalidNumber') : '',
748
- overriddenLabel: props.t('overridden'),
749
- resetLabel: props.t('reset'),
750
- onReset: function () { props.resetField(name); }
751
- },
752
- React.createElement('input', {
753
- className: 'qr-input' + (state.invalid ? ' qr-invalid' : ''),
754
- type: name === 'count' ? 'number' : 'text',
755
- disabled: disabled,
756
- value: state.text,
757
- onChange: function (event) { props.edit(name, event.target.value); }
758
- })
759
- );
760
- }
761
-
762
- /** Required services (cordis fiber inject). */
763
- var inject = ['slots', 'connection', 'settingsScope', 'remote', 'locale'];
764
-
765
- /**
766
- * Mount the Querit settings card into the plugins configuration tab.
767
- * @param ctx - the browser plugin context.
768
- */
769
- function apply(ctx) {
770
- var slots = ctx.get('slots');
771
- var scopeService = ctx.get('settingsScope');
772
- var locale = ctx.get('locale');
773
- var api = ctx.get('connection');
774
- if (slots === undefined || scopeService === undefined || locale === undefined || api === undefined) return;
775
- api = api.api;
776
- // Register the card dictionaries, then bind our own translator. The slot
777
- // framework may also deliver a `t` seat from the entry's `locale` option,
778
- // but binding here guarantees text resolves even if that seat is not yet
779
- // backed for this entry.
780
- var dicts = { zh: zh, en: en };
781
- ctx.effect(function () {
782
- return locale.register(NS, dicts);
783
- }, 'dsh-querit: card dictionaries');
784
- var t = locale.bind(NS);
785
- var scope = scopeService.bind({ namespace: NAMESPACE });
786
- var controller = new QueritCardController(scope, api);
787
- var remote = ctx.get('remote');
788
- if (remote !== undefined) {
789
- ctx.effect(function () {
790
- return remote.$on('credentials/updated', function (ref) {
791
- controller.refreshCredential(ref);
792
- });
793
- }, 'dsh-querit: credential invalidations');
794
- }
795
- slots.inject('settings.plugin.item', function () {
796
- return slots.register(
797
- {
798
- name: 'settings.plugin.item',
799
- key: NAMESPACE,
800
- locale: NS,
801
- inject: function () {
802
- var face = controller.inject();
803
- face.t = t;
804
- return face;
805
- }
806
- },
807
- QueritCard
808
- );
809
- });
810
- }
811
-
812
- exports.apply = apply;
813
- exports.inject = inject;
814
- exports.QueritCardController = QueritCardController;
815
- exports.QueritCard = QueritCard;
816
- return module.exports;
1
+ /**
2
+ * dsh-querit browser bundle — Querit settings card.
3
+ *
4
+ * Built by scripts/build-client.mjs into lib/card.js (do not edit the
5
+ * generated file). The browser loader wraps this module; the node-side unit
6
+ * tests cover the form model definitions in src/form-model.js, which this
7
+ * bundle inlines below.
8
+ *
9
+ * Plain JavaScript only: no TS, no JSX, no imports — `require` resolves
10
+ * against the browser module loader, and React comes from the shared kernel.
11
+ */
12
+ (function (root, factory) {
13
+ if (root && typeof root.__ModuleLoader__ === 'object' && typeof root.__ModuleLoader__.load === 'function') {
14
+ root.__ModuleLoader__.load({ id: 'dsh-querit', factory: factory });
15
+ return;
16
+ }
17
+ if (typeof module !== 'undefined' && module.exports) {
18
+ module.exports = factory(require);
19
+ }
20
+ })(typeof window !== 'undefined' ? window : globalThis, function (require) {
21
+ 'use strict';
22
+ var module = { exports: {} };
23
+ var exports = module.exports;
24
+ var React = require('react');
25
+
26
+ /**
27
+ * Pure form model behind the dsh-querit settings card.
28
+ *
29
+ * This file is the SINGLE SOURCE of truth for the card's field conversions and
30
+ * save planning. The browser bundle inlines these exact definitions (see
31
+ * scripts/build-client.mjs); the node-side unit tests import them through the
32
+ * exports at the bottom. Keep everything here free of DOM, React, and window
33
+ * references so both consumers can run it.
34
+ */
35
+
36
+ /**
37
+ * A whole-number field. An empty draft clears the field; any other draft that
38
+ * is not a finite number blocks the save.
39
+ * @param {string} field - field name inside the namespace section.
40
+ * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
41
+ */
42
+ function numberField(field) {
43
+ return {
44
+ field,
45
+ format: (value) => (typeof value === 'number' ? String(value) : ''),
46
+ parse: (text) => {
47
+ const trimmed = text.trim();
48
+ if (trimmed === '') return { kind: 'clear' };
49
+ const parsed = Number(trimmed);
50
+ return Number.isFinite(parsed)
51
+ ? { kind: 'set', value: parsed }
52
+ : undefined;
53
+ },
54
+ };
55
+ }
56
+
57
+ /**
58
+ * A free-text field. An empty draft clears the field, so emptying the control
59
+ * and saving is the same gesture as resetting it.
60
+ * @param {string} field - field name inside the namespace section.
61
+ * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
62
+ */
63
+ function textField(field) {
64
+ return {
65
+ field,
66
+ format: (value) => (typeof value === 'string' ? value : ''),
67
+ parse: (text) => {
68
+ const trimmed = text.trim();
69
+ return trimmed === '' ? { kind: 'clear' } : { kind: 'set', value: trimmed };
70
+ },
71
+ };
72
+ }
73
+
74
+ /**
75
+ * A comma-separated list field (string[] ↔ "a, b, c"). An empty draft clears
76
+ * the field; duplicates and blank entries are dropped.
77
+ * @param {string} field - field name inside the namespace section.
78
+ * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
79
+ */
80
+ function listField(field) {
81
+ return {
82
+ field,
83
+ format: (value) => (Array.isArray(value) ? value.join(', ') : ''),
84
+ parse: (text) => {
85
+ const trimmed = text.trim();
86
+ if (trimmed === '') return { kind: 'clear' };
87
+ const seen = new Set();
88
+ const items = [];
89
+ for (const raw of trimmed.split(',')) {
90
+ const item = raw.trim();
91
+ if (item === '' || seen.has(item)) continue;
92
+ seen.add(item);
93
+ items.push(item);
94
+ }
95
+ return { kind: 'set', value: items };
96
+ },
97
+ };
98
+ }
99
+
100
+ /**
101
+ * A boolean toggle field. It always writes a value; there is no "clear".
102
+ * @param {string} field - field name inside the namespace section.
103
+ * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
104
+ */
105
+ function booleanField(field) {
106
+ return {
107
+ field,
108
+ format: (value) => (typeof value === 'boolean' ? String(value) : 'false'),
109
+ parse: (text) => ({ kind: 'set', value: text === 'true' }),
110
+ choices: ['true', 'false'],
111
+ };
112
+ }
113
+
114
+ /**
115
+ * A single-choice field over a fixed set of strings.
116
+ * @param {string} field - field name inside the namespace section.
117
+ * @param {readonly string[]} choices - acceptable values.
118
+ * @returns {import('./client-types.js').FieldSpec} the field's conversion spec.
119
+ */
120
+ function enumField(field, choices) {
121
+ return {
122
+ field,
123
+ format: (value) => (typeof value === 'string' && choices.includes(value) ? value : ''),
124
+ parse: (text) => {
125
+ const trimmed = text.trim();
126
+ if (trimmed === '') return { kind: 'clear' };
127
+ return choices.includes(trimmed) ? { kind: 'set', value: trimmed } : undefined;
128
+ },
129
+ choices,
130
+ };
131
+ }
132
+
133
+ /**
134
+ * A write-only control staged outside the settings section (the API key is
135
+ * stored in the credentials domain, never in the settings document).
136
+ * @param {string} field - field name this control stages under.
137
+ * @param {(value: string) => Promise<boolean>} write - persist the literal.
138
+ * @returns {import('./client-types.js').SecretSpec} the secret's spec.
139
+ */
140
+ function secretSpec(field, write) {
141
+ return { field, write };
142
+ }
143
+
144
+ /**
145
+ * The staged form model one settings card runs on.
146
+ *
147
+ * A card stages what the user types and writes it only when they save. Each
148
+ * settings write is a durable, revision-fenced document mutation, so nothing
149
+ * commits as the user types. A field shows its effective value — the user
150
+ * layer over the composition layer over the schema default — and whether the
151
+ * user layer carries it; that presence, not a value comparison, is what marks
152
+ * a field overridden.
153
+ */
154
+ class QueritFormModel {
155
+ /** @param {import('./client-types.js').SettingsScope} scope - bound settings scope for the namespace. */
156
+ constructor(scope, specs, secrets = []) {
157
+ this.scope = scope;
158
+ this.specs = new Map(specs.map((spec) => [spec.field, spec]));
159
+ this.secretSpecs = new Map(secrets.map((spec) => [spec.field, spec]));
160
+ this.staged = new Map();
161
+ this.listeners = new Set();
162
+ this.saving = false;
163
+ this.failed = false;
164
+ scope.subscribe(() => this.publish());
165
+ }
166
+
167
+ /**
168
+ * Publish a projection of this form rebuilt whenever the scope or a draft
169
+ * changes.
170
+ * @param {() => object} project - build the card's state from the form reads.
171
+ * @returns {import('./client-types.js').SnapshotStore} the store the component reads.
172
+ */
173
+ bind(project) {
174
+ const store = makeStore(project());
175
+ this.listeners.add(() => {
176
+ store.set(project());
177
+ });
178
+ return store;
179
+ }
180
+
181
+ /** Read the card-level state: what the Host serves, and what a save would do. */
182
+ shell() {
183
+ const snapshot = this.scope.getSnapshot();
184
+ const plan = this.plan();
185
+ return {
186
+ available: snapshot.status === 'ready',
187
+ writable: snapshot.writable === true,
188
+ dirty: plan.length > 0,
189
+ invalid: plan.some((item) => item.run === undefined),
190
+ saving: this.saving,
191
+ failed: this.failed,
192
+ };
193
+ }
194
+
195
+ /** Read one control's state. */
196
+ field(field) {
197
+ const staged = this.staged.get(field);
198
+ if (this.secretSpecs.has(field)) {
199
+ return { text: staged?.text ?? '', overridden: false, invalid: false };
200
+ }
201
+ const spec = this.spec(field);
202
+ if (staged === undefined) {
203
+ return {
204
+ text: spec.format(this.sectionValue(field)),
205
+ overridden: this.stored(field),
206
+ invalid: false,
207
+ };
208
+ }
209
+ const write = staged.clear ? { kind: 'clear' } : spec.parse(staged.text);
210
+ return {
211
+ text: staged.text,
212
+ overridden: write?.kind === 'set',
213
+ invalid: write === undefined,
214
+ };
215
+ }
216
+
217
+ /** The actions a card's slot entry injects. */
218
+ actions() {
219
+ return {
220
+ edit: (field, text) => {
221
+ this.stage(field, { text, clear: false });
222
+ },
223
+ resetField: (field) => {
224
+ if (this.secretSpecs.has(field)) return;
225
+ this.stage(field, { text: this.spec(field).format(this.baseValue(field)), clear: true });
226
+ },
227
+ save: () => {
228
+ return this.save();
229
+ },
230
+ discard: () => {
231
+ if (this.staged.size === 0 && !this.failed) return;
232
+ this.staged.clear();
233
+ this.failed = false;
234
+ this.publish();
235
+ },
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Write every staged edit, then re-seed from what the Host accepted. The Host
241
+ * is the only authority on whether a value was accepted, so the outcome is
242
+ * read back from the scope rather than predicted here.
243
+ */
244
+ async save() {
245
+ const plan = this.plan();
246
+ const writes = plan.flatMap((item) => (item.run === undefined ? [] : [item.run]));
247
+ if (plan.length === 0 || this.saving || writes.length !== plan.length) return;
248
+ this.saving = true;
249
+ this.failed = false;
250
+ this.publish();
251
+ let landed = true;
252
+ for (const write of writes) landed = (await write()) && landed;
253
+ if (landed) this.staged.clear();
254
+ this.saving = false;
255
+ this.failed = !landed;
256
+ this.publish();
257
+ }
258
+
259
+ /** Every staged edit a save would write, in the order the fields were staged. */
260
+ plan() {
261
+ const plan = [];
262
+ for (const [field, staged] of this.staged) {
263
+ const secret = this.secretSpecs.get(field);
264
+ if (secret !== undefined) {
265
+ const value = staged.text.trim();
266
+ if (value !== '') {
267
+ plan.push({ field, run: () => secret.write(value).then((ok) => !!ok) });
268
+ }
269
+ continue;
270
+ }
271
+ const spec = this.spec(field);
272
+ if (staged.clear) {
273
+ if (this.stored(field)) plan.push({ field, run: () => this.clear(field) });
274
+ continue;
275
+ }
276
+ if (staged.text === spec.format(this.sectionValue(field))) continue;
277
+ const write = spec.parse(staged.text);
278
+ if (write === undefined) plan.push({ field, run: undefined });
279
+ else if (write.kind === 'clear') plan.push({ field, run: () => this.clear(field) });
280
+ else plan.push({ field, run: () => this.store(field, write.value) });
281
+ }
282
+ return plan;
283
+ }
284
+
285
+ stage(field, draft) {
286
+ this.staged.set(field, draft);
287
+ this.publish();
288
+ }
289
+
290
+ publish() {
291
+ for (const listener of this.listeners) listener();
292
+ }
293
+
294
+ spec(field) {
295
+ const spec = this.specs.get(field);
296
+ if (spec === undefined) throw new Error(`querit card: unknown field "${field}"`);
297
+ return spec;
298
+ }
299
+
300
+ sectionValue(field) {
301
+ return this.scope.getSnapshot().value?.[field];
302
+ }
303
+
304
+ stored(field) {
305
+ const user = this.scope.getSnapshot().user;
306
+ return typeof user === 'object' && user !== null && Object.prototype.hasOwnProperty.call(user, field);
307
+ }
308
+
309
+ baseValue(field) {
310
+ return this.scope.getSnapshot().base?.[field];
311
+ }
312
+
313
+ clear(field) {
314
+ return this.scope.unset(field);
315
+ }
316
+
317
+ store(field, value) {
318
+ return this.scope.set(field, value);
319
+ }
320
+ }
321
+
322
+ /** Minimal snapshot store: stable state object, getSnapshot, subscribe, set. */
323
+ function makeStore(initial) {
324
+ let state = initial;
325
+ const listeners = new Set();
326
+ return {
327
+ getSnapshot: () => state,
328
+ subscribe: (listener) => {
329
+ listeners.add(listener);
330
+ return () => listeners.delete(listener);
331
+ },
332
+ set: (next) => {
333
+ state = next;
334
+ for (const listener of listeners) listener();
335
+ },
336
+ };
337
+ }
338
+
339
+ var NS = 'dsh-querit';
340
+ var NAMESPACE = 'web-search-querit';
341
+ var DEFAULT_API_KEY_REF = 'QUERIT_API_KEY';
342
+ var FETCH_FORMATS = ['markdown', 'text', 'html'];
343
+
344
+ /* Card styles: scoped classes over the theme's alias tokens. */
345
+ (function injectCardCss() {
346
+ if (typeof document === 'undefined') return;
347
+ var tagId = NS + '/card.css';
348
+ if (document.querySelector('style[data-plugin-css="' + tagId + '"]') !== null) return;
349
+ var css = [
350
+ '.qr-card{list-style:none;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);border-radius:12px;transition:border-color .16s,background .16s}',
351
+ '.qr-card:hover{border-color:var(--dsw-alias-label-dimmed)}',
352
+ '.qr-card.qr-open{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-label-dimmed)}',
353
+ '.qr-header{appearance:none;display:flex;align-items:center;gap:12px;width:100%;padding:14px 16px;background:0 0;border:0;border-radius:12px;cursor:pointer;color:inherit;font:inherit;text-align:left}',
354
+ '.qr-header:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}',
355
+ '.qr-head{flex-direction:column;flex:1;min-width:0;gap:4px;display:flex}',
356
+ '.qr-name{color:var(--dsw-alias-label-primary);font-size:15px;font-weight:600;line-height:1.4}',
357
+ '.qr-desc{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.5}',
358
+ '.qr-pending{white-space:nowrap;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary);border-radius:999px;flex:none;padding:1px 8px;font-size:11px;font-weight:500;line-height:17px}',
359
+ '.qr-chev{color:var(--dsw-alias-label-tertiary);flex:none;transition:transform .16s}',
360
+ '.qr-card.qr-open .qr-chev{transform:rotate(180deg)}',
361
+ '.qr-body{border-top:1px solid var(--dsw-alias-border-l2);margin:0 16px;padding-bottom:8px}',
362
+ '.qr-readonly{color:var(--dsw-alias-label-tertiary);margin:12px 0 0;font-size:12px;line-height:1.5}',
363
+ '.qr-field{display:flex;flex-direction:column;gap:6px;padding:12px 0}',
364
+ '.qr-field+.qr-field{border-top:1px solid var(--dsw-alias-border-l2)}',
365
+ '.qr-fhead{display:flex;align-items:center;gap:8px}',
366
+ '.qr-label{flex:1;min-width:0;color:var(--dsw-alias-label-primary);font-size:13px;font-weight:500;line-height:1.5}',
367
+ '.qr-badges{align-items:center;gap:8px;display:inline-flex}',
368
+ '.qr-tagOver{white-space:nowrap;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary);border-radius:999px;padding:1px 8px;font-size:11px;font-weight:500;line-height:17px}',
369
+ '.qr-reset{font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;padding:0;font-size:12px;line-height:1.5}',
370
+ '.qr-reset:hover:not(:disabled){color:var(--dsw-alias-label-primary)}',
371
+ '.qr-reset:disabled{cursor:default}',
372
+ '.qr-input{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);height:34px;font:inherit;color:var(--dsw-alias-label-primary);border-radius:8px;padding:0 12px;font-size:13px;line-height:1.5;box-sizing:border-box}',
373
+ '.qr-input:focus-visible{border-color:var(--dsw-alias-brand-primary);outline:none}',
374
+ '.qr-input:disabled{color:var(--dsw-alias-label-tertiary);cursor:default}',
375
+ '.qr-input-invalid{border-color:var(--dsw-alias-label-error)}',
376
+ '.qr-check{width:16px;height:16px;accent-color:var(--dsw-alias-brand-primary);cursor:pointer;flex:none}',
377
+ '.qr-check:disabled{cursor:default}',
378
+ '.qr-invalid{color:var(--dsw-alias-label-error);margin:0;font-size:12px;line-height:1.5}',
379
+ '.qr-hint{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}',
380
+ '.qr-foot{border-top:1px solid var(--dsw-alias-border-l2);justify-content:flex-end;align-items:center;gap:8px;padding:12px 0 4px;display:flex}',
381
+ '.qr-failed{min-width:0;color:var(--dsw-alias-label-error);flex:1;margin:0;font-size:12px;line-height:1.5}',
382
+ '.qr-btn{appearance:none;font:inherit;cursor:pointer;border:1px solid transparent;border-radius:8px;padding:5px 14px;font-size:13px;line-height:1.5}',
383
+ '.qr-discard{border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary);background:transparent}',
384
+ '.qr-discard:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}',
385
+ '.qr-save{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3)}',
386
+ '.qr-btn:disabled{opacity:.4;cursor:default}',
387
+ '.qr-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}'
388
+ ].join('');
389
+ var tag = document.createElement('style');
390
+ tag.dataset.plugin = NS;
391
+ tag.dataset.pluginCss = tagId;
392
+ tag.textContent = css;
393
+ document.head.appendChild(tag);
394
+ })();
395
+
396
+ var en = {
397
+ title: 'Querit web search',
398
+ description: 'Querit-backed search and fetch provider.',
399
+ readOnly: 'This deployment stores settings read-only.',
400
+ expand: 'Show settings',
401
+ collapse: 'Hide settings',
402
+ pass: 'Password',
403
+ save: 'Save',
404
+ saving: 'Saving\u2026',
405
+ discard: 'Discard',
406
+ unsaved: 'Unsaved',
407
+ overridden: 'Overridden',
408
+ reset: 'Reset to default',
409
+ saveFailed: 'The deployment did not accept these values; they were left for you to correct.',
410
+ invalidNumber: 'Enter a number, or leave blank to use the default.',
411
+ keyLabel: 'API key',
412
+ keyHint: 'Stored outside the settings file. Leave blank to keep the current key.',
413
+ keySet: 'A key is configured for',
414
+ keyUnset: 'No key is configured; search fails until one is set via the credentials file or here.',
415
+ refLabel: 'Credential reference',
416
+ refHint: 'Environment variable / credentials-store name the provider resolves per call.',
417
+ countLabel: 'Result count',
418
+ countHint: 'Results per search when no explicit bound is given (1\u201320).',
419
+ timeRangeLabel: 'Time range',
420
+ timeRangeHint: 'Relative (d7, w2, m3, y1, \u2026) or YYYY-MM-DDtoYYYY-MM-DD.',
421
+ languagesLabel: 'Languages',
422
+ languagesHint: 'Comma-separated: english, japanese, korean, german, french, spanish, portuguese.',
423
+ countriesLabel: 'Countries',
424
+ countriesHint: 'Comma-separated country bias (argentina, australia, brazil, \u2026).',
425
+ includeLabel: 'Include domains',
426
+ includeHint: 'Whitelist hostnames; only these domains return results.',
427
+ excludeLabel: 'Exclude domains',
428
+ excludeHint: 'Blacklist hostnames; these domains never return results.',
429
+ contentLabel: 'Include content excerpts',
430
+ contentHint: 'Request sentence-level content excerpts alongside snippets.',
431
+ formatLabel: 'Fetch format',
432
+ formatHint: 'Format requested from /v1/contents for fetch calls.'
433
+ };
434
+ var zh = {
435
+ title: 'Querit 网页搜索',
436
+ description: '基于 Querit 的搜索与抓取提供方。',
437
+ readOnly: '本部署的设置为只读。',
438
+ expand: '展开设置',
439
+ collapse: '收起设置',
440
+ pass: '密码',
441
+ save: '保存',
442
+ saving: '保存中\u2026',
443
+ discard: '放弃修改',
444
+ unsaved: '未保存',
445
+ overridden: '已覆盖',
446
+ reset: '恢复默认',
447
+ saveFailed: '本部署没有接受这些值,已保留供你修改。',
448
+ invalidNumber: '请填数字;留空表示使用默认值。',
449
+ keyLabel: 'API Key',
450
+ keyHint: '不写入设置文件。留空表示保持当前密钥。',
451
+ keySet: '已为',
452
+ keyUnset: '未配置密钥;请在凭据文件或此处配置后搜索才可用。',
453
+ refLabel: '凭据引用名',
454
+ refHint: '每次调用解析的环境变量 / 凭据存储键名。',
455
+ countLabel: '结果数量',
456
+ countHint: '未指定上限时每次搜索返回的结果数(1–20)。',
457
+ timeRangeLabel: '时间范围',
458
+ timeRangeHint: '相对(d7、w2、m3、y1…)或 YYYY-MM-DDtoYYYY-MM-DD。',
459
+ languagesLabel: '语言',
460
+ languagesHint: '逗号分隔:english、japanese、korean、german、french、spanish、portuguese。',
461
+ countriesLabel: '国家',
462
+ countriesHint: '逗号分隔的国家偏好(argentina、australia、brazil…)。',
463
+ includeLabel: '仅限域名',
464
+ includeHint: '白名单主机名;只返回这些域的结果。',
465
+ excludeLabel: '排除域名',
466
+ excludeHint: '黑名单主机名;这些域永不返回结果。',
467
+ contentLabel: '包含内容摘要',
468
+ contentHint: '在摘要旁请求句子级内容摘录。',
469
+ formatLabel: '抓取格式',
470
+ formatHint: '/v1/contents 抓取请求的格式。'
471
+ };
472
+
473
+ /** The credential reference the section names, or the provider default. */
474
+ function refOf(snapshot) {
475
+ var declared = snapshot.value && snapshot.value.apiKeyEnv;
476
+ return declared !== undefined && declared.length > 0 ? declared : DEFAULT_API_KEY_REF;
477
+ }
478
+
479
+ /** Bridges the web-search-querit scope and the credentials domain onto the card. */
480
+ function QueritCardController(scope, api) {
481
+ this.scope = scope;
482
+ this.api = api;
483
+ this.credential = { ref: '', configured: false, writable: true };
484
+ this.form = new QueritFormModel(
485
+ scope,
486
+ [
487
+ textField('apiKeyEnv'),
488
+ numberField('count'),
489
+ textField('timeRange'),
490
+ listField('languages'),
491
+ listField('countries'),
492
+ listField('includeDomains'),
493
+ listField('excludeDomains'),
494
+ booleanField('includeContent'),
495
+ enumField('fetchFormat', FETCH_FORMATS)
496
+ ],
497
+ [secretSpec('apiKey', (value) => this.writeKey(value))]
498
+ );
499
+ this.store = this.form.bind(() => this.projection());
500
+ var self = this;
501
+ scope.subscribe(() => {
502
+ self.readCredential();
503
+ });
504
+ this.readCredential();
505
+ }
506
+
507
+ QueritCardController.prototype.projection = function () {
508
+ return {
509
+ ...this.form.shell(),
510
+ apiKeyEnv: this.form.field('apiKeyEnv'),
511
+ count: this.form.field('count'),
512
+ timeRange: this.form.field('timeRange'),
513
+ languages: this.form.field('languages'),
514
+ countries: this.form.field('countries'),
515
+ includeDomains: this.form.field('includeDomains'),
516
+ excludeDomains: this.form.field('excludeDomains'),
517
+ includeContent: this.form.field('includeContent'),
518
+ fetchFormat: this.form.field('fetchFormat'),
519
+ apiKey: this.form.field('apiKey'),
520
+ apiKeyConfigured: this.credential.configured,
521
+ apiKeyWritable: this.credential.writable,
522
+ apiKeyRef: this.credential.ref
523
+ };
524
+ };
525
+
526
+ QueritCardController.prototype.readCredential = function () {
527
+ var self = this;
528
+ var ref = refOf(this.scope.getSnapshot());
529
+ if (ref !== this.credential.ref) {
530
+ this.credential = { ref: ref, configured: false, writable: true };
531
+ this.store.set(this.projection());
532
+ }
533
+ this.api.credentials
534
+ .describe({ refs: [ref] })
535
+ .then(function (response) {
536
+ if (!response || !response.result || !response.result.ok) return;
537
+ if (ref !== refOf(self.scope.getSnapshot())) return;
538
+ var view = response.result.value.credentials[ref];
539
+ var next = {
540
+ ref: ref,
541
+ configured: view && view.configured === true,
542
+ writable: !view || view.writable !== false
543
+ };
544
+ if (next.configured === self.credential.configured && next.writable === self.credential.writable) return;
545
+ self.credential = next;
546
+ self.store.set(self.projection());
547
+ })
548
+ .catch(function () {});
549
+ };
550
+
551
+ QueritCardController.prototype.refreshCredential = function (ref) {
552
+ if (ref !== this.credential.ref) return;
553
+ this.readCredential();
554
+ };
555
+
556
+ QueritCardController.prototype.writeKey = function (value) {
557
+ var self = this;
558
+ return this.api.credentials
559
+ .set({ ref: refOf(this.scope.getSnapshot()), value: value })
560
+ .then(function () {
561
+ return self.readCredential();
562
+ })
563
+ .catch(function () {
564
+ return self.readCredential();
565
+ })
566
+ .then(function () {
567
+ return self.credential.configured;
568
+ });
569
+ };
570
+
571
+ QueritCardController.prototype.inject = function () {
572
+ return {
573
+ hooks: { queritCard: this.store },
574
+ ...this.form.actions()
575
+ };
576
+ };
577
+
578
+ /** Chevron-down icon mirroring the official PluginCard toggle glyph. */
579
+ function ChevronDown(props) {
580
+ var className = props.className || '';
581
+ return React.createElement(
582
+ 'svg',
583
+ {
584
+ className: className,
585
+ width: 14,
586
+ height: 14,
587
+ viewBox: '0 0 14 14',
588
+ fill: 'none',
589
+ xmlns: 'http://www.w3.org/2000/svg',
590
+ 'aria-hidden': true,
591
+ focusable: false
592
+ },
593
+ React.createElement('path', {
594
+ d: 'M3.5 5.25L7 8.75L10.5 5.25',
595
+ stroke: 'currentColor',
596
+ strokeWidth: 1.4,
597
+ strokeLinecap: 'round',
598
+ strokeLinejoin: 'round'
599
+ })
600
+ );
601
+ }
602
+
603
+ /** One labeled control row. `inline` puts the control on the label line (toggle rows). */
604
+ function FieldRow(props) {
605
+ var inline = props.inline === true;
606
+ var id = props.id;
607
+ var inputProps = Object.assign({}, props.inputProps || {});
608
+ var as = inputProps.as === 'select' ? 'select' : 'input';
609
+ delete inputProps.as;
610
+ var controlClass = 'qr-input' + (props.state && props.state.invalid ? ' qr-input-invalid' : '');
611
+ inputProps.id = id;
612
+ inputProps.className = controlClass;
613
+ var control;
614
+ if (as === 'select') {
615
+ control = React.createElement('select', inputProps, props.options || []);
616
+ } else {
617
+ control = React.createElement('input', inputProps);
618
+ }
619
+ var headChildren = [
620
+ inline
621
+ ? React.createElement('label', { key: 'label', className: 'qr-label', htmlFor: id }, props.label)
622
+ : React.createElement('span', { key: 'label', className: 'qr-label' }, props.label),
623
+ props.state && props.state.overridden
624
+ ? React.createElement(
625
+ 'span',
626
+ { key: 'badges', className: 'qr-badges' },
627
+ React.createElement('span', { className: 'qr-tagOver' }, props.overriddenLabel),
628
+ props.onReset
629
+ ? React.createElement(
630
+ 'button',
631
+ { type: 'button', className: 'qr-reset', disabled: props.disabled || !props.state.overridden, onClick: props.onReset },
632
+ props.resetLabel
633
+ )
634
+ : null
635
+ )
636
+ : null,
637
+ inline ? props.children : null
638
+ ];
639
+ var bodyChildren = inline ? null : control;
640
+ var help = props.state && props.state.invalid
641
+ ? React.createElement('p', { className: 'qr-invalid' }, props.invalidLabel)
642
+ : props.hint
643
+ ? React.createElement('p', { className: 'qr-hint' }, props.hint)
644
+ : null;
645
+ return React.createElement(
646
+ 'div',
647
+ { className: 'qr-field' },
648
+ React.createElement('div', { className: 'qr-fhead' }, headChildren),
649
+ bodyChildren,
650
+ help
651
+ );
652
+ }
653
+
654
+ /** Render one plugin card: header naming the provider, disclosing its controls in place. */
655
+ function QueritCard(props) {
656
+ var t = props.t || function (key) {
657
+ return zh[key] || en[key] || key;
658
+ };
659
+ var state = props.useQueritCard(function (snapshot) {
660
+ return snapshot;
661
+ });
662
+ var openState = React.useState(props.defaultOpen === true);
663
+ var open = openState[0];
664
+ var setOpen = openState[1];
665
+ if (!state.available) return null;
666
+ var disabled = !state.writable;
667
+ var blocked = !state.dirty || state.invalid || state.saving;
668
+ var text = function (control) {
669
+ return control.text;
670
+ };
671
+ var title = t('title');
672
+ return React.createElement(
673
+ 'li',
674
+ { className: 'qr-card' + (open ? ' qr-open' : '') },
675
+ React.createElement(
676
+ 'button',
677
+ {
678
+ type: 'button',
679
+ className: 'qr-header',
680
+ 'aria-expanded': open ? 'true' : 'false',
681
+ 'aria-label': t(open ? 'collapse' : 'expand') + ': ' + title,
682
+ onClick: function () { setOpen(!open); }
683
+ },
684
+ React.createElement(
685
+ 'span',
686
+ { className: 'qr-head' },
687
+ React.createElement('span', { className: 'qr-name' }, title),
688
+ React.createElement('span', { className: 'qr-desc' }, t('description'))
689
+ ),
690
+ state.dirty ? React.createElement('span', { className: 'qr-pending' }, t('unsaved')) : null,
691
+ React.createElement(ChevronDown, { className: 'qr-chev' })
692
+ ),
693
+ open
694
+ ? React.createElement(
695
+ 'div',
696
+ { className: 'qr-body' },
697
+ disabled ? React.createElement('p', { className: 'qr-readonly', role: 'status' }, t('readOnly')) : null,
698
+ React.createElement(
699
+ FieldRow,
700
+ {
701
+ id: 'plugin-config-querit-key',
702
+ label: t('keyLabel'),
703
+ hint: state.apiKeyConfigured
704
+ ? t('keySet') + ' ' + state.apiKeyRef + '.'
705
+ : t('keyUnset'),
706
+ disabled: disabled || !state.apiKeyWritable,
707
+ inputProps: {
708
+ className: 'qr-input',
709
+ type: 'password',
710
+ autoComplete: 'new-password',
711
+ disabled: disabled || !state.apiKeyWritable,
712
+ placeholder: state.apiKeyConfigured ? '\u2022\u2022\u2022\u2022\u2022\u2022' : '',
713
+ value: text(state.apiKey),
714
+ onChange: function (event) { props.edit('apiKey', event.target.value); }
715
+ }
716
+ }
717
+ ),
718
+ field(props, t('refLabel'), t('refHint'), state.apiKeyEnv, 'apiKeyEnv', disabled, 'plugin-config-querit-env'),
719
+ field(props, t('countLabel'), t('countHint'), state.count, 'count', disabled, 'plugin-config-querit-count', true),
720
+ field(props, t('timeRangeLabel'), t('timeRangeHint'), state.timeRange, 'timeRange', disabled, 'plugin-config-querit-time'),
721
+ field(props, t('languagesLabel'), t('languagesHint'), state.languages, 'languages', disabled, 'plugin-config-querit-languages'),
722
+ field(props, t('countriesLabel'), t('countriesHint'), state.countries, 'countries', disabled, 'plugin-config-querit-countries'),
723
+ field(props, t('includeLabel'), t('includeHint'), state.includeDomains, 'includeDomains', disabled, 'plugin-config-querit-include'),
724
+ field(props, t('excludeLabel'), t('excludeHint'), state.excludeDomains, 'excludeDomains', disabled, 'plugin-config-querit-exclude'),
725
+ React.createElement(
726
+ FieldRow,
727
+ {
728
+ id: 'plugin-config-querit-content',
729
+ label: t('contentLabel'),
730
+ hint: t('contentHint'),
731
+ state: state.includeContent,
732
+ disabled: disabled,
733
+ inline: true,
734
+ overriddenLabel: t('overridden'),
735
+ resetLabel: t('reset'),
736
+ onReset: function () { props.resetField('includeContent'); }
737
+ },
738
+ React.createElement('input', {
739
+ className: 'qr-check',
740
+ type: 'checkbox',
741
+ disabled: disabled,
742
+ checked: state.includeContent.text === 'true',
743
+ onChange: function (event) { props.edit('includeContent', event.target.checked ? 'true' : 'false'); }
744
+ })
745
+ ),
746
+ React.createElement(
747
+ FieldRow,
748
+ {
749
+ id: 'plugin-config-querit-format',
750
+ label: t('formatLabel'),
751
+ hint: t('formatHint'),
752
+ state: state.fetchFormat,
753
+ disabled: disabled,
754
+ overriddenLabel: t('overridden'),
755
+ resetLabel: t('reset'),
756
+ onReset: function () { props.resetField('fetchFormat'); },
757
+ inputProps: {
758
+ disabled: disabled,
759
+ value: text(state.fetchFormat),
760
+ onChange: function (event) { props.edit('fetchFormat', event.target.value); },
761
+ as: 'select'
762
+ },
763
+ options: FETCH_FORMATS.map(function (format) {
764
+ return React.createElement('option', { key: format, value: format }, format);
765
+ })
766
+ }
767
+ ),
768
+ React.createElement(
769
+ 'div',
770
+ { className: 'qr-foot' },
771
+ state.failed ? React.createElement('p', { className: 'qr-failed', role: 'status' }, t('saveFailed')) : null,
772
+ React.createElement(
773
+ 'button',
774
+ { type: 'button', className: 'qr-btn qr-discard', disabled: (!state.dirty && !state.failed) || state.saving, onClick: props.discard },
775
+ t('discard')
776
+ ),
777
+ React.createElement(
778
+ 'button',
779
+ { type: 'button', className: 'qr-btn qr-save', disabled: blocked, onClick: props.save },
780
+ t(state.saving ? 'saving' : 'save')
781
+ )
782
+ )
783
+ )
784
+ : null
785
+ );
786
+ }
787
+
788
+ /** Extract one section field's row into a shared control render. */
789
+ function field(props, label, hint, state, name, disabled, id, numeric) {
790
+ var inputProps = {
791
+ className: 'qr-input' + (state.invalid ? ' qr-input-invalid' : ''),
792
+ type: numeric === true ? 'number' : 'text',
793
+ disabled: disabled,
794
+ value: state.text,
795
+ onChange: function (event) { props.edit(name, event.target.value); }
796
+ };
797
+ if (numeric === true) inputProps.inputMode = 'numeric';
798
+ if (state.invalid) inputProps['aria-invalid'] = true;
799
+ return React.createElement(
800
+ FieldRow,
801
+ {
802
+ id: id,
803
+ label: label,
804
+ hint: hint,
805
+ state: state,
806
+ disabled: disabled,
807
+ invalidLabel: props.t('invalidNumber'),
808
+ overriddenLabel: props.t('overridden'),
809
+ resetLabel: props.t('reset'),
810
+ onReset: function () { props.resetField(name); },
811
+ inputProps: inputProps
812
+ }
813
+ );
814
+ }
815
+
816
+ /** Required services (cordis fiber inject). */
817
+ var inject = ['slots', 'connection', 'settingsScope', 'remote', 'locale'];
818
+
819
+ /**
820
+ * Mount the Querit settings card into the plugins configuration tab.
821
+ * @param ctx - the browser plugin context.
822
+ */
823
+ function apply(ctx) {
824
+ var slots = ctx.get('slots');
825
+ var scopeService = ctx.get('settingsScope');
826
+ var locale = ctx.get('locale');
827
+ var api = ctx.get('connection');
828
+ if (slots === undefined || scopeService === undefined || locale === undefined || api === undefined) return;
829
+ api = api.api;
830
+ // Register the card dictionaries, then bind our own translator. The slot
831
+ // framework may also deliver a `t` seat from the entry's `locale` option,
832
+ // but binding here guarantees text resolves even if that seat is not yet
833
+ // backed for this entry.
834
+ var dicts = { zh: zh, en: en };
835
+ ctx.effect(function () {
836
+ return locale.register(NS, dicts);
837
+ }, 'dsh-querit: card dictionaries');
838
+ var t = locale.bind(NS);
839
+ var scope = scopeService.bind({ namespace: NAMESPACE });
840
+ var controller = new QueritCardController(scope, api);
841
+ var remote = ctx.get('remote');
842
+ if (remote !== undefined) {
843
+ ctx.effect(function () {
844
+ return remote.$on('credentials/updated', function (ref) {
845
+ controller.refreshCredential(ref);
846
+ });
847
+ }, 'dsh-querit: credential invalidations');
848
+ }
849
+ slots.inject('settings.plugin.item', function () {
850
+ return slots.register(
851
+ {
852
+ name: 'settings.plugin.item',
853
+ key: NAMESPACE,
854
+ locale: NS,
855
+ inject: function () {
856
+ var face = controller.inject();
857
+ face.t = t;
858
+ return face;
859
+ }
860
+ },
861
+ QueritCard
862
+ );
863
+ });
864
+ }
865
+
866
+ exports.apply = apply;
867
+ exports.inject = inject;
868
+ exports.QueritCardController = QueritCardController;
869
+ exports.QueritCard = QueritCard;
870
+ return module.exports;
817
871
  });