dsh-stm32 0.1.8 → 0.1.9
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.
- package/README.md +567 -409
- package/README_EN.md +544 -410
- package/client/client.js +7033 -5021
- package/docs/reading-guide.md +921 -921
- package/lib/client.js +7033 -5021
- package/lib/commands/register.js +2 -0
- package/lib/data/firmware-packages.js +35 -0
- package/lib/data/firmware-pins.js +7 -0
- package/lib/data/install-guides.js +110 -0
- package/lib/data/ioc-presets.js +118 -0
- package/lib/engine/build.js +88 -2
- package/lib/engine/datasheet/auto.js +74 -0
- package/lib/engine/datasheet/digest.js +74 -0
- package/lib/engine/datasheet/lcsc.js +60 -0
- package/lib/engine/datasheet/pinout.js +119 -0
- package/lib/engine/datasheet/price.js +152 -0
- package/lib/engine/datasheet/search.js +147 -0
- package/lib/engine/datasheet/store.js +371 -0
- package/lib/engine/debug-session.js +2 -1
- package/lib/engine/ecad/autobuild.js +156 -0
- package/lib/engine/ecad/bom.js +238 -0
- package/lib/engine/ecad/brief.js +205 -0
- package/lib/engine/ecad/checks.js +239 -0
- package/lib/engine/ecad/design.js +177 -0
- package/lib/engine/ecad/dfm.js +314 -0
- package/lib/engine/ecad/easyeda.js +454 -0
- package/lib/engine/ecad/fabrication.js +104 -0
- package/lib/engine/ecad/gen/footprint.js +159 -0
- package/lib/engine/ecad/gen/symbol.js +103 -0
- package/lib/engine/ecad/import.js +372 -0
- package/lib/engine/ecad/jlcpcb.js +141 -0
- package/lib/engine/ecad/libs.js +316 -0
- package/lib/engine/ecad/models3d.js +89 -0
- package/lib/engine/ecad/netgate.js +286 -0
- package/lib/engine/ecad/normalize.js +182 -0
- package/lib/engine/ecad/package.js +126 -0
- package/lib/engine/ecad/padmerge.js +128 -0
- package/lib/engine/ecad/padprecheck.js +123 -0
- package/lib/engine/ecad/part-import.js +257 -0
- package/lib/engine/ecad/pcb/apply.js +53 -0
- package/lib/engine/ecad/pcb/emc-deep.js +396 -0
- package/lib/engine/ecad/pcb/emc.js +275 -0
- package/lib/engine/ecad/pcb/geometry.js +63 -0
- package/lib/engine/ecad/pcb/gerber.js +499 -0
- package/lib/engine/ecad/pcb/hand-sync.js +242 -0
- package/lib/engine/ecad/pcb/impedance.js +119 -0
- package/lib/engine/ecad/pcb/ipc-open.js +78 -0
- package/lib/engine/ecad/pcb/ipc-script.js +276 -0
- package/lib/engine/ecad/pcb/ipc.js +129 -0
- package/lib/engine/ecad/pcb/krt.js +182 -0
- package/lib/engine/ecad/pcb/links.js +393 -0
- package/lib/engine/ecad/pcb/mech.js +201 -0
- package/lib/engine/ecad/pcb/model-fix.js +178 -0
- package/lib/engine/ecad/pcb/netlist.js +146 -0
- package/lib/engine/ecad/pcb/pcb-svg.js +199 -0
- package/lib/engine/ecad/pcb/placement.js +140 -0
- package/lib/engine/ecad/pcb/power.js +203 -0
- package/lib/engine/ecad/pcb/render3d.js +208 -0
- package/lib/engine/ecad/pcb/route.js +167 -0
- package/lib/engine/ecad/pcb/router.js +469 -0
- package/lib/engine/ecad/pcb/rules.js +122 -0
- package/lib/engine/ecad/pcb/scene.js +513 -0
- package/lib/engine/ecad/pcb/stackup.js +154 -0
- package/lib/engine/ecad/pcb/swap.js +222 -0
- package/lib/engine/ecad/pcb/tracks.js +70 -0
- package/lib/engine/ecad/runtime.js +227 -0
- package/lib/engine/ecad/toolchain.js +146 -0
- package/lib/engine/ecad/tsci.js +362 -0
- package/lib/engine/ecad/zip.js +98 -0
- package/lib/engine/generate-script.js +4 -1
- package/lib/engine/generate.js +145 -5
- package/lib/engine/ioc-plan.js +12 -2
- package/lib/engine/mcu-info.js +134 -0
- package/lib/engine/pdf/curve.js +321 -0
- package/lib/engine/pdf/png.js +83 -0
- package/lib/engine/pdf/reader.js +336 -0
- package/lib/engine/pdf/schematic.js +93 -0
- package/lib/engine/pdf/tables.js +249 -0
- package/lib/engine/pdf/toolchain.js +50 -0
- package/lib/engine/probe.js +45 -0
- package/lib/engine/project-conf.js +93 -38
- package/lib/engine/project-layout.js +198 -0
- package/lib/engine/project-repair.js +205 -0
- package/lib/engine/schematic/checks.js +153 -0
- package/lib/engine/schematic/draw.js +390 -0
- package/lib/engine/schematic/edit.js +229 -0
- package/lib/engine/schematic/kicad-sch.js +225 -0
- package/lib/engine/schematic/model.js +442 -0
- package/lib/engine/schematic/nets.js +219 -0
- package/lib/engine/schematic/pcb.js +144 -0
- package/lib/engine/schematic/review.js +134 -0
- package/lib/engine/schematic/sexpr.js +134 -0
- package/lib/engine/schematic/to-ioc.js +197 -0
- package/lib/engine/schematic/transform.js +25 -0
- package/lib/engine/session-context.js +93 -6
- package/lib/engine/toolchain-gate.js +8 -0
- package/lib/engine/web-api.js +269 -32
- package/lib/index.js +56 -5
- package/lib/skill/stm32-workflow.js +1 -1
- package/lib/tools/build.js +10 -2
- package/lib/tools/code-patch.js +2 -2
- package/lib/tools/datasheet.js +447 -0
- package/lib/tools/debug-session.js +9 -4
- package/lib/tools/debug.js +2 -2
- package/lib/tools/doctor.js +2 -2
- package/lib/tools/ecad.js +903 -0
- package/lib/tools/flash.js +2 -2
- package/lib/tools/gen.js +166 -0
- package/lib/tools/generate.js +7 -5
- package/lib/tools/import-circuit.js +146 -0
- package/lib/tools/ioc-apply.js +2 -2
- package/lib/tools/ioc-inspect.js +2 -2
- package/lib/tools/ioc-plan.js +2 -2
- package/lib/tools/ioc-verify.js +2 -2
- package/lib/tools/layout.js +92 -0
- package/lib/tools/mcu-info.js +163 -0
- package/lib/tools/part-import.js +182 -0
- package/lib/tools/pcb.js +2316 -0
- package/lib/tools/pdf.js +423 -0
- package/lib/tools/project-dir.js +19 -1
- package/lib/tools/regs.js +2 -2
- package/lib/tools/route-plan.js +2 -2
- package/lib/tools/rtt.js +2 -2
- package/lib/tools/sch-draw.js +433 -0
- package/lib/tools/sch-edit.js +145 -0
- package/lib/tools/schematic.js +817 -0
- package/package.json +1 -1
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 立创商城的商品页解析(S119)。
|
|
3
|
+
*
|
|
4
|
+
* 只有商品详情页是稳定入口:`/datasheet/<编号>.pdf` 返回的是反爬 HTML,
|
|
5
|
+
* 真正的 PDF 在 `datasheet.lcsc.com/datasheet/pdf/<hash>.pdf`,链接写在详情页里。
|
|
6
|
+
* 因此这里做两件事:抓详情页、从页面里取「MPN / 品牌 / 正版 PDF 直链」。
|
|
7
|
+
*/
|
|
8
|
+
const PDF_URL = /(https:\/\/datasheet\.lcsc\.com\/datasheet\/pdf\/[A-Za-z0-9]+\.pdf)/u;
|
|
9
|
+
const MPN = /"mpn"\s*:\s*"([^"]{1,80})"/u;
|
|
10
|
+
const BRAND = /"brandName"\s*:\s*"([^"]{1,80})"/u;
|
|
11
|
+
const TITLE = /<title>([^<]{1,200})<\/title>/u;
|
|
12
|
+
export function lcscDetailUrl(code) {
|
|
13
|
+
return "https://www.lcsc.com/product-detail/" + encodeURIComponent(code) + ".html";
|
|
14
|
+
}
|
|
15
|
+
function firstMatch(pattern, text) {
|
|
16
|
+
const found = pattern.exec(text);
|
|
17
|
+
return found === null ? "" : (found[1] ?? "").trim();
|
|
18
|
+
}
|
|
19
|
+
/** 从详情页 HTML 里取元信息;取不到 PDF 直链时返回错误,不猜。 */
|
|
20
|
+
export function parseLcscPage(code, html, sourceUrl = lcscDetailUrl(code)) {
|
|
21
|
+
// 页面里的 JSON 会把斜杠转义成 `\/`,先统一回原样,再按同一套正则取字段。
|
|
22
|
+
const text = html.replace(/\\\//gu, "/");
|
|
23
|
+
const pdfUrl = firstMatch(PDF_URL, text);
|
|
24
|
+
if (pdfUrl === "") {
|
|
25
|
+
return { ok: false, error: "详情页里没有数据手册直链:" + sourceUrl + "(可能是页面结构变化,或该商品没有公开手册)" };
|
|
26
|
+
}
|
|
27
|
+
const title = firstMatch(TITLE, text);
|
|
28
|
+
const parts = title.split("|").map((part) => part.trim());
|
|
29
|
+
const mpn = firstMatch(MPN, text) || (parts[0] ?? "");
|
|
30
|
+
const brand = firstMatch(BRAND, text) || (parts.length >= 3 ? (parts[parts.length - 1] ?? "") : "");
|
|
31
|
+
return { ok: true, product: { code, mpn, brand, title, pdfUrl, sourceUrl } };
|
|
32
|
+
}
|
|
33
|
+
/** 抓详情页并解析。`fetchImpl` 可注入,测试不联网。 */
|
|
34
|
+
export async function fetchLcscProduct(code, options = {}) {
|
|
35
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
36
|
+
const controller = new AbortController();
|
|
37
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 20_000);
|
|
38
|
+
const signals = [controller.signal];
|
|
39
|
+
if (options.signal !== undefined)
|
|
40
|
+
signals.push(options.signal);
|
|
41
|
+
const url = lcscDetailUrl(code);
|
|
42
|
+
try {
|
|
43
|
+
const response = await fetchImpl(url, {
|
|
44
|
+
signal: signals.length === 1 ? signals[0] : AbortSignal.any(signals),
|
|
45
|
+
redirect: "follow",
|
|
46
|
+
headers: { "user-agent": "dsh-stm32 datasheet fetcher (lcsc product page)" },
|
|
47
|
+
});
|
|
48
|
+
if (!response.ok) {
|
|
49
|
+
return { ok: false, error: "商品页返回 HTTP " + String(response.status) + ":" + url };
|
|
50
|
+
}
|
|
51
|
+
return parseLcscPage(code, await response.text(), url);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
55
|
+
return { ok: false, error: "抓商品页失败:" + reason };
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { extractPdfTables } from "../pdf/reader.js";
|
|
2
|
+
const PIN_NAME = /^P[A-Z]\d{1,2}$/u;
|
|
3
|
+
const PIN_HEADER = /^(?:pin\s*(?:name|number|no\.?)?|symbol|name|引脚|引脚名)$/iu;
|
|
4
|
+
const FUNC_HEADER = /(?:alternate|additional|function|remap|复用|附加)/iu;
|
|
5
|
+
const FUNCTION_TOKEN = /^[A-Z][A-Z0-9]*(?:[_-][A-Z0-9]+)*$/u;
|
|
6
|
+
const AF_PREFIX = /^(?:AF\d+|ALT\d*)[:_\s-]*/iu;
|
|
7
|
+
/** 引脚名可能写成 "PB9-BOOT0" 或 "PA5/ADC_IN5":取第一段做名字,其余进别名。 */
|
|
8
|
+
function nameParts(value) {
|
|
9
|
+
const parts = value
|
|
10
|
+
.split(/[\s/,-]+/u)
|
|
11
|
+
.map((part) => part.replace(/[^\w]/gu, "").toUpperCase())
|
|
12
|
+
.filter((part) => part !== "");
|
|
13
|
+
return { name: parts[0] ?? "", aliases: parts.slice(1) };
|
|
14
|
+
}
|
|
15
|
+
function cleanName(value) {
|
|
16
|
+
return nameParts(value).name;
|
|
17
|
+
}
|
|
18
|
+
function tokensOfCell(cell) {
|
|
19
|
+
const out = [];
|
|
20
|
+
for (const raw of cell.split(/[\s,;/]+/u)) {
|
|
21
|
+
const token = raw.replace(AF_PREFIX, "").replace(/[^\w]/gu, "");
|
|
22
|
+
if (token === "" || token.length < 3 || token.length > 24)
|
|
23
|
+
continue;
|
|
24
|
+
if (!FUNCTION_TOKEN.test(token))
|
|
25
|
+
continue;
|
|
26
|
+
if (!/\d/u.test(token))
|
|
27
|
+
continue;
|
|
28
|
+
if (out.includes(token))
|
|
29
|
+
continue;
|
|
30
|
+
out.push(token);
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
/** 从一张表里认出「引脚列」与「功能列」,读不出就返回 null。 */
|
|
35
|
+
function readTable(table) {
|
|
36
|
+
const header = table.cells[0];
|
|
37
|
+
if (header === undefined)
|
|
38
|
+
return null;
|
|
39
|
+
let pin = -1;
|
|
40
|
+
const funcs = [];
|
|
41
|
+
header.forEach((cell, index) => {
|
|
42
|
+
if (pin < 0 && PIN_HEADER.test(cell.trim()))
|
|
43
|
+
pin = index;
|
|
44
|
+
else if (FUNC_HEADER.test(cell))
|
|
45
|
+
funcs.push(index);
|
|
46
|
+
});
|
|
47
|
+
if (pin < 0 || funcs.length === 0)
|
|
48
|
+
return null;
|
|
49
|
+
return { pin, funcs };
|
|
50
|
+
}
|
|
51
|
+
/** 把若干张表里的引脚行合并成一张「脚 → 功能」表。 */
|
|
52
|
+
export function readPinoutTables(tables) {
|
|
53
|
+
const pins = new Map();
|
|
54
|
+
const used = [];
|
|
55
|
+
for (const table of tables) {
|
|
56
|
+
const columns = readTable(table);
|
|
57
|
+
if (columns === null)
|
|
58
|
+
continue;
|
|
59
|
+
used.push({ page: table.page, title: table.title, columns: table.columns });
|
|
60
|
+
for (const row of table.cells.slice(1)) {
|
|
61
|
+
const rawName = row[columns.pin] ?? "";
|
|
62
|
+
const name = cleanName(rawName);
|
|
63
|
+
if (!PIN_NAME.test(name))
|
|
64
|
+
continue;
|
|
65
|
+
const aliases = nameParts(rawName).aliases.filter((part) => part !== name);
|
|
66
|
+
const functions = [];
|
|
67
|
+
for (const index of columns.funcs) {
|
|
68
|
+
for (const token of tokensOfCell(row[index] ?? "")) {
|
|
69
|
+
if (!functions.includes(token))
|
|
70
|
+
functions.push(token);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const existing = pins.get(name);
|
|
74
|
+
if (existing === undefined) {
|
|
75
|
+
pins.set(name, { name, aliases, functions, page: table.page, table: table.title });
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
for (const token of functions)
|
|
79
|
+
if (!existing.functions.includes(token))
|
|
80
|
+
existing.functions.push(token);
|
|
81
|
+
for (const alias of aliases)
|
|
82
|
+
if (!existing.aliases.includes(alias))
|
|
83
|
+
existing.aliases.push(alias);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const notes = [];
|
|
87
|
+
if (pins.size === 0)
|
|
88
|
+
notes.push("没有认出引脚表:需要表头含「Pin / Pin name / Symbol」与「Alternate / Additional / Function」两列");
|
|
89
|
+
const withFunctions = [...pins.values()].filter((pin) => pin.functions.length > 0).length;
|
|
90
|
+
if (pins.size > 0)
|
|
91
|
+
notes.push(pins.size + " 个引脚,其中 " + String(withFunctions) + " 个带复用功能");
|
|
92
|
+
return { ok: pins.size > 0, error: pins.size === 0 ? notes[0] ?? "" : "", pins: [...pins.values()], tables: used, notes };
|
|
93
|
+
}
|
|
94
|
+
/** 引脚名 → 功能清单,交给 sch_to_ioc 在器件库缺信号时兜底。 */
|
|
95
|
+
export function pinFunctionIndex(report) {
|
|
96
|
+
const map = new Map();
|
|
97
|
+
for (const pin of report.pins) {
|
|
98
|
+
if (pin.functions.length === 0)
|
|
99
|
+
continue;
|
|
100
|
+
map.set(pin.name, [...pin.functions]);
|
|
101
|
+
for (const alias of pin.aliases)
|
|
102
|
+
if (!map.has(alias))
|
|
103
|
+
map.set(alias, [...pin.functions]);
|
|
104
|
+
}
|
|
105
|
+
return map;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* 从缓存里的手册读引脚表。
|
|
109
|
+
*
|
|
110
|
+
* 引脚表通常在手册前部(Pinout and pin description),这里只翻前 16 页:
|
|
111
|
+
* 再往后是电气特性与封装图,翻多了慢且容易把别的表当引脚表。
|
|
112
|
+
*/
|
|
113
|
+
export async function readDatasheetPinout(subprocess, tools, file, options = {}, signal) {
|
|
114
|
+
const tables = await extractPdfTables(subprocess, tools, file, { first: options.first ?? 1, last: options.last ?? 16 }, signal);
|
|
115
|
+
if (!tables.ok)
|
|
116
|
+
return { ok: false, error: tables.error, pins: [], tables: [], notes: tables.notes };
|
|
117
|
+
const report = readPinoutTables(tables.tables);
|
|
118
|
+
return { ...report, notes: [...report.notes, ...tables.notes] };
|
|
119
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 立创商城的元件价格(S156)。
|
|
3
|
+
*
|
|
4
|
+
* 价格只出现在商品详情页的结构化数据里(`<script type="application/ld+json">` 的
|
|
5
|
+
* `Product.offers`):`price` / `priceCurrency` / `inventoryLevel`。这里把它单独缓存成
|
|
6
|
+
* `~/.dsh-stm32/prices.json`,与手册缓存分开——手册是几十 MB 的 PDF、价格是几十字节的数字,
|
|
7
|
+
* 生命周期也不一样(价格 7 天过期,手册长期有效)。
|
|
8
|
+
*
|
|
9
|
+
* 不联网也能用:BOM 先读缓存,缺价的行明确标出来,不猜价格。
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { homedir } from "node:os";
|
|
13
|
+
import { dirname, join } from "node:path";
|
|
14
|
+
import { lcscDetailUrl } from "./lcsc.js";
|
|
15
|
+
const DEFAULT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
16
|
+
const DEFAULT_GAP_MS = 800;
|
|
17
|
+
/** 价格缓存文件:`DSH_STM32_HOME/prices.json` 优先,否则 `~/.dsh-stm32/prices.json`。 */
|
|
18
|
+
export function priceCachePath(env = process.env) {
|
|
19
|
+
const home = (env["DSH_STM32_HOME"] ?? "").trim();
|
|
20
|
+
const base = home !== "" ? home : join(env["USERPROFILE"]?.trim() || homedir(), ".dsh-stm32");
|
|
21
|
+
return join(base, "prices.json");
|
|
22
|
+
}
|
|
23
|
+
export function readPriceCache(path) {
|
|
24
|
+
if (!existsSync(path))
|
|
25
|
+
return { version: 1, quotes: {} };
|
|
26
|
+
try {
|
|
27
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
28
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
29
|
+
return { version: 1, quotes: {} };
|
|
30
|
+
const quotes = parsed.quotes;
|
|
31
|
+
if (typeof quotes !== "object" || quotes === null)
|
|
32
|
+
return { version: 1, quotes: {} };
|
|
33
|
+
const out = {};
|
|
34
|
+
for (const [code, value] of Object.entries(quotes)) {
|
|
35
|
+
const quote = value;
|
|
36
|
+
if (typeof quote.priceUsd !== "number" || !Number.isFinite(quote.priceUsd))
|
|
37
|
+
continue;
|
|
38
|
+
out[code] = {
|
|
39
|
+
priceUsd: quote.priceUsd,
|
|
40
|
+
currency: typeof quote.currency === "string" ? quote.currency : "USD",
|
|
41
|
+
stock: typeof quote.stock === "number" ? quote.stock : null,
|
|
42
|
+
mpn: typeof quote.mpn === "string" ? quote.mpn : "",
|
|
43
|
+
brand: typeof quote.brand === "string" ? quote.brand : "",
|
|
44
|
+
fetchedAt: typeof quote.fetchedAt === "string" ? quote.fetchedAt : "",
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return { version: 1, quotes: out };
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return { version: 1, quotes: {} };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export function writePriceCache(path, cache) {
|
|
54
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
55
|
+
writeFileSync(path, JSON.stringify(cache, null, 2) + "\n", "utf8");
|
|
56
|
+
}
|
|
57
|
+
/** 从商品页的 JSON-LD 里取报价;拿不到数字就回 null,不按标题猜。 */
|
|
58
|
+
export function parseLcscPrice(html) {
|
|
59
|
+
const blocks = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/gu) ?? [];
|
|
60
|
+
for (const block of blocks) {
|
|
61
|
+
const json = block.replace(/^<script[^>]*>/u, "").replace(/<\/script>$/u, "");
|
|
62
|
+
let parsed;
|
|
63
|
+
try {
|
|
64
|
+
parsed = JSON.parse(json);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const product = parsed;
|
|
70
|
+
if (product["@type"] !== "Product")
|
|
71
|
+
continue;
|
|
72
|
+
const offers = product.offers;
|
|
73
|
+
const price = typeof offers?.price === "number" ? offers.price : Number(offers?.price);
|
|
74
|
+
if (!Number.isFinite(price) || price <= 0)
|
|
75
|
+
continue;
|
|
76
|
+
const brand = product.brand;
|
|
77
|
+
return {
|
|
78
|
+
priceUsd: price,
|
|
79
|
+
currency: typeof offers?.priceCurrency === "string" ? offers.priceCurrency : "USD",
|
|
80
|
+
stock: typeof offers?.inventoryLevel === "number" ? offers.inventoryLevel : null,
|
|
81
|
+
mpn: typeof product.mpn === "string" ? product.mpn : "",
|
|
82
|
+
brand: typeof brand?.name === "string" ? brand.name : "",
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
function isFresh(quote, nowMs, ttlMs) {
|
|
88
|
+
if (quote === undefined)
|
|
89
|
+
return false;
|
|
90
|
+
const at = Date.parse(quote.fetchedAt);
|
|
91
|
+
if (!Number.isFinite(at))
|
|
92
|
+
return false;
|
|
93
|
+
return nowMs - at < ttlMs;
|
|
94
|
+
}
|
|
95
|
+
async function fetchPrice(code, options) {
|
|
96
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 20_000);
|
|
99
|
+
const signals = [controller.signal];
|
|
100
|
+
if (options.signal !== undefined)
|
|
101
|
+
signals.push(options.signal);
|
|
102
|
+
try {
|
|
103
|
+
const response = await fetchImpl(lcscDetailUrl(code), {
|
|
104
|
+
signal: signals.length === 1 ? signals[0] : AbortSignal.any(signals),
|
|
105
|
+
redirect: "follow",
|
|
106
|
+
headers: { "user-agent": "dsh-stm32 bom price fetcher (lcsc product page)" },
|
|
107
|
+
});
|
|
108
|
+
if (!response.ok)
|
|
109
|
+
return null;
|
|
110
|
+
return parseLcscPrice(await response.text());
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* 取一批编号的报价:缓存里新鲜的直接用,其余按需联网。
|
|
121
|
+
*
|
|
122
|
+
* 只写成功的结果;失败的编号在返回值里列出来,不写负缓存(价格随时会变,下次还该试)。
|
|
123
|
+
*/
|
|
124
|
+
export async function ensurePrices(codes, options = {}) {
|
|
125
|
+
const path = priceCachePath(options.env);
|
|
126
|
+
const cache = readPriceCache(path);
|
|
127
|
+
const nowMs = (options.now ?? Date.now)();
|
|
128
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
129
|
+
const gapMs = options.gapMs ?? DEFAULT_GAP_MS;
|
|
130
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
131
|
+
const fetched = [];
|
|
132
|
+
const failed = [];
|
|
133
|
+
const unique = [...new Set(codes.filter((code) => code !== ""))];
|
|
134
|
+
let waited = false;
|
|
135
|
+
for (const code of unique) {
|
|
136
|
+
if (isFresh(cache.quotes[code], nowMs, ttlMs))
|
|
137
|
+
continue;
|
|
138
|
+
if (waited)
|
|
139
|
+
await sleep(gapMs);
|
|
140
|
+
waited = true;
|
|
141
|
+
const quote = await fetchPrice(code, options);
|
|
142
|
+
if (quote === null) {
|
|
143
|
+
failed.push(code);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
cache.quotes[code] = { ...quote, fetchedAt: new Date(nowMs).toISOString() };
|
|
147
|
+
fetched.push(code);
|
|
148
|
+
}
|
|
149
|
+
if (fetched.length > 0)
|
|
150
|
+
writePriceCache(path, cache);
|
|
151
|
+
return { quotes: cache.quotes, fetched, failed };
|
|
152
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 器件搜索(S163):立创的公开搜索接口。
|
|
3
|
+
*
|
|
4
|
+
* 打的是前端自己在用的那个接口(`wmsc.lcsc.com/ftps/wm/search/third`),不需要登录:
|
|
5
|
+
* 搜关键词回产品列表,含编号、型号、品牌、封装、库存、阶梯价、手册地址。
|
|
6
|
+
*
|
|
7
|
+
* 这一层只做三件事:拼请求、把回包削成稳定的形状、按查询缓存(默认 24 小时)。
|
|
8
|
+
* 「该选哪个」不在这里判断——参数、温度等级、寿命都得人看手册。
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
export const LCSC_SEARCH_URL = "https://wmsc.lcsc.com/ftps/wm/search/third";
|
|
13
|
+
export function searchCachePath(env) {
|
|
14
|
+
const home = env.DSH_STM32_HOME;
|
|
15
|
+
return home !== undefined && home !== "" ? join(home, "part-search.json") : join(process.env.USERPROFILE ?? process.env.HOME ?? ".", ".dsh-stm32", "part-search.json");
|
|
16
|
+
}
|
|
17
|
+
function readCache(file) {
|
|
18
|
+
try {
|
|
19
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
20
|
+
if (parsed.version === 1 && typeof parsed.entries === "object" && parsed.entries !== null) {
|
|
21
|
+
return { version: 1, entries: parsed.entries };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// 缓存坏了就当没有:搜索是只读操作,重下一份即可。
|
|
26
|
+
}
|
|
27
|
+
return { version: 1, entries: {} };
|
|
28
|
+
}
|
|
29
|
+
function writeCache(file, cache) {
|
|
30
|
+
try {
|
|
31
|
+
mkdirSync(join(file, ".."), { recursive: true });
|
|
32
|
+
writeFileSync(file, JSON.stringify(cache), "utf8");
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// 写不了缓存不影响搜索本身。
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function num(value) {
|
|
39
|
+
const parsed = typeof value === "number" ? value : Number(value);
|
|
40
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
41
|
+
}
|
|
42
|
+
function str(value) {
|
|
43
|
+
return typeof value === "string" ? value : "";
|
|
44
|
+
}
|
|
45
|
+
/** 把一页回包削成 `PartHit[]`;字段名跟接口走,缺的下沉成空串/0。 */
|
|
46
|
+
export function parseProductList(payload) {
|
|
47
|
+
const result = payload?.result;
|
|
48
|
+
const list = Array.isArray(result?.productList) ? result.productList : [];
|
|
49
|
+
const hits = [];
|
|
50
|
+
for (const item of list) {
|
|
51
|
+
const code = str(item["productCode"]);
|
|
52
|
+
if (!/^C\d+$/u.test(code))
|
|
53
|
+
continue;
|
|
54
|
+
const rawLadder = Array.isArray(item["productPriceList"]) ? item["productPriceList"] : [];
|
|
55
|
+
const ladder = [];
|
|
56
|
+
for (const step of rawLadder) {
|
|
57
|
+
const qty = num(step["ladder"]);
|
|
58
|
+
const priceUsd = num(step["usdPrice"]);
|
|
59
|
+
if (qty > 0 && priceUsd > 0)
|
|
60
|
+
ladder.push({ qty, priceUsd });
|
|
61
|
+
}
|
|
62
|
+
ladder.sort((a, b) => a.qty - b.qty);
|
|
63
|
+
const stock = num(item["stockNumber"]);
|
|
64
|
+
hits.push({
|
|
65
|
+
code,
|
|
66
|
+
mpn: str(item["productModel"]),
|
|
67
|
+
brand: str(item["brandNameEn"]) || str(item["lcOrderBrandNameEn"]),
|
|
68
|
+
packageName: str(item["encapStandard"]),
|
|
69
|
+
stock,
|
|
70
|
+
minBuy: num(item["minBuyNumber"]),
|
|
71
|
+
priceUsd: ladder.length > 0 ? ladder[0].priceUsd : 0,
|
|
72
|
+
ladder,
|
|
73
|
+
category: str(item["thirdWmCatalogNameEn"]) || str(item["wmCatalogNameEn"]),
|
|
74
|
+
datasheetUrl: str(item["pdfUrl"]),
|
|
75
|
+
inStock: stock > 0,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return { total: num(result?.totalCount), hits };
|
|
79
|
+
}
|
|
80
|
+
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
81
|
+
/** 搜一次;命中缓存直接回,不回网络。 */
|
|
82
|
+
export async function searchParts(query, options = {}) {
|
|
83
|
+
const keyword = query.trim();
|
|
84
|
+
const limit = Math.min(Math.max(Math.round(options.limit ?? 10), 1), 50);
|
|
85
|
+
const page = Math.max(Math.round(options.page ?? 1), 1);
|
|
86
|
+
const empty = { ok: false, error: "", query: keyword, total: 0, hits: [], cached: false, notes: [] };
|
|
87
|
+
if (keyword === "")
|
|
88
|
+
return { ...empty, error: "搜索关键词不能为空:给型号、参数或立创编号,例如 `STM32F103C8T6`、`0603 100nF`" };
|
|
89
|
+
const file = options.cacheFile ?? searchCachePath(process.env);
|
|
90
|
+
const key = String(limit) + "|" + String(page) + "|" + keyword.toLowerCase();
|
|
91
|
+
const now = options.now ?? (() => Date.now());
|
|
92
|
+
if (options.noCache !== true && existsSync(file)) {
|
|
93
|
+
const cache = readCache(file);
|
|
94
|
+
const hit = cache.entries[key];
|
|
95
|
+
if (hit !== undefined && now() - hit.at < (options.ttlMs ?? DEFAULT_TTL_MS)) {
|
|
96
|
+
return { ok: true, error: "", query: keyword, total: hit.total, hits: hit.hits, cached: true, notes: ["这一页来自本地缓存(24 小时内有效)"] };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
100
|
+
const controller = new AbortController();
|
|
101
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 20_000);
|
|
102
|
+
const onAbort = () => controller.abort();
|
|
103
|
+
options.signal?.addEventListener("abort", onAbort);
|
|
104
|
+
try {
|
|
105
|
+
const response = await fetchImpl(LCSC_SEARCH_URL, {
|
|
106
|
+
method: "POST",
|
|
107
|
+
headers: {
|
|
108
|
+
"content-type": "application/json",
|
|
109
|
+
accept: "application/json",
|
|
110
|
+
origin: "https://www.lcsc.com",
|
|
111
|
+
referer: "https://www.lcsc.com/",
|
|
112
|
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) dsh-stm32",
|
|
113
|
+
},
|
|
114
|
+
body: JSON.stringify({ keyword, currentPage: page, pageSize: limit }),
|
|
115
|
+
signal: controller.signal,
|
|
116
|
+
});
|
|
117
|
+
if (!response.ok)
|
|
118
|
+
return { ...empty, error: "立创搜索接口回了 HTTP " + String(response.status) + ":稍后再试,或换成更具体的关键词" };
|
|
119
|
+
const payload = (await response.json());
|
|
120
|
+
const code = num(payload.code);
|
|
121
|
+
if (code !== 200)
|
|
122
|
+
return { ...empty, error: "立创搜索接口回了错误码 " + String(code) + ":" + str(payload.msg) };
|
|
123
|
+
const parsed = parseProductList(payload);
|
|
124
|
+
const notes = [];
|
|
125
|
+
if (parsed.hits.length === 0)
|
|
126
|
+
notes.push("没有匹配结果:试试去掉封装或电压,只留型号主体");
|
|
127
|
+
if (parsed.total > 0)
|
|
128
|
+
notes.push("共 " + String(parsed.total) + " 条匹配,这里只给前 " + String(parsed.hits.length) + " 条");
|
|
129
|
+
const cache = readCache(file);
|
|
130
|
+
cache.entries[key] = { at: now(), total: parsed.total, hits: parsed.hits };
|
|
131
|
+
const keys = Object.keys(cache.entries);
|
|
132
|
+
if (keys.length > 200) {
|
|
133
|
+
for (const stale of keys.slice(0, keys.length - 200))
|
|
134
|
+
delete cache.entries[stale];
|
|
135
|
+
}
|
|
136
|
+
writeCache(file, cache);
|
|
137
|
+
return { ok: true, error: "", query: keyword, total: parsed.total, hits: parsed.hits, cached: false, notes };
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
141
|
+
return { ...empty, error: controller.signal.aborted ? "搜索超时或已取消:" + reason : "搜索失败:" + reason };
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
146
|
+
}
|
|
147
|
+
}
|