@team-antioch/sc2-doodad-finder 0.0.0-stage → 0.1.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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/bin/sc2-doodad-finder.js +7 -0
  4. package/dist/asker.d.ts +86 -0
  5. package/dist/asker.js +205 -0
  6. package/dist/cache-dir.d.ts +4 -0
  7. package/dist/cache-dir.js +17 -0
  8. package/dist/card-html.d.ts +13 -0
  9. package/dist/card-html.js +34 -0
  10. package/dist/cards.d.ts +20 -0
  11. package/dist/cards.js +65 -0
  12. package/dist/cli/doodad-finder.d.ts +44 -0
  13. package/dist/cli/doodad-finder.js +95 -0
  14. package/dist/cli/is-main.d.ts +6 -0
  15. package/dist/cli/is-main.js +17 -0
  16. package/dist/credentials.d.ts +29 -0
  17. package/dist/credentials.js +31 -0
  18. package/dist/embedder.d.ts +22 -0
  19. package/dist/embedder.js +48 -0
  20. package/dist/embedding-index.d.ts +25 -0
  21. package/dist/embedding-index.js +125 -0
  22. package/dist/finder.d.ts +58 -0
  23. package/dist/finder.js +144 -0
  24. package/dist/jev-ranker.d.ts +16 -0
  25. package/dist/jev-ranker.js +62 -0
  26. package/dist/key-file.d.ts +13 -0
  27. package/dist/key-file.js +62 -0
  28. package/dist/login.d.ts +32 -0
  29. package/dist/login.js +136 -0
  30. package/dist/narrow.d.ts +47 -0
  31. package/dist/narrow.js +97 -0
  32. package/dist/page.d.ts +2 -0
  33. package/dist/page.js +349 -0
  34. package/dist/payload-log.d.ts +5 -0
  35. package/dist/payload-log.js +12 -0
  36. package/dist/ranker.d.ts +81 -0
  37. package/dist/ranker.js +40 -0
  38. package/dist/server.d.ts +147 -0
  39. package/dist/server.js +577 -0
  40. package/dist/settings.d.ts +7 -0
  41. package/dist/settings.js +20 -0
  42. package/dist/spend-cap.d.ts +14 -0
  43. package/dist/spend-cap.js +22 -0
  44. package/dist/start.d.ts +60 -0
  45. package/dist/start.js +77 -0
  46. package/dist/stock-sources.d.ts +17 -0
  47. package/dist/stock-sources.js +34 -0
  48. package/dist/tags.d.ts +23 -0
  49. package/dist/tags.js +56 -0
  50. package/dist/test-asks.d.ts +46 -0
  51. package/dist/test-asks.js +81 -0
  52. package/dist/tray.d.ts +21 -0
  53. package/dist/tray.js +19 -0
  54. package/dist/wording.d.ts +7 -0
  55. package/dist/wording.js +17 -0
  56. package/package.json +57 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TeamAntioch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @team-antioch/sc2-doodad-finder
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ask for StarCraft II doodads in plain words and see ranked cards at once: a local page that narrows each ask with a keyword search and a local embeddings model, then ranks the candidates with Jev (optional: save a TypeSafe key with `npx @team-antioch/sc2-doodad-finder login`, or set `TYPESAFE_API_KEY`).
4
+
5
+ ```sh
6
+ npx @team-antioch/sc2-doodad-finder --open
7
+ ```
8
+
9
+ The first start extracts the catalog's fields from SC2GameData into your cache folder and downloads the embeddings model. `npx @team-antioch/sc2-doodad-finder extract` extracts again. `login` asks for your TypeSafe key and saves it in your config folder, and `logout` deletes it. Options: `--port <n>`, `--budget <dollars>` (Jev's spend cap per session, $1.00 by default), `--tick-log <folder>`, `--open`.
10
+
11
+ Getting a TypeSafe key, where it is kept, what each ask sends, the cost and the cap, the cache folders and the platforms: see the [repo's README](https://github.com/TeamAntioch/sc2-asset-catalog#readme).
12
+
13
+ Not affiliated with or endorsed by Blizzard Entertainment. MIT License.
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../dist/cli/doodad-finder.js";
3
+
4
+ main().catch((error) => {
5
+ console.error(error instanceof Error ? error.message : error);
6
+ process.exitCode = 1;
7
+ });
@@ -0,0 +1,86 @@
1
+ import type { NarrowOptions, Narrowing } from "./finder.ts";
2
+ import type { Narrowed, Tag } from "./narrow.ts";
3
+ import { type Ranker, type RankerName, type Ranking } from "./ranker.ts";
4
+ import type { SpendCap } from "./spend-cap.ts";
5
+ export type AskMode = "type" | "enter" | "refresh";
6
+ /** What an ask runs with, besides its text: the page's state when it was made. */
7
+ export type AskContext = {
8
+ readonly tags?: readonly Tag[] | undefined;
9
+ /** The object the ask is a part of, when there is one: context for the ranker. */
10
+ readonly object?: string | undefined;
11
+ /** A map's dependencies: their doodads are marked and kept first. */
12
+ readonly dependencies?: readonly string[] | undefined;
13
+ };
14
+ export type AskRequest = AskContext & {
15
+ readonly text: string;
16
+ /** `type` for a keystroke, `enter` to rank now, `refresh` to narrow again now (the tags changed). */
17
+ readonly mode: AskMode;
18
+ /** The page state's version: an ask is its text and version. */
19
+ readonly version: number;
20
+ /** How long typing pauses before the ranker runs, in ms: the page's setting. */
21
+ readonly idleMs?: number | undefined;
22
+ };
23
+ export type RankedCandidate = Narrowed & {
24
+ readonly level: number;
25
+ };
26
+ export type AskEvent = {
27
+ readonly type: "narrowed";
28
+ readonly text: string;
29
+ readonly version: number;
30
+ readonly candidates: readonly Narrowed[];
31
+ readonly ms: number;
32
+ } | {
33
+ readonly type: "ranked";
34
+ readonly text: string;
35
+ readonly version: number;
36
+ readonly ranker: RankerName;
37
+ /** The tags it ran with. */
38
+ readonly tags: readonly Tag[];
39
+ readonly candidates: readonly RankedCandidate[];
40
+ /** From the ranker being asked for to its order: the narrowing, the call and the order. */
41
+ readonly ms: number;
42
+ readonly cost: number;
43
+ } | {
44
+ readonly type: "failed";
45
+ readonly text: string;
46
+ readonly version: number;
47
+ readonly ranker: RankerName;
48
+ readonly error: string;
49
+ } | {
50
+ readonly type: "capped";
51
+ readonly text: string;
52
+ readonly version: number;
53
+ readonly reason: string;
54
+ };
55
+ export type AskTiming = {
56
+ readonly debounceMs: number;
57
+ readonly idleMs: number;
58
+ readonly budgetMs: number;
59
+ };
60
+ /** The spec's timings: narrow after 250 ms, rank after 1.5 s idle, wait 300 ms for the ranker. */
61
+ export declare const ASK_TIMING: AskTiming;
62
+ /** An ask's ranking: the ranker's answer and the narrowed candidates in its order. */
63
+ export type AskRanking = {
64
+ readonly ranking: Ranking;
65
+ readonly tags: readonly Tag[];
66
+ readonly candidates: readonly RankedCandidate[];
67
+ readonly ms: number;
68
+ };
69
+ export type AskerOptions = {
70
+ readonly narrow: (text: string, options: NarrowOptions) => Promise<Narrowing>;
71
+ /** The ranker; with none, asks are narrowed only. */
72
+ readonly ranker?: Ranker | undefined;
73
+ /** The session's spend cap: past it, no more ranker calls. Each ranking's cost is recorded in it. */
74
+ readonly budget?: SpendCap;
75
+ readonly emit: (event: AskEvent) => void;
76
+ readonly timing?: Partial<AskTiming>;
77
+ /** Called with each ranker's answer. */
78
+ readonly onRanking?: (ranking: Ranking) => void;
79
+ };
80
+ export type Asker = {
81
+ ask(request: AskRequest): void;
82
+ /** The ranking for an ask, for ticking a card from it: the one it has, else one made now. */
83
+ ranked(request: AskRequest): Promise<AskRanking>;
84
+ close(): void;
85
+ };
86
+ export declare function createAsker(options: AskerOptions): Asker;
package/dist/asker.js ADDED
@@ -0,0 +1,205 @@
1
+ // The Doodad Finder process's asks (docs/adr/0001), behind the page's ask endpoint. The page sends
2
+ // each change to the ask as it is typed; the process decides when to narrow and when to rank:
3
+ //
4
+ // typing the narrowing runs 250 ms after typing pauses, and its cards are shown
5
+ // idle 1.5 s after typing pauses (a setting), the ranker runs
6
+ // Enter the narrowing runs at once if it hasn't, then the ranker
7
+ // ranking the page waits up to 300 ms for the ranker; past that it is shown the narrowing's
8
+ // order, and the ranked order replaces it once, when the ranker answers
9
+ //
10
+ // A newer ask cancels the older one: its timers stop, its ranker call is aborted, and nothing it
11
+ // finds afterwards is sent. Asks are known by their text and the state version they were made in
12
+ // (its tags and the map's dependencies), and by the tags it runs with, so a change of tags is a new ask too. Once the session's spend cap is
13
+ // reached, an ask that would rank shows the narrowing's order and a `capped` event says why.
14
+ import { orderByFit, RankerError } from "./ranker.js";
15
+ /** The spec's timings: narrow after 250 ms, rank after 1.5 s idle, wait 300 ms for the ranker. */
16
+ export const ASK_TIMING = { debounceMs: 250, idleMs: 1500, budgetMs: 300 };
17
+ /** An ask's key: its version, its tags and its text. The version moves when the page's tags do, but a ticked card's ask can be ranked with the tags it was ticked with. */
18
+ const keyOf = ({ text, version, tags }) => `${version}\n${JSON.stringify((tags ?? []).map(({ facet, value, pinned }) => [facet, value, pinned === true]))}\n${text.trim()}`;
19
+ /** How many past asks' rankings are kept: going back to an earlier ask costs no call. */
20
+ const KEPT_RANKINGS = 50;
21
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
22
+ export function createAsker(options) {
23
+ const timing = { ...ASK_TIMING, ...options.timing };
24
+ const kept = new Map();
25
+ let current;
26
+ const { budget } = options;
27
+ const stale = (ask) => current !== ask;
28
+ const narrowNow = (ask) => {
29
+ if (ask.narrowing)
30
+ return ask.narrowing;
31
+ const { text, tags, dependencies } = ask.request;
32
+ const narrowing = options.narrow(text, { ...(tags ? { tags } : {}), dependencies });
33
+ ask.narrowing = narrowing;
34
+ // A failed narrowing isn't kept either: the next Enter or idle pause on this ask narrows again.
35
+ narrowing.catch(() => {
36
+ if (ask.narrowing === narrowing)
37
+ delete ask.narrowing;
38
+ });
39
+ return narrowing;
40
+ };
41
+ const showNarrowing = async (ask) => {
42
+ const narrowing = await narrowNow(ask);
43
+ if (stale(ask) || ask.shown)
44
+ return;
45
+ ask.shown = "narrowed";
46
+ options.emit({ type: "narrowed", text: ask.request.text, version: ask.request.version, candidates: narrowing.candidates, ms: narrowing.timings.total });
47
+ };
48
+ const rankingOf = (ask, ranker) => {
49
+ if (ask.ranking)
50
+ return ask.ranking;
51
+ const known = kept.get(ask.key);
52
+ if (known?.ranking.ranker === ranker.name)
53
+ return (ask.ranking = Promise.resolve(known));
54
+ const started = performance.now();
55
+ ask.ranking = (async () => {
56
+ const { candidates: narrowed } = await narrowNow(ask);
57
+ const { text, object, tags } = ask.request;
58
+ let ranking;
59
+ try {
60
+ ranking = narrowed.length ? await ranker.rank({ ask: text, object, tags, candidates: narrowed.map(({ card }) => card) }, { signal: ask.controller.signal }) : undefined;
61
+ }
62
+ catch (error) {
63
+ // A call answered (and paid for) but not read still counts against the cap.
64
+ if (error instanceof RankerError && error.cost > 0)
65
+ budget?.record(error.cost);
66
+ throw error;
67
+ }
68
+ if (ranking) {
69
+ budget?.record(ranking.cost);
70
+ options.onRanking?.(ranking);
71
+ }
72
+ const candidates = ranking ? orderByFit(narrowed, ranking.grades) : [];
73
+ const result = {
74
+ ranking: ranking ?? { ranker: ranker.name, model: "", grades: new Map(), timings: { request: 0, total: 0 }, usage: { input: 0, output: 0 }, cost: 0 },
75
+ tags: tags ?? [],
76
+ candidates,
77
+ ms: performance.now() - started,
78
+ };
79
+ kept.delete(ask.key);
80
+ kept.set(ask.key, result);
81
+ if (kept.size > KEPT_RANKINGS)
82
+ kept.delete(kept.keys().next().value);
83
+ return result;
84
+ })();
85
+ // A ranking no one waits for (it was cancelled) mustn't be an unhandled rejection.
86
+ ask.ranking.catch(() => { });
87
+ return ask.ranking;
88
+ };
89
+ /** Whether the ask's ranking is known, so no call is needed for it. */
90
+ const known = (ask, ranker) => ask.ranking !== undefined || kept.get(ask.key)?.ranking.ranker === ranker.name;
91
+ const rankNow = async (ask) => {
92
+ const { ranker } = options;
93
+ if (!ranker)
94
+ return showNarrowing(ask);
95
+ if (ask.rankStarted)
96
+ return;
97
+ ask.rankStarted = true;
98
+ if (budget && !budget.allows() && !known(ask, ranker)) {
99
+ await showNarrowing(ask);
100
+ if (!stale(ask))
101
+ options.emit({ type: "capped", text: ask.request.text, version: ask.request.version, reason: budget.reason });
102
+ return;
103
+ }
104
+ const ranking = rankingOf(ask, ranker);
105
+ const late = await Promise.race([ranking.then(() => false, () => false), sleep(timing.budgetMs).then(() => true)]);
106
+ try {
107
+ if (late)
108
+ await showNarrowing(ask);
109
+ const { candidates, ranking: answer, ms, tags } = await ranking;
110
+ if (stale(ask))
111
+ return;
112
+ ask.shown = "ranked";
113
+ options.emit({ type: "ranked", text: ask.request.text, version: ask.request.version, ranker: ranker.name, tags, candidates, ms, cost: answer.cost });
114
+ }
115
+ catch (error) {
116
+ if (stale(ask))
117
+ return;
118
+ // A failed ranking isn't kept: the next Enter or idle pause on this ask calls the ranker again.
119
+ delete ask.ranking;
120
+ ask.rankStarted = false;
121
+ // The narrowing's order is shown when the narrowing worked; when it failed, it isn't run again now.
122
+ if (ask.narrowing)
123
+ await showNarrowing(ask).catch(() => { });
124
+ if (stale(ask))
125
+ return;
126
+ options.emit({ type: "failed", text: ask.request.text, version: ask.request.version, ranker: ranker.name, error: error.message });
127
+ }
128
+ };
129
+ const later = (ask, timer, ms, run) => {
130
+ clearTimeout(ask[timer]);
131
+ ask[timer] = setTimeout(() => void run(ask).catch(() => { }), ms);
132
+ };
133
+ const stopTimers = (ask) => {
134
+ clearTimeout(ask.debounce);
135
+ clearTimeout(ask.idle);
136
+ };
137
+ const cancel = (ask) => {
138
+ if (!ask)
139
+ return;
140
+ stopTimers(ask);
141
+ ask.controller.abort(new Error("A newer ask replaced this one"));
142
+ };
143
+ return {
144
+ ask(request) {
145
+ const key = keyOf(request);
146
+ let ask = current;
147
+ if (ask?.key !== key) {
148
+ cancel(current);
149
+ current = undefined;
150
+ if (!request.text.trim())
151
+ return;
152
+ ask = { key, request, controller: new AbortController() };
153
+ current = ask;
154
+ if (request.mode === "type")
155
+ later(ask, "debounce", timing.debounceMs, showNarrowing);
156
+ }
157
+ const idle = request.idleMs ?? timing.idleMs;
158
+ if (request.mode === "type") {
159
+ // The same ask typed again (a trailing space): the idle wait starts over.
160
+ if (!ask.rankStarted)
161
+ later(ask, "idle", idle, rankNow);
162
+ }
163
+ else if (request.mode === "enter") {
164
+ stopTimers(ask);
165
+ void rankNow(ask).catch(() => { });
166
+ }
167
+ else {
168
+ stopTimers(ask);
169
+ void showNarrowing(ask).catch(() => { });
170
+ if (!ask.rankStarted)
171
+ later(ask, "idle", idle, rankNow);
172
+ }
173
+ },
174
+ async ranked(request) {
175
+ const key = keyOf(request);
176
+ const known = kept.get(key);
177
+ if (known)
178
+ return known;
179
+ const { ranker } = options;
180
+ if (!ranker)
181
+ throw new Error("No ranker is on");
182
+ // A ranking already under way for the current ask was paid for before the cap was reached.
183
+ if (budget && !budget.allows() && !(current?.key === key && current.ranking))
184
+ throw new Error(`No ranking: ${budget.reason}`);
185
+ if (current?.key === key) {
186
+ const ask = current;
187
+ void rankNow(ask).catch(() => { });
188
+ try {
189
+ return await rankingOf(ask, ranker);
190
+ }
191
+ catch (error) {
192
+ // A newer ask cancelled it: the tick still needs it, so it is ranked on its own below.
193
+ if (!ask.controller.signal.aborted)
194
+ throw error;
195
+ }
196
+ }
197
+ // An ask no longer current: ranked on its own, its results not sent.
198
+ return rankingOf({ key, request, controller: new AbortController() }, ranker);
199
+ },
200
+ close() {
201
+ cancel(current);
202
+ current = undefined;
203
+ },
204
+ };
205
+ }
@@ -0,0 +1,4 @@
1
+ import { type CachePlatform } from "@team-antioch/sc2-asset-catalog/catalog/catalog-dirs.js";
2
+ export type { CachePlatform } from "@team-antioch/sc2-asset-catalog/catalog/catalog-dirs.js";
3
+ /** Where the model's weights are kept: $SC2_ASSET_CATALOG_MODEL_CACHE (or, for sc2-adjutant, $SC2_ADJUTANT_MODEL_CACHE), else the cache folder's models. */
4
+ export declare function modelCacheDir(on?: CachePlatform): string;
@@ -0,0 +1,17 @@
1
+ // The Finder keeps its files in the catalog's cache folder (catalogCacheDir, catalog-dirs.ts in
2
+ // @team-antioch/sc2-asset-catalog), on each platform where that platform keeps caches: %LOCALAPPDATA%
3
+ // on Windows, ~/Library/Caches on macOS, $XDG_CACHE_HOME (else ~/.cache) elsewhere, or
4
+ // SC2_ASSET_CATALOG_CACHE on any of them. It holds the extracted catalog fields, the embeddings
5
+ // model's weights, the card vectors, Jev's payload logs and the page's settings: all of it a copy
6
+ // of something else, safe to delete.
7
+ import path from "node:path";
8
+ import { catalogCacheDir } from "@team-antioch/sc2-asset-catalog/catalog/catalog-dirs.js";
9
+ /** Where the model's weights are kept: $SC2_ASSET_CATALOG_MODEL_CACHE (or, for sc2-adjutant, $SC2_ADJUTANT_MODEL_CACHE), else the cache folder's models. */
10
+ export function modelCacheDir(on = {}) {
11
+ const env = on.env ?? process.env;
12
+ const moved = env.SC2_ASSET_CATALOG_MODEL_CACHE || env.SC2_ADJUTANT_MODEL_CACHE;
13
+ if (moved)
14
+ return moved;
15
+ const dir = catalogCacheDir(on);
16
+ return (on.platform ?? process.platform) === "win32" ? path.win32.join(dir, "models") : path.posix.join(dir, "models");
17
+ }
@@ -0,0 +1,13 @@
1
+ import type { DoodadPicture } from "@team-antioch/sc2-asset-catalog/catalog/doodad-search.js";
2
+ import type { CandidateCard } from "./cards.ts";
3
+ /** Where the process serves a doodad's sheet. */
4
+ export declare const sheetUrl: (id: string) => string;
5
+ /** A level's short name: the four levels' words before the colon. */
6
+ export declare const levelName: (level: number) => string;
7
+ /** The dependency badge: with a choice, `provided`'s text for a card it provides; else what the card needs, if anything. */
8
+ export declare function badge(card: CandidateCard, provided?: string): {
9
+ readonly text: string;
10
+ readonly provided: boolean;
11
+ } | undefined;
12
+ /** A card's markup, with its tick box; the level is filled in on the page when the ranker answers. */
13
+ export declare function cardHtml(card: CandidateCard, picture: DoodadPicture, provided?: string): string;
@@ -0,0 +1,34 @@
1
+ // A candidate's card on the Finder's page: its sheet or gallery picture (zoomable), its
2
+ // name, id and look, the ranker's level once it has one, and its dependency badge: "needs Void
3
+ // (Campaign)", or with a choice from the Finder's badges option, its own text ("in this map")
4
+ // for a card the choice provides. The picture and the escaping are the catalog's doodad-card-html.ts. A sheet is served by the Finder's process, since a page served over
5
+ // HTTP can't load a file.
6
+ import { dependencyName, escapeHtml, pictureHtml } from "@team-antioch/sc2-asset-catalog/catalog/doodad-card-html.js";
7
+ import { LEVELS } from "./wording.js";
8
+ /** Where the process serves a doodad's sheet. */
9
+ export const sheetUrl = (id) => `/sheet/${encodeURIComponent(id)}`;
10
+ /** A level's short name: the four levels' words before the colon. */
11
+ export const levelName = (level) => {
12
+ const words = LEVELS[Math.min(LEVELS.length - 1, Math.max(0, Math.round(level)))];
13
+ return words.slice(0, words.indexOf(":")).toLowerCase();
14
+ };
15
+ /** The dependency badge: with a choice, `provided`'s text for a card it provides; else what the card needs, if anything. */
16
+ export function badge(card, provided) {
17
+ if (provided !== undefined && card.provided)
18
+ return { text: provided, provided: true };
19
+ if (card.dependency !== undefined)
20
+ return { text: `needs ${dependencyName(card.dependency)}`, provided: false };
21
+ return undefined;
22
+ }
23
+ /** A card's markup, with its tick box; the level is filled in on the page when the ranker answers. */
24
+ export function cardHtml(card, picture, provided) {
25
+ const { id, name } = card;
26
+ const look = card.entry.description?.look;
27
+ const needs = badge(card, provided);
28
+ return [
29
+ `<header><label><input type="checkbox" class="tick" aria-label="Tick ${escapeHtml(name)}"> <span class="name">${escapeHtml(name)}</span></label> <code>${escapeHtml(id)}</code></header>`,
30
+ pictureHtml(picture, name, picture.kind === "image", () => sheetUrl(id)),
31
+ `<p class="look">${look ? escapeHtml(look) : "no description"}${card.pending ? " (description pending)" : ""}</p>`,
32
+ `<p class="facts"><span class="level"></span>${needs ? `<span class="badge${needs.provided ? " provided" : ""}">${escapeHtml(needs.text)}</span>` : ""}</p>`,
33
+ ].join("");
34
+ }
@@ -0,0 +1,20 @@
1
+ import { type DoodadEntry, type DoodadSearchSources } from "@team-antioch/sc2-asset-catalog/catalog/doodad-search.js";
2
+ export type CandidateCard = {
3
+ readonly id: string;
4
+ readonly name: string;
5
+ readonly source: DoodadEntry["source"];
6
+ /** The card's text: what is embedded and what the ranker reads. */
7
+ readonly text: string;
8
+ /** The entry the card was written from: its facets, for tags, and its look, for the page. */
9
+ readonly entry: DoodadEntry;
10
+ /** The map dependency it needs, absent when the default Void (Mod) brings it in. */
11
+ readonly dependency?: string;
12
+ /** For a map's dependencies: whether its dependencies already bring it in. */
13
+ readonly provided?: boolean;
14
+ /** A mod doodad its index has no description of for its current model. */
15
+ readonly pending?: true;
16
+ };
17
+ /** A card's text: its name line, then its look, facets, uses and pending flag, each when it has one. */
18
+ export declare function cardText(entry: DoodadEntry): string;
19
+ /** The card for every doodad, terrain object and mod doodad the sources hold; with a map's dependencies, each marked provided or not. */
20
+ export declare function candidateCards(sources: DoodadSearchSources, dependencies?: readonly string[]): CandidateCard[];
package/dist/cards.js ADDED
@@ -0,0 +1,65 @@
1
+ // The Doodad Finder's candidate cards (docs/adr/0001): each game doodad, terrain object and mod
2
+ // doodad as a few lines of text, about 50 to 80 tokens, that the embeddings model embeds and the
3
+ // ranker reads. A card holds the name, the id's words, the look, kind, size, role, story, biome,
4
+ // tilesets and Doodad Use phrases. Where a use came from (its `from`) stays out: it names a search,
5
+ // not the doodad. An undescribed doodad's card is its name and id words alone.
6
+ import { allDoodadEntries, idWords } from "@team-antioch/sc2-asset-catalog/catalog/doodad-search.js";
7
+ /** About 80 tokens: a card stops adding Doodad Uses past this many words. */
8
+ const MAX_WORDS = 60;
9
+ const wordCount = (text) => text.split(/\s+/).filter(Boolean).length;
10
+ const sameWords = (a, b) => (a.toLowerCase().match(/[a-z0-9]+/g) ?? []).join(" ") === (b.toLowerCase().match(/[a-z0-9]+/g) ?? []).join(" ");
11
+ /** A card's text: its name line, then its look, facets, uses and pending flag, each when it has one. */
12
+ export function cardText(entry) {
13
+ const words = idWords(entry.id);
14
+ const lines = [sameWords(entry.name, words) ? entry.name : `${entry.name} (${words})`];
15
+ const { description } = entry;
16
+ if (description) {
17
+ lines.push(`look: ${description.look}`);
18
+ const facets = [[description.kind, description.size, description.role ?? description.use].filter(Boolean).join(", ")];
19
+ if (description.story?.length)
20
+ facets.push(`story: ${description.story.join(", ")}`);
21
+ if (description.biome?.length)
22
+ facets.push(`biome: ${description.biome.join(", ")}`);
23
+ if (entry.tilesets?.length)
24
+ facets.push(`tilesets: ${entry.tilesets.join(", ")}`);
25
+ const facetLine = facets.filter(Boolean).join("; ");
26
+ if (facetLine)
27
+ lines.push(facetLine);
28
+ const uses = [];
29
+ let budget = MAX_WORDS - wordCount(lines.join(" ")) - 2;
30
+ for (const { use } of entry.uses) {
31
+ const cost = wordCount(use);
32
+ if (uses.length > 0 && cost > budget)
33
+ break;
34
+ uses.push(use);
35
+ budget -= cost;
36
+ }
37
+ if (uses.length)
38
+ lines.push(`used as: ${uses.join("; ")}`);
39
+ }
40
+ if (entry.pending)
41
+ lines.push(description ? "pending: described for an earlier model" : "pending: not yet described");
42
+ return lines.join("\n");
43
+ }
44
+ const PREFERRED = { mod: 0, doodad: 1, "terrain-object": 2 };
45
+ /** The card for every doodad, terrain object and mod doodad the sources hold; with a map's dependencies, each marked provided or not. */
46
+ export function candidateCards(sources, dependencies) {
47
+ // A terrain object may share an id with a game doodad or a mod doodad: the id names the
48
+ // one a lookup by id gives: the mod's, else the game doodad.
49
+ const entries = new Map();
50
+ for (const entry of allDoodadEntries(sources, dependencies)) {
51
+ const known = entries.get(entry.id);
52
+ if (!known || PREFERRED[entry.source] < PREFERRED[known.source])
53
+ entries.set(entry.id, entry);
54
+ }
55
+ return [...entries.values()].map((entry) => ({
56
+ id: entry.id,
57
+ name: entry.name,
58
+ source: entry.source,
59
+ text: cardText(entry),
60
+ entry,
61
+ ...(entry.dependency !== undefined ? { dependency: entry.dependency } : {}),
62
+ ...(entry.provided !== undefined ? { provided: entry.provided } : {}),
63
+ ...(entry.pending ? { pending: true } : {}),
64
+ }));
65
+ }
@@ -0,0 +1,44 @@
1
+ import { type RunningFinder } from "../start.ts";
2
+ export declare const USAGE = "Usage: sc2-doodad-finder [--port n] [--budget dollars] [--tick-log <folder>] [--open]\n sc2-doodad-finder extract | login | logout";
3
+ export type FinderArgs = {
4
+ readonly port: number;
5
+ readonly budget?: number;
6
+ readonly tickLog?: string;
7
+ readonly open: boolean;
8
+ readonly help?: true;
9
+ readonly extract?: true;
10
+ readonly login?: true;
11
+ readonly logout?: true;
12
+ };
13
+ /** The CLI's options, for parseArgs: sc2-adjutant's CLI adds its own to these. */
14
+ export declare const FINDER_ARG_OPTIONS: {
15
+ readonly port: {
16
+ readonly type: "string";
17
+ };
18
+ readonly budget: {
19
+ readonly type: "string";
20
+ };
21
+ readonly "tick-log": {
22
+ readonly type: "string";
23
+ };
24
+ readonly open: {
25
+ readonly type: "boolean";
26
+ };
27
+ readonly help: {
28
+ readonly type: "boolean";
29
+ };
30
+ };
31
+ /** The options from parsed values, `--tick-log` resolved from `cwd`. */
32
+ export declare function finderArgs(values: {
33
+ readonly port?: string | undefined;
34
+ readonly budget?: string | undefined;
35
+ readonly "tick-log"?: string | undefined;
36
+ readonly open?: boolean | undefined;
37
+ readonly help?: boolean | undefined;
38
+ }, cwd: string, usage?: string): FinderArgs;
39
+ /** The CLI's options and command: none, `extract`, `login` or `logout`. */
40
+ export declare function parseFinderArgs(args: readonly string[], cwd: string): FinderArgs;
41
+ /** Says what started, opens the page if asked, and stops on Ctrl-C. */
42
+ export declare function announce(running: RunningFinder, { open, budget }: Pick<FinderArgs, "open" | "budget">, started: number): void;
43
+ /** Runs the CLI with its arguments: bin/sc2-doodad-finder.js calls this. */
44
+ export declare function main(argv?: readonly string[]): Promise<void>;
@@ -0,0 +1,95 @@
1
+ // The Doodad Finder's CLI, `sc2-doodad-finder` (docs/adr/0001), with the public defaults: the
2
+ // stock catalog (extracted into the cache folder on a first start), Jev when TYPESAFE_API_KEY or
3
+ // the key file holds a key (else the narrowing's order), a spend cap of $1.00 a session unless --budget sets another,
4
+ // and a tick log only in a folder --tick-log names. It starts the Finder (start.ts) and prints the
5
+ // page's address. The process listens on 127.0.0.1 only. `extract` extracts the catalog again and
6
+ // starts nothing, as the catalog's own `sc2-asset-catalog extract` does. `login` saves the TypeSafe
7
+ // key to the key file and `logout` deletes it (login.ts). Starting it, the key and what each ask
8
+ // sends: the repo's README.md.
9
+ //
10
+ // sc2-doodad-finder [--port n] [--budget dollars] [--tick-log <folder>] [--open]
11
+ // sc2-doodad-finder extract | login | logout
12
+ import { execFile } from "node:child_process";
13
+ import path from "node:path";
14
+ import { parseArgs } from "node:util";
15
+ import { runCatalogCli } from "@team-antioch/sc2-asset-catalog";
16
+ import { keySourceText } from "../credentials.js";
17
+ import { login, logout } from "../login.js";
18
+ import { DEFAULT_BUDGET, dollars } from "../spend-cap.js";
19
+ import { startFinder } from "../start.js";
20
+ import { FINDER_PORT } from "../server.js";
21
+ import { isMainModule } from "./is-main.js";
22
+ export const USAGE = "Usage: sc2-doodad-finder [--port n] [--budget dollars] [--tick-log <folder>] [--open]\n sc2-doodad-finder extract | login | logout";
23
+ /** The CLI's options, for parseArgs: sc2-adjutant's CLI adds its own to these. */
24
+ export const FINDER_ARG_OPTIONS = { port: { type: "string" }, budget: { type: "string" }, "tick-log": { type: "string" }, open: { type: "boolean" }, help: { type: "boolean" } };
25
+ /** The options from parsed values, `--tick-log` resolved from `cwd`. */
26
+ export function finderArgs(values, cwd, usage = USAGE) {
27
+ const port = Number(values.port ?? FINDER_PORT);
28
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
29
+ throw new Error(`--port takes a port number\n${usage}`);
30
+ const budget = values.budget === undefined ? undefined : Number(values.budget);
31
+ if (budget !== undefined && !(budget >= 0))
32
+ throw new Error(`--budget takes US dollars, 0 or more\n${usage}`);
33
+ return {
34
+ port,
35
+ ...(budget !== undefined ? { budget } : {}),
36
+ ...(values["tick-log"] !== undefined ? { tickLog: path.resolve(cwd, values["tick-log"]) } : {}),
37
+ open: values.open === true,
38
+ ...(values.help ? { help: true } : {}),
39
+ };
40
+ }
41
+ const COMMANDS = ["extract", "login", "logout"];
42
+ /** The CLI's options and command: none, `extract`, `login` or `logout`. */
43
+ export function parseFinderArgs(args, cwd) {
44
+ const { values, positionals } = parseArgs({ args: [...args], options: FINDER_ARG_OPTIONS, allowPositionals: true });
45
+ const [command, ...rest] = positionals;
46
+ if ((command !== undefined && !COMMANDS.includes(command)) || rest.length)
47
+ throw new Error(USAGE);
48
+ return { ...finderArgs(values, cwd), ...(command ? { [command]: true } : {}) };
49
+ }
50
+ /** Says what started, opens the page if asked, and stops on Ctrl-C. */
51
+ export function announce(running, { open, budget }, started) {
52
+ console.log(`${running.cards} cards, ${running.embeddedOnOpen} embedded now; ready in ${Math.round(performance.now() - started)} ms`);
53
+ const key = running.keySource ? `, with ${keySourceText(running.keySource)}` : "";
54
+ console.log(running.off ? `Not ranking: ${running.off}` : `Ranking with Jev${key}, up to ${dollars(budget ?? DEFAULT_BUDGET)} this session`);
55
+ console.log(`The Doodad Finder is at ${running.url} (Ctrl-C stops it)`);
56
+ if (open)
57
+ execFile(process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open", [running.url]);
58
+ const stop = async () => {
59
+ await running.close();
60
+ if (running.spend)
61
+ console.log(`Estimated spend this run: $${running.spend.toFixed(4)}; payloads in ${running.payloadLog}`);
62
+ process.exit(0);
63
+ };
64
+ process.once("SIGINT", () => void stop());
65
+ process.once("SIGTERM", () => void stop());
66
+ }
67
+ /** Runs the CLI with its arguments: bin/sc2-doodad-finder.js calls this. */
68
+ export async function main(argv = process.argv.slice(2)) {
69
+ const args = parseFinderArgs(argv, process.env.INIT_CWD ?? process.cwd());
70
+ if (args.help)
71
+ return void console.log(USAGE);
72
+ if (args.extract)
73
+ return runCatalogCli(["extract"]);
74
+ if (args.login)
75
+ return void (process.exitCode = await login());
76
+ if (args.logout)
77
+ return logout();
78
+ const started = performance.now();
79
+ const running = await startFinder({
80
+ port: args.port,
81
+ ...(args.budget !== undefined ? { budget: args.budget } : {}),
82
+ ...(args.tickLog ? { tickLog: args.tickLog } : {}),
83
+ log: (line) => console.log(line),
84
+ });
85
+ if (args.tickLog)
86
+ console.log(`Ticks are logged to ${args.tickLog}`);
87
+ announce(running, args, started);
88
+ }
89
+ // Run as a file in a checkout (node src/cli/doodad-finder.ts); the package's bin calls main.
90
+ if (isMainModule(import.meta.url)) {
91
+ main().catch((error) => {
92
+ console.error(error instanceof Error ? error.message : error);
93
+ process.exitCode = 1;
94
+ });
95
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Whether the module at `url` is the one the process was started with (`argv1`, process.argv[1]),
3
+ * so a CLI module runs only then and is safe to import. Never throws: an argv[1] that isn't a file
4
+ * (a REPL, `node -e`, a test runner's own) is no module's.
5
+ */
6
+ export declare function isMainModule(url: string, argv1?: string | undefined): boolean;