@celljs/ta-extensions 4.6.1 → 4.7.0

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.
@@ -3,6 +3,7 @@ import type { WebExtensionAPI } from '@celljs/ta-web/lib/browser/extension/web-e
3
3
  import { ExtensionsUtil } from './extensions-util';
4
4
  import type { ExportedPackage, ImportedPackage } from './host';
5
5
  import { ExtensionWords, type Words } from './i18n';
6
+ import type { MarketStore } from './market-store';
6
7
 
7
8
  export interface PackagesState {
8
9
  /** Undefined until the first list came. */
@@ -53,6 +54,7 @@ export class ExtensionActions {
53
54
  constructor(
54
55
  protected readonly pi: WebExtensionAPI,
55
56
  protected readonly store: PackagesStore,
57
+ protected readonly market: MarketStore,
56
58
  ) {}
57
59
 
58
60
  get words(): Words {
@@ -157,6 +159,24 @@ export class ExtensionActions {
157
159
  });
158
160
  }
159
161
 
162
+ /** A package of the market, for the user (`ta install npm:<name>`): unpinned, so `ta update` updates it. */
163
+ async installFromMarket(name: string): Promise<boolean> {
164
+ if (this.market.state.installing.has(name)) {
165
+ return false;
166
+ }
167
+ this.market.setInstalling(name, true);
168
+ try {
169
+ return await this.guard(async () => {
170
+ await this.pi.packages.installPackage(`npm:${name}`, 'user');
171
+ await this.changed();
172
+ this.pi.ui.notify(ExtensionWords.fill(this.words.installedOk, { name }));
173
+ return true;
174
+ });
175
+ } finally {
176
+ this.market.setInstalling(name, false);
177
+ }
178
+ }
179
+
160
180
  /** The page and the conversation shown load what changed, and the list follows. */
161
181
  protected async changed(): Promise<void> {
162
182
  await this.pi.reloadExtensions();
@@ -0,0 +1,24 @@
1
+ import type { WebExtensionAPI, WebIcon } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
+ import type { ExtensionActions, PackagesStore } from './actions';
3
+ import type { MarketStore } from './market-store';
4
+ import type { Signal } from './signal';
5
+
6
+ /** The two halves of the page: the extensions of the user, and the market where more are found. */
7
+ export type ExtensionsTab = 'mine' | 'market';
8
+
9
+ /** What the page and its parts share; the menu of the view reaches the same signals. */
10
+ export interface ExtensionsContext {
11
+ pi: WebExtensionAPI;
12
+ store: PackagesStore;
13
+ market: MarketStore;
14
+ actions: ExtensionActions;
15
+ tab: Signal<ExtensionsTab>;
16
+ /** The package of the market shown on its own page, by name. */
17
+ selected: Signal<string | undefined>;
18
+ /** The dialog of Import, which the menu of the page opens too. */
19
+ importing: Signal<boolean>;
20
+ }
21
+
22
+ export function icon(pi: WebExtensionAPI, name: string, fallback = 'Square'): WebIcon {
23
+ return pi.ui.icons[name] ?? pi.ui.icons[fallback] ?? (() => null);
24
+ }
package/web-src/host.ts CHANGED
@@ -3,6 +3,8 @@ import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } f
3
3
  import { basename, dirname, join } from 'node:path';
4
4
  import type { TaExtensionHost, TaPackageService } from '@celljs/ta-protocol';
5
5
  import { ExtensionArchive } from './archive';
6
+ import { NpmMarket } from './market';
7
+ import type { MarketDetail, MarketPage } from './market-util';
6
8
 
7
9
  /** A package in one file, as the page downloads it: the bytes in base64, which JSON carries. */
8
10
  export interface ExportedPackage {
@@ -32,14 +34,26 @@ export namespace PackageFiles {
32
34
 
33
35
  /**
34
36
  * The server side of ta-extensions: a package of the user in one file to hand on, and such a file put
35
- * into `extensions/` of the agent directory, where pi finds it with no setting.
37
+ * into `extensions/` of the agent directory, where pi finds it with no setting; and the market, the
38
+ * pi packages of npm, found here because here they install.
36
39
  */
37
40
  export class ExtensionsService implements TaPackageService {
38
- constructor(protected readonly host: TaExtensionHost) {}
41
+ constructor(
42
+ protected readonly host: TaExtensionHost,
43
+ protected readonly market = new NpmMarket(),
44
+ ) {}
39
45
 
40
46
  /** Nothing to stop: each call stands alone. */
41
47
  dispose(): void {}
42
48
 
49
+ searchMarket(query: string, from?: number): Promise<MarketPage> {
50
+ return this.market.search(query, from);
51
+ }
52
+
53
+ marketPackage(name: string): Promise<MarketDetail> {
54
+ return this.market.detail(name);
55
+ }
56
+
43
57
  async exportPackage(id: string, cwd?: string): Promise<ExportedPackage> {
44
58
  const pkg = (await this.host.listPackages(cwd)).find(candidate => candidate.id === id);
45
59
  if (!pkg) {
package/web-src/i18n.ts CHANGED
@@ -1,6 +1,13 @@
1
1
  import type { TaPackageResource } from '@celljs/ta-protocol';
2
+ import type { MarketKind } from './market-util';
2
3
  import type { KindName } from './pictures';
3
4
 
5
+ /** A search the market suggests before the user types one. */
6
+ export interface Topic {
7
+ label: string;
8
+ query: string;
9
+ }
10
+
4
11
  /** A kind of extension, and the one Ta makes of it when picked. */
5
12
  export interface Example {
6
13
  kind: KindName;
@@ -19,7 +26,45 @@ const EN = {
19
26
  changeTitle: 'Change {name}',
20
27
  changePlaceholder: 'What should it do differently?',
21
28
  mine: 'Yours',
22
- mineEmpty: 'None yet: say what you want above.',
29
+ mineEmpty: 'None yet: say what you want above, or find one in the marketplace.',
30
+ tabMine: 'Mine',
31
+ tabMarket: 'Marketplace',
32
+ browseMarket: 'Browse the marketplace',
33
+ marketSearch: 'Search extensions, for example web search, mcp',
34
+ marketClear: 'Clear',
35
+ marketPopular: 'Most used',
36
+ marketResults: 'Results',
37
+ marketCount: '{count} in all',
38
+ marketNote: 'Pi packages from npm. An extension runs code on this computer: read what it does before installing it.',
39
+ marketEmpty: 'Nothing matches “{query}”. Try other words.',
40
+ marketError: 'The marketplace cannot be reached',
41
+ retry: 'Try again',
42
+ installing: 'Installing…',
43
+ installedTag: 'Installed',
44
+ builtinTag: 'Built in',
45
+ perMonth: '{count}/mo',
46
+ by: 'by {name}',
47
+ back: 'Back',
48
+ source: 'Source',
49
+ homepage: 'Homepage',
50
+ noReadme: 'It says nothing more about itself.',
51
+ readmeTitle: 'Details',
52
+ loadingMore: 'Loading more…',
53
+ allShown: 'That is all of them.',
54
+ topics: [
55
+ { label: 'Web search', query: 'web search' },
56
+ { label: 'MCP', query: 'mcp' },
57
+ { label: 'Subagents', query: 'subagent' },
58
+ { label: 'Memory', query: 'memory' },
59
+ { label: 'Browser', query: 'browser' },
60
+ { label: 'Themes', query: 'theme' },
61
+ ] as Topic[],
62
+ marketKinds: {
63
+ extensions: 'Extension',
64
+ skills: 'Skill',
65
+ prompts: 'Prompts',
66
+ themes: 'Theme',
67
+ } as Record<MarketKind, string>,
23
68
  installed: 'Installed',
24
69
  import: 'Import',
25
70
  export: 'Export',
@@ -96,7 +141,45 @@ const ZH: Words = {
96
141
  changeTitle: '修改 {name}',
97
142
  changePlaceholder: '想让它有什么不同?',
98
143
  mine: '我的扩展',
99
- mineEmpty: '还没有,在上面说一句就行。',
144
+ mineEmpty: '还没有。在上面说一句就能做一个,也可以去市场找找。',
145
+ tabMine: '我的',
146
+ tabMarket: '市场',
147
+ browseMarket: '去市场看看',
148
+ marketSearch: '用英文搜索扩展,例如 web search、mcp',
149
+ marketClear: '清除',
150
+ marketPopular: '最常用',
151
+ marketResults: '搜索结果',
152
+ marketCount: '共 {count} 个',
153
+ marketNote: '来自 npm 上的 pi 包。扩展会在这台电脑上运行代码,安装前可以先看看介绍。',
154
+ marketEmpty: '没有找到“{query}”相关的扩展,换个词试试。',
155
+ marketError: '暂时连不上扩展市场',
156
+ retry: '重试',
157
+ installing: '安装中…',
158
+ installedTag: '已安装',
159
+ builtinTag: '内置',
160
+ perMonth: '{count}/月',
161
+ by: '{name}',
162
+ back: '返回',
163
+ source: '源代码',
164
+ homepage: '主页',
165
+ noReadme: '作者没有写更多介绍。',
166
+ readmeTitle: '介绍',
167
+ loadingMore: '正在加载更多…',
168
+ allShown: '已经到底了',
169
+ topics: [
170
+ { label: '网页搜索', query: 'web search' },
171
+ { label: 'MCP', query: 'mcp' },
172
+ { label: '子 Agent', query: 'subagent' },
173
+ { label: '记忆', query: 'memory' },
174
+ { label: '浏览器', query: 'browser' },
175
+ { label: '主题', query: 'theme' },
176
+ ],
177
+ marketKinds: {
178
+ extensions: '扩展',
179
+ skills: '技能',
180
+ prompts: '提示模板',
181
+ themes: '主题',
182
+ },
100
183
  installed: '安装的扩展',
101
184
  import: '导入',
102
185
  export: '导出',
package/web-src/index.tsx CHANGED
@@ -1,43 +1,47 @@
1
1
  import type { WebExtensionAPI } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
2
  import { ExtensionActions, PackagesStore } from './actions';
3
+ import type { ExtensionsContext, ExtensionsTab } from './context';
3
4
  import { ExtensionWords } from './i18n';
4
- import { type ExtensionsContext, ExtensionsPage } from './page';
5
+ import { MarketStore } from './market-store';
6
+ import { ExtensionsPage } from './page';
5
7
  // biome-ignore lint/correctness/noUnusedImports: the JSX below compiles to React.createElement (jsxFactory)
6
8
  import { bind, React } from './react';
9
+ import { Signal } from './signal';
7
10
  import { injectStyle } from './style';
8
11
 
9
12
  /**
10
13
  * The page of extensions, in the navigation: where the user learns that Ta makes extensions from what
11
- * they say, and hands them on or takes them in. Files go through the host of the package (host.ts).
14
+ * they say, hands them on or takes them in, and finds more in the market. Files and npm go through the
15
+ * host of the package (host.ts).
12
16
  */
13
17
  export default function activate(pi: WebExtensionAPI): () => void {
14
18
  bind(pi.React);
15
19
  const removeStyle = injectStyle();
16
20
  const store = new PackagesStore(pi);
17
- const actions = new ExtensionActions(pi, store);
18
- const listeners = new Set<() => void>();
19
- const importing: ExtensionsContext['importing'] = {
20
- shown: false,
21
- open: () => set(true),
22
- close: () => set(false),
23
- subscribe: listener => {
24
- listeners.add(listener);
25
- return () => listeners.delete(listener);
26
- },
21
+ const market = new MarketStore(pi);
22
+ const context: ExtensionsContext = {
23
+ pi,
24
+ store,
25
+ market,
26
+ actions: new ExtensionActions(pi, store, market),
27
+ tab: new Signal<ExtensionsTab>('mine'),
28
+ selected: new Signal<string | undefined>(undefined),
29
+ importing: new Signal(false),
27
30
  };
28
- function set(shown: boolean) {
29
- importing.shown = shown;
30
- for (const listener of listeners) {
31
- listener();
32
- }
33
- }
34
- const context: ExtensionsContext = { pi, store, actions, importing };
35
- const Puzzle = pi.ui.icons.Puzzle ?? pi.ui.icons.Square;
31
+ const icons = pi.ui.icons;
36
32
  pi.registerView('extensions', {
37
33
  title: () => ExtensionWords.of(pi.ui.language).title,
38
- icon: Puzzle,
34
+ icon: icons.Puzzle ?? icons.Square,
39
35
  render: () => <ExtensionsPage context={context} />,
40
- menu: () => [[{ key: 'import', label: ExtensionWords.of(pi.ui.language).import, icon: pi.ui.icons.Upload, run: () => importing.open() }]],
36
+ menu: () => {
37
+ const words = ExtensionWords.of(pi.ui.language);
38
+ return [
39
+ [
40
+ { key: 'market', label: words.tabMarket, icon: icons.Store ?? icons.PackageOpen, run: () => context.tab.set('market') },
41
+ { key: 'import', label: words.import, icon: icons.Upload, run: () => context.importing.set(true) },
42
+ ],
43
+ ];
44
+ },
41
45
  order: 90,
42
46
  });
43
47
  // A reply of Ta may have made, changed or removed one.
@@ -0,0 +1,138 @@
1
+ import { type ExtensionsContext, icon } from './context';
2
+ import { ExtensionWords } from './i18n';
3
+ import { InstallButton, PackageFace, PackageName, useMarketStatus } from './market-parts';
4
+ import { MarketStore } from './market-store';
5
+ import { type MarketDetail, MarketUtil } from './market-util';
6
+ import { React } from './react';
7
+
8
+ export interface MarketDetailProps {
9
+ context: ExtensionsContext;
10
+ name: string;
11
+ onBack(): void;
12
+ }
13
+
14
+ /**
15
+ * The page of a package of the market, as a store shows an app: its face, name and numbers, the button
16
+ * to install it (or remove it), where it comes from, its preview of pi's gallery, and its README.
17
+ */
18
+ export function MarketDetailView({ context, name, onBack }: MarketDetailProps): React.ReactElement {
19
+ const { pi, market, actions } = context;
20
+ const words = actions.words;
21
+ const [detail, setDetail] = React.useState<MarketDetail>();
22
+ const [error, setError] = React.useState<string>();
23
+ const [attempt, setAttempt] = React.useState(0);
24
+ React.useEffect(() => {
25
+ let live = true;
26
+ setError(undefined);
27
+ market.detail(name).then(
28
+ value => live && setDetail(value),
29
+ reason => live && setError(MarketStore.message(reason)),
30
+ );
31
+ return () => {
32
+ live = false;
33
+ };
34
+ }, [market, name, attempt]);
35
+ React.useEffect(() => {
36
+ const onKey = (event: KeyboardEvent) => {
37
+ // Not while a dialog is open or the user types.
38
+ const target = event.target as HTMLElement | null;
39
+ if (event.key === 'Escape' && !document.querySelector('[aria-modal="true"]') && !target?.closest('input, textarea, [contenteditable="true"]')) {
40
+ onBack();
41
+ }
42
+ };
43
+ document.addEventListener('keydown', onKey);
44
+ return () => document.removeEventListener('keydown', onKey);
45
+ }, [onBack]);
46
+ // What the list knew shows at once; the README follows. The list knows when it was published.
47
+ const listed = market.state.packages?.find(pkg => pkg.name === name);
48
+ const summary = detail ? { ...detail, date: detail.date ?? listed?.date, downloads: detail.downloads ?? listed?.downloads } : listed;
49
+ const status = useMarketStatus(context, name);
50
+ const ArrowLeft = icon(pi, 'ArrowLeft');
51
+ const External = icon(pi, 'ExternalLink');
52
+ const Trash = icon(pi, 'Trash2');
53
+ const Markdown = pi.ui.Markdown;
54
+ const ago = MarketUtil.ago(summary?.date, pi.ui.language);
55
+ const facts = [
56
+ summary?.publisher,
57
+ summary?.version && `v${summary.version}`,
58
+ summary?.downloads ? ExtensionWords.fill(words.perMonth, { count: MarketUtil.compact(summary.downloads) }) : undefined,
59
+ detail?.license,
60
+ ago,
61
+ ].filter((fact): fact is string => !!fact);
62
+ const links = [
63
+ { key: 'npm', label: 'npm', href: summary?.links.npm ?? `https://www.npmjs.com/package/${name}` },
64
+ { key: 'source', label: words.source, href: summary?.links.repository },
65
+ { key: 'home', label: words.homepage, href: summary?.links.homepage !== summary?.links.repository ? summary?.links.homepage : undefined },
66
+ ].filter((link): link is { key: string; label: string; href: string } => !!link.href && /^https?:\/\//.test(link.href));
67
+ const tags = (detail?.resources.length ? detail.resources : (summary?.kinds ?? [])).map(type =>
68
+ type === 'web' ? words.kinds.web : words.marketKinds[type],
69
+ );
70
+ return (
71
+ <article className="tax-detail" aria-label={name}>
72
+ <button type="button" className="tax-back" onClick={onBack}>
73
+ <ArrowLeft size={15} /> {words.back}
74
+ </button>
75
+ <header className="tax-detail-head">
76
+ <PackageFace name={name} size={72} />
77
+ <div className="tax-detail-title">
78
+ <h1>
79
+ <PackageName name={name} />
80
+ </h1>
81
+ {summary?.description && <p className="tax-detail-description">{summary.description}</p>}
82
+ {(facts.length > 0 || tags.length > 0) && (
83
+ <div className="tax-detail-facts">
84
+ {tags.map(tag => (
85
+ <span key={tag} className="tax-tag">
86
+ {tag}
87
+ </span>
88
+ ))}
89
+ {facts.map(fact => (
90
+ <span key={fact} className="tax-fact">
91
+ {fact}
92
+ </span>
93
+ ))}
94
+ </div>
95
+ )}
96
+ <div className="tax-detail-actions">
97
+ <InstallButton context={context} name={name} large />
98
+ {status.kind === 'installed' && (
99
+ <button type="button" className="tax-button tax-button-quiet" onClick={() => void actions.remove(status.pkg)}>
100
+ <Trash size={14} /> {words.remove}
101
+ </button>
102
+ )}
103
+ {links.map(link => (
104
+ <a key={link.key} className="tax-button tax-button-quiet" href={link.href} target="_blank" rel="noreferrer noopener">
105
+ {link.label} <External size={13} />
106
+ </a>
107
+ ))}
108
+ </div>
109
+ </div>
110
+ </header>
111
+ {detail?.video ? (
112
+ <video className="tax-preview" src={detail.video} controls muted playsInline preload="metadata" />
113
+ ) : detail?.image ? (
114
+ <img className="tax-preview" src={detail.image} alt="" loading="lazy" />
115
+ ) : null}
116
+ <section className="tax-readme" aria-label={words.readmeTitle}>
117
+ {error ? (
118
+ <div className="tax-empty tax-market-error">
119
+ <span>{error}</span>
120
+ <button type="button" className="tax-button" onClick={() => setAttempt(attempt + 1)}>
121
+ {words.retry}
122
+ </button>
123
+ </div>
124
+ ) : !detail ? (
125
+ <div className="tax-readme-loading" aria-busy="true">
126
+ <span />
127
+ <span />
128
+ <span />
129
+ </div>
130
+ ) : detail.readme ? (
131
+ <Markdown text={detail.readme} />
132
+ ) : (
133
+ <div className="tax-note">{words.noReadme}</div>
134
+ )}
135
+ </section>
136
+ </article>
137
+ );
138
+ }
@@ -0,0 +1,94 @@
1
+ import type { TaPackageInfo } from '@celljs/ta-protocol';
2
+ import { type ExtensionsContext, icon } from './context';
3
+ import { MarketUtil } from './market-util';
4
+ import { React } from './react';
5
+
6
+ /** Where a package of the market stands on this computer. */
7
+ export type MarketStatus = { kind: 'none' } | { kind: 'installing' } | { kind: 'builtin' } | { kind: 'installed'; pkg: TaPackageInfo };
8
+
9
+ /** A React hook: the status of a package of the market, by the packages Ta loads and what is being installed. */
10
+ export function useMarketStatus(context: ExtensionsContext, name: string): MarketStatus {
11
+ const { packages } = React.useSyncExternalStore(
12
+ listener => context.store.subscribe(listener),
13
+ () => context.store.state,
14
+ );
15
+ const installing = React.useSyncExternalStore(
16
+ listener => context.market.subscribe(listener),
17
+ () => context.market.state.installing.has(name),
18
+ );
19
+ if (installing) {
20
+ return { kind: 'installing' };
21
+ }
22
+ const pkg = packages?.find(candidate => candidate.name === name);
23
+ return !pkg ? { kind: 'none' } : pkg.origin === 'builtin' ? { kind: 'builtin' } : { kind: 'installed', pkg };
24
+ }
25
+
26
+ /** The face of a package: its initials on a tint of its own, as npm gives no picture. */
27
+ export function PackageFace({ name, size }: { name: string; size: number }): React.ReactElement {
28
+ const { letters, hue } = MarketUtil.monogram(name);
29
+ return (
30
+ <span className="tax-face" aria-hidden="true" style={{ width: size, height: size, fontSize: Math.round(size * 0.36), ['--tax-hue' as string]: hue }}>
31
+ {letters}
32
+ </span>
33
+ );
34
+ }
35
+
36
+ /** `@scope/` lighter than the name itself, which is what people tell packages apart by. */
37
+ export function PackageName({ name }: { name: string }): React.ReactNode {
38
+ const slash = name.startsWith('@') ? name.indexOf('/') : -1;
39
+ return slash > 0 ? (
40
+ <>
41
+ <span className="tax-scope">{name.slice(0, slash + 1)}</span>
42
+ {name.slice(slash + 1)}
43
+ </>
44
+ ) : (
45
+ name
46
+ );
47
+ }
48
+
49
+ export interface InstallButtonProps {
50
+ context: ExtensionsContext;
51
+ name: string;
52
+ /** The larger button of the page of a package. */
53
+ large?: boolean;
54
+ }
55
+
56
+ /** Install in one click; then what is: installing, installed, or come with Ta. */
57
+ export function InstallButton({ context, name, large }: InstallButtonProps): React.ReactElement {
58
+ const { pi, actions } = context;
59
+ const words = actions.words;
60
+ const status = useMarketStatus(context, name);
61
+ const size = large ? ' tax-install-large' : '';
62
+ if (status.kind === 'installing') {
63
+ const Loader = icon(pi, 'LoaderCircle');
64
+ return (
65
+ <span className={`tax-install tax-install-busy${size}`} role="status">
66
+ <span className="tax-spin">
67
+ <Loader size={large ? 15 : 13} />
68
+ </span>
69
+ {words.installing}
70
+ </span>
71
+ );
72
+ }
73
+ if (status.kind !== 'none') {
74
+ const Check = icon(pi, 'Check');
75
+ return (
76
+ <span className={`tax-install tax-install-done${size}`}>
77
+ {status.kind === 'installed' && <Check size={large ? 15 : 13} />}
78
+ {status.kind === 'installed' ? words.installedTag : words.builtinTag}
79
+ </span>
80
+ );
81
+ }
82
+ return (
83
+ <button
84
+ type="button"
85
+ className={`tax-install${size}`}
86
+ onClick={event => {
87
+ event.stopPropagation();
88
+ void actions.installFromMarket(name);
89
+ }}
90
+ >
91
+ {words.install}
92
+ </button>
93
+ );
94
+ }
@@ -0,0 +1,116 @@
1
+ import type { WebExtensionAPI } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
+ import type { MarketDetail, MarketPackage, MarketPage } from './market-util';
3
+
4
+ export interface MarketState {
5
+ query: string;
6
+ /** Undefined until the first page of a search came. */
7
+ packages?: MarketPackage[];
8
+ /** How many there are, for a search without words. */
9
+ total?: number;
10
+ /** Where the next page starts; undefined at the end. */
11
+ next?: number;
12
+ /** A search, or its next page, is on its way. */
13
+ loading: boolean;
14
+ error?: string;
15
+ /** Names of the packages being installed. */
16
+ installing: ReadonlySet<string>;
17
+ }
18
+
19
+ /**
20
+ * The market as the page shows it: the search and its pages, asked of the host of the package, which
21
+ * asks npm; and what is being installed, which goes on while the user looks elsewhere.
22
+ */
23
+ export class MarketStore {
24
+ protected current: MarketState = { query: '', loading: false, installing: new Set() };
25
+ protected readonly listeners = new Set<() => void>();
26
+ protected readonly details = new Map<string, Promise<MarketDetail>>();
27
+ /** Each search counts up: the answer of an older one is dropped. */
28
+ protected generation = 0;
29
+
30
+ constructor(protected readonly pi: WebExtensionAPI) {}
31
+
32
+ get state(): MarketState {
33
+ return this.current;
34
+ }
35
+
36
+ subscribe(listener: () => void): () => void {
37
+ this.listeners.add(listener);
38
+ return () => this.listeners.delete(listener);
39
+ }
40
+
41
+ /** Asks again only when the query changed, or the last time failed; the same one on its way is waited for. */
42
+ async search(query: string): Promise<void> {
43
+ const trimmed = query.trim();
44
+ if (trimmed === this.current.query && (this.current.packages || this.current.loading) && !this.current.error) {
45
+ return;
46
+ }
47
+ const generation = ++this.generation;
48
+ this.set({ query: trimmed, loading: true, error: undefined });
49
+ try {
50
+ const page = await this.pi.callHost<MarketPage>('searchMarket', trimmed, 0);
51
+ if (generation === this.generation) {
52
+ this.set({ packages: page.packages, total: page.total, next: page.next, loading: false });
53
+ }
54
+ } catch (error) {
55
+ if (generation === this.generation) {
56
+ this.set({ packages: undefined, total: undefined, next: undefined, loading: false, error: MarketStore.message(error) });
57
+ }
58
+ }
59
+ }
60
+
61
+ /** The next page, when there is one and none is on its way. */
62
+ async more(): Promise<void> {
63
+ const { packages, next, loading, query } = this.current;
64
+ if (!packages || loading || next === undefined) {
65
+ return;
66
+ }
67
+ const generation = this.generation;
68
+ this.set({ loading: true });
69
+ try {
70
+ const page = await this.pi.callHost<MarketPage>('searchMarket', query, next);
71
+ if (generation === this.generation) {
72
+ const seen = new Set(packages.map(pkg => pkg.name));
73
+ const fresh = page.packages.filter(pkg => !seen.has(pkg.name));
74
+ // npm ranks again between pages: stop when one brings nothing new.
75
+ this.set({ packages: [...packages, ...fresh], next: fresh.length ? page.next : undefined, loading: false });
76
+ }
77
+ } catch (error) {
78
+ if (generation === this.generation) {
79
+ this.set({ loading: false });
80
+ this.pi.ui.notify(MarketStore.message(error), 'error');
81
+ }
82
+ }
83
+ }
84
+
85
+ /** Kept for the page: going back and forth does not ask again. */
86
+ detail(name: string): Promise<MarketDetail> {
87
+ let detail = this.details.get(name);
88
+ if (!detail) {
89
+ detail = this.pi.callHost<MarketDetail>('marketPackage', name);
90
+ this.details.set(name, detail);
91
+ detail.catch(() => this.details.delete(name));
92
+ }
93
+ return detail;
94
+ }
95
+
96
+ setInstalling(name: string, installing: boolean): void {
97
+ const next = new Set(this.current.installing);
98
+ if (installing) {
99
+ next.add(name);
100
+ } else {
101
+ next.delete(name);
102
+ }
103
+ this.set({ installing: next });
104
+ }
105
+
106
+ protected set(change: Partial<MarketState>): void {
107
+ this.current = { ...this.current, ...change };
108
+ for (const listener of this.listeners) {
109
+ listener();
110
+ }
111
+ }
112
+
113
+ static message(error: unknown): string {
114
+ return error instanceof Error ? error.message : String(error);
115
+ }
116
+ }