@cn-quickotp/k3cloud-webapi-sdk 1.0.1 → 1.0.3

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 CHANGED
@@ -100,6 +100,33 @@ const client = createClientFromEnv();
100
100
 
101
101
  可运行示例见 `examples/node-cjs/`。
102
102
 
103
+
104
+ ## AI创建新项目规范目录结构 强规范
105
+
106
+ ```
107
+ Project/
108
+ ├── command.js # CLI 入口
109
+ ├── libs/
110
+ │ ├── erp.js # 凭证加载、客户端创建、单据查询
111
+ │ ├── snapshot.js # SQLite 快照库读写
112
+ │ ├── views.js # 视图配置读写
113
+ │ ├── refresh.js # 全量刷新编排
114
+ │ ├── selfcheck.js # 恒等式与完整性自检
115
+ │ ├── inventory/
116
+ │ │ ├── constants.js # 口径常量
117
+ │ │ ├── materials.js # 物料清单
118
+ │ │ ├── masterData.js # 仓库/换算率主数据与缓存
119
+ │ │ ├── collect.js # 单项取数与分步式单据明细
120
+ │ │ ├── buildRows.js # 仓库行与合计
121
+ │ │ ├── batches.js # 批次明细
122
+ │ │ └── index.js # InventoryService
123
+ │ └── utils/ # 日志、时间
124
+ ├── scripts/ # 每个文件对应一个命令(probe / refresh / server / check)
125
+ ├── web/index.html # 单文件看板页面
126
+ └── tmps/ # 运行期产物:data/ cache/ logs/ lifecycle/
127
+ ```
128
+
129
+
103
130
  ## 许可
104
131
 
105
132
  MulanPSL-2.0
package/dist/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ var require$$0 = require('fs');
4
+ var require$$1 = require('path');
5
+
3
6
  function getDefaultExportFromCjs (x) {
4
7
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
5
8
  }
@@ -15,7 +18,7 @@ function requireVersion () {
15
18
  * SDK 版本号,与 package.json 的 version 保持一致。
16
19
  * @type {string}
17
20
  */
18
- const SDK_VERSION = '1.0.1';
21
+ const SDK_VERSION = '1.0.3';
19
22
 
20
23
  version = { SDK_VERSION };
21
24
  return version;
@@ -228,14 +231,20 @@ function requireConfig () {
228
231
  retryBaseDelay: DEFAULTS.retryBaseDelay,
229
232
  });
230
233
 
231
- /** 必填配置项 */
234
+ /** 公共必填配置项 */
235
+ const COMMON_REQUIRED_FIELDS = Object.freeze(['serverUrl', 'acctId']);
236
+
237
+ /** 账密登录凭证字段 */
238
+ const PASSWORD_FIELDS = Object.freeze(['username', 'password']);
239
+
240
+ /** 应用凭证登录字段 */
241
+ const APP_SECRET_FIELDS = Object.freeze(['appKey', 'appSec']);
242
+
243
+ /** 全部必填字段(公共项 + 两种认证方式字段的并集),仅用于缺失提示 */
232
244
  const REQUIRED_FIELDS = Object.freeze([
233
- 'serverUrl',
234
- 'acctId',
235
- 'username',
236
- 'password',
237
- 'appKey',
238
- 'appSec',
245
+ ...COMMON_REQUIRED_FIELDS,
246
+ ...PASSWORD_FIELDS,
247
+ ...APP_SECRET_FIELDS,
239
248
  ]);
240
249
 
241
250
  /** 配置来源的优先级顺序(低 → 高) */
@@ -284,18 +293,36 @@ function requireConfig () {
284
293
  }
285
294
 
286
295
  /**
287
- * 校验必填配置项,缺失时抛出 `VALIDATION` 错误并列出全部缺失字段。
296
+ * 筛选缺失的配置项。
288
297
  * @param {object} config
298
+ * @param {string[]} fields
299
+ * @returns {string[]}
289
300
  */
290
- function validateConfig(config) {
291
- const missing = REQUIRED_FIELDS.filter((field) => {
301
+ function findMissing(config, fields) {
302
+ return fields.filter((field) => {
292
303
  const value = config[field];
293
304
  return value === undefined || value === null || value === '';
294
305
  });
306
+ }
307
+
308
+ /**
309
+ * 校验必填配置项:公共项必填;账密凭证与应用凭证二选一,缺失时抛出 `VALIDATION` 错误并列出全部缺失字段。
310
+ * @param {object} config
311
+ */
312
+ function validateConfig(config) {
313
+ const missing = findMissing(config, COMMON_REQUIRED_FIELDS);
314
+ const missingPassword = findMissing(config, PASSWORD_FIELDS);
315
+ const missingAppSecret = findMissing(config, APP_SECRET_FIELDS);
316
+ if (missingPassword.length > 0 && missingAppSecret.length > 0) {
317
+ missing.push(...missingPassword, ...missingAppSecret);
318
+ }
295
319
  if (missing.length > 0) {
296
- throw new K3CloudError(ERROR_CODES.VALIDATION, `缺少必填配置项: ${missing.join(', ')}`, {
297
- missing,
298
- });
320
+ let message = `缺少必填配置项: ${missing.join(', ')}`;
321
+ if (missingPassword.length > 0 && missingAppSecret.length > 0) {
322
+ message +=
323
+ '(需满足账密登录 username + password 或应用凭证登录 appKey + appSec 之一)';
324
+ }
325
+ throw new K3CloudError(ERROR_CODES.VALIDATION, message, { missing });
299
326
  }
300
327
  }
301
328
 
@@ -329,6 +356,9 @@ function requireConfig () {
329
356
  config = {
330
357
  DEFAULT_CONFIG,
331
358
  REQUIRED_FIELDS,
359
+ COMMON_REQUIRED_FIELDS,
360
+ PASSWORD_FIELDS,
361
+ APP_SECRET_FIELDS,
332
362
  SOURCE_ORDER,
333
363
  normalizeServerUrl,
334
364
  normalizeLang,
@@ -1469,6 +1499,465 @@ function requireBill () {
1469
1499
  return bill;
1470
1500
  }
1471
1501
 
1502
+ var metadataBase;
1503
+ var hasRequiredMetadataBase;
1504
+
1505
+ function requireMetadataBase () {
1506
+ if (hasRequiredMetadataBase) return metadataBase;
1507
+ hasRequiredMetadataBase = 1;
1508
+
1509
+ const { K3CloudError, ERROR_CODES } = requireErrors();
1510
+
1511
+ /** 多语言取值的默认 LCID(简体中文) */
1512
+ const DEFAULT_LCID = 2052;
1513
+
1514
+ /**
1515
+ * 元数据基类。
1516
+ *
1517
+ * 纯内存对象:只封装原始元数据的访问、多语言取值与序列化,不触网络;
1518
+ * 网络与会话由元数据服务层(T7)负责。
1519
+ */
1520
+ class Metadata {
1521
+ /**
1522
+ * @param {object} raw 原始元数据对象(如 QueryBusinessInfo 的 NeedReturnData)
1523
+ */
1524
+ constructor(raw) {
1525
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
1526
+ throw new K3CloudError(ERROR_CODES.VALIDATION, '元数据必须由对象构造');
1527
+ }
1528
+ if (typeof raw.Id !== 'string' || raw.Id === '') {
1529
+ throw new K3CloudError(ERROR_CODES.VALIDATION, '元数据缺少 Id');
1530
+ }
1531
+ this._raw = raw;
1532
+ }
1533
+
1534
+ /** 原始元数据对象(原样引用) */
1535
+ get raw() {
1536
+ return this._raw;
1537
+ }
1538
+
1539
+ /** 元数据标识(如表单 FormId) */
1540
+ get id() {
1541
+ return this._raw.Id;
1542
+ }
1543
+
1544
+ /**
1545
+ * 返回原始元数据对象。
1546
+ * @returns {object}
1547
+ */
1548
+ toObject() {
1549
+ return this._raw;
1550
+ }
1551
+
1552
+ /**
1553
+ * JSON 序列化钩子:JSON.stringify(metadata) 输出原始元数据。
1554
+ * @returns {object}
1555
+ */
1556
+ toJSON() {
1557
+ return this._raw;
1558
+ }
1559
+
1560
+ /**
1561
+ * 多语言取值:从名称数组中取目标 LCID 的 Value。
1562
+ *
1563
+ * 登录限定 lcid(本 SDK 默认 2052)后,Name 数组仅含一项且即最终值,
1564
+ * 直接取该项;未匹配到 lcid 时兜底取第一项;空数组、非数组或缺失返回 null。
1565
+ *
1566
+ * @param {*} names 多语言名称数组,如 [{ Key: 2052, Value: '销售订单' }]
1567
+ * @param {number} [lcid] 目标 LCID,缺省 2052
1568
+ * @returns {string|null}
1569
+ */
1570
+ static text(names, lcid) {
1571
+ const target = lcid === undefined ? DEFAULT_LCID : lcid;
1572
+ if (!Array.isArray(names)) return null;
1573
+ const match = names.find((item) => item && typeof item === 'object' && item.Key === target);
1574
+ if (match && typeof match.Value === 'string') return match.Value;
1575
+ const first = names.find((item) => item && typeof item === 'object');
1576
+ if (first && typeof first.Value === 'string') return first.Value;
1577
+ return null;
1578
+ }
1579
+ }
1580
+
1581
+ metadataBase = { Metadata, DEFAULT_LCID };
1582
+ return metadataBase;
1583
+ }
1584
+
1585
+ var formMetadata;
1586
+ var hasRequiredFormMetadata;
1587
+
1588
+ function requireFormMetadata () {
1589
+ if (hasRequiredFormMetadata) return formMetadata;
1590
+ hasRequiredFormMetadata = 1;
1591
+
1592
+ const { K3CloudError, ERROR_CODES } = requireErrors();
1593
+ const { Metadata } = requireMetadataBase();
1594
+
1595
+ /** 视图实体的表名前缀:仅用于展示,不参与 Save 骨架 */
1596
+ const VIEW_TABLE_PREFIX = 'T_V_';
1597
+
1598
+ /**
1599
+ * 表单(Form)元数据子类。
1600
+ *
1601
+ * 在基类的原始数据访问之上提供结构化查询与建模辅助:
1602
+ * 实体树、字段、枚举、基础资料、操作、下推设置,以及
1603
+ * 「正向生成请求字段、反向解释返回数据」的映射工具。
1604
+ */
1605
+ class FormMetadata extends Metadata {
1606
+ /**
1607
+ * @param {object} raw 原始表单元数据(含 Id 与 Entrys 数组)
1608
+ */
1609
+ constructor(raw) {
1610
+ super(raw);
1611
+ if (!Array.isArray(raw.Entrys)) {
1612
+ throw new K3CloudError(ERROR_CODES.VALIDATION, '表单元数据缺少 Entrys 数组');
1613
+ }
1614
+ /** @type {Map<string, object>} 实体 Key → 实体对象 */
1615
+ this._entryByKey = new Map();
1616
+ /** @type {Map<string, {field: object, entry: object}>} 字段 Key → 字段与所属实体(首个同名者生效) */
1617
+ this._fieldByKey = new Map();
1618
+ for (const entry of raw.Entrys) {
1619
+ if (!entry || typeof entry !== 'object' || typeof entry.Key !== 'string') continue;
1620
+ this._entryByKey.set(entry.Key, entry);
1621
+ const fields = Array.isArray(entry.Fields) ? entry.Fields : [];
1622
+ for (const field of fields) {
1623
+ if (!field || typeof field !== 'object' || typeof field.Key !== 'string') continue;
1624
+ if (!this._fieldByKey.has(field.Key)) this._fieldByKey.set(field.Key, { field, entry });
1625
+ }
1626
+ }
1627
+ }
1628
+
1629
+ /** 原始 Entrys 数组(原样透传) */
1630
+ entrys() {
1631
+ return this._raw.Entrys;
1632
+ }
1633
+
1634
+ /** 实体摘要列表:key、name、tableName、parentKey、pkField */
1635
+ entities() {
1636
+ return this._raw.Entrys.filter((entry) => entry && typeof entry === 'object').map((entry) => ({
1637
+ key: entry.Key,
1638
+ name: Metadata.text(entry.Name),
1639
+ tableName: entry.TableName === undefined ? null : entry.TableName,
1640
+ parentKey: entry.ParentKey === undefined ? null : entry.ParentKey,
1641
+ pkField: entry.EntryPkFieldName === undefined ? null : entry.EntryPkFieldName,
1642
+ }));
1643
+ }
1644
+
1645
+ /**
1646
+ * 按实体 Key 查询实体对象。
1647
+ * @param {string} key 实体 Key(如 'FBillHead'、'FSaleOrderEntry')
1648
+ * @returns {object|null}
1649
+ */
1650
+ entity(key) {
1651
+ if (typeof key !== 'string') return null;
1652
+ const entry = this._entryByKey.get(key);
1653
+ return entry === undefined ? null : entry;
1654
+ }
1655
+
1656
+ /**
1657
+ * 原始 Fields:指定实体返回该实体的字段,缺省跨实体按顺序合并。
1658
+ * @param {string} [entityKey] 实体 Key
1659
+ * @returns {Array<object>}
1660
+ */
1661
+ fields(entityKey) {
1662
+ if (entityKey === undefined) {
1663
+ const all = [];
1664
+ for (const entry of this._raw.Entrys) {
1665
+ if (entry && Array.isArray(entry.Fields)) all.push(...entry.Fields);
1666
+ }
1667
+ return all;
1668
+ }
1669
+ return this.fieldsOf(entityKey);
1670
+ }
1671
+
1672
+ /**
1673
+ * 实体内字段列表(fields(entityKey) 的显式形式)。
1674
+ * @param {string} entityKey 实体 Key
1675
+ * @returns {Array<object>} 未命中实体返回空数组
1676
+ */
1677
+ fieldsOf(entityKey) {
1678
+ const entry = this.entity(entityKey);
1679
+ return entry && Array.isArray(entry.Fields) ? entry.Fields : [];
1680
+ }
1681
+
1682
+ /**
1683
+ * 跨实体字段查询(首个同名者生效)。
1684
+ * @param {string} fieldKey 字段 Key(如 'FBillNo')
1685
+ * @returns {object|null}
1686
+ */
1687
+ field(fieldKey) {
1688
+ if (typeof fieldKey !== 'string') return null;
1689
+ const hit = this._fieldByKey.get(fieldKey);
1690
+ return hit === undefined ? null : hit.field;
1691
+ }
1692
+
1693
+ /**
1694
+ * 原始 Extends 选项数组(下拉/枚举)。
1695
+ * @param {string} fieldKey 字段 Key
1696
+ * @returns {Array<object>|null} 无选项时返回 null
1697
+ */
1698
+ extends(fieldKey) {
1699
+ const field = this.field(fieldKey);
1700
+ const options = field && field.Extends;
1701
+ return Array.isArray(options) ? options : null;
1702
+ }
1703
+
1704
+ /**
1705
+ * 规范化枚举选项 → [{ value, caption, seq, invalid }]。
1706
+ * @param {string} fieldKey 字段 Key
1707
+ * @returns {Array<object>} 无选项时返回空数组
1708
+ */
1709
+ enums(fieldKey) {
1710
+ const options = this.extends(fieldKey);
1711
+ if (options === null) return [];
1712
+ return options
1713
+ .filter((item) => item && typeof item === 'object')
1714
+ .map((item) => ({
1715
+ value: item.Value,
1716
+ caption: item.Caption,
1717
+ seq: item.Seq,
1718
+ invalid: Boolean(item.Invalid),
1719
+ }));
1720
+ }
1721
+
1722
+ /** 字段是否为基础资料(LookUpObjectFormId 非空) */
1723
+ isLookup(fieldKey) {
1724
+ return this.lookupFormId(fieldKey) !== null;
1725
+ }
1726
+
1727
+ /** 基础资料字段指向的源表单标识;非基础资料返回 null */
1728
+ lookupFormId(fieldKey) {
1729
+ const field = this.field(fieldKey);
1730
+ const value = field && field.LookUpObjectFormId;
1731
+ return typeof value === 'string' && value !== '' ? value : null;
1732
+ }
1733
+
1734
+ /** 原始 Operations 数组(含 OperationNumber 与多语言 OperationName) */
1735
+ operations() {
1736
+ const operations = this._raw.Operations;
1737
+ return Array.isArray(operations) ? operations : [];
1738
+ }
1739
+
1740
+ /** 操作编号字符串列表,如 ['Delete', 'Draft', 'Save', ...] */
1741
+ operationNumbers() {
1742
+ return this.operations()
1743
+ .map((item) => (item && typeof item === 'object' ? item.OperationNumber : undefined))
1744
+ .filter((value) => typeof value === 'string' && value !== '');
1745
+ }
1746
+
1747
+ /** 最小必录集:MustInput=1 且 DefValue 为空的字段 Key 列表 */
1748
+ requiredFields() {
1749
+ const keys = [];
1750
+ for (const field of this.fields()) {
1751
+ if (!field || typeof field.Key !== 'string') continue;
1752
+ if (field.MustInput === 1 && (field.DefValue === undefined || field.DefValue === null || field.DefValue === '')) {
1753
+ keys.push(field.Key);
1754
+ }
1755
+ }
1756
+ return keys;
1757
+ }
1758
+
1759
+ /** 原样 LinkSet(下推关联携带设置);缺失返回 null */
1760
+ linkSet() {
1761
+ const linkSet = this._raw.LinkSet;
1762
+ return linkSet && typeof linkSet === 'object' ? linkSet : null;
1763
+ }
1764
+
1765
+ /**
1766
+ * 生成 Save 用 Model 骨架(只生成结构不填业务值)。
1767
+ *
1768
+ * 规则:普通字段 null 占位;基础资料字段 `{ FNumber: null }`;
1769
+ * 下拉字段带 DefValue;表头(FBillHead)字段平铺进 Model 根,
1770
+ * 单据体实体以 EntryName 为键生成数组,子实体(有 ParentKey)嵌套进
1771
+ * 父实体行内;视图实体(TableName 以 T_V_ 开头)不参与骨架。
1772
+ *
1773
+ * @param {string} [entryKey] 指定实体时仅生成该实体的 `{ Model: { [EntryName]: [row] } }`
1774
+ * @returns {object} `{ Model: ... }` 形态的骨架
1775
+ * @throws {K3CloudError} entryKey 未命中实体时抛 VALIDATION
1776
+ */
1777
+ toSaveModel(entryKey) {
1778
+ if (entryKey !== undefined) {
1779
+ const entry = this.entity(entryKey);
1780
+ if (!entry) {
1781
+ throw new K3CloudError(ERROR_CODES.VALIDATION, `未知实体: ${entryKey}`);
1782
+ }
1783
+ return { Model: { [this._entryName(entry)]: [this._buildRowSkeleton(entry)] } };
1784
+ }
1785
+ const model = {};
1786
+ for (const entry of this._saveEntrys()) {
1787
+ if (entry.ParentKey) continue;
1788
+ if (entry.Key === 'FBillHead') {
1789
+ Object.assign(model, this._fieldSkeletons(entry));
1790
+ } else {
1791
+ model[this._entryName(entry)] = [this._buildRowSkeleton(entry)];
1792
+ }
1793
+ }
1794
+ return { Model: model };
1795
+ }
1796
+
1797
+ /**
1798
+ * 正向:ExecuteBillQuery 的 FieldKeys 候选清单。
1799
+ * @param {string} [entityKey] 指定实体时返回该实体字段 Key;缺省跨实体去重合并
1800
+ * @returns {string[]}
1801
+ */
1802
+ toFieldKeys(entityKey) {
1803
+ if (entityKey !== undefined) return this.fieldsOf(entityKey).map((field) => field.Key);
1804
+ const keys = [];
1805
+ const seen = new Set();
1806
+ for (const field of this.fields()) {
1807
+ if (field && typeof field.Key === 'string' && !seen.has(field.Key)) {
1808
+ seen.add(field.Key);
1809
+ keys.push(field.Key);
1810
+ }
1811
+ }
1812
+ return keys;
1813
+ }
1814
+ /**
1815
+ * 正向:FieldKeys → 字段描述(所属实体、名称、类型、基础资料)。
1816
+ *
1817
+ * `Key.属性` 形态取点号前的字段 Key 查找;未命中字段 entity 为 null。
1818
+ *
1819
+ * @param {string[]} fieldKeys FieldKeys 列表
1820
+ * @returns {Array<object>} 每项含 key/entity/name/fieldType/isLookup/lookupFormId
1821
+ */
1822
+ describeFields(fieldKeys) {
1823
+ if (!Array.isArray(fieldKeys)) {
1824
+ throw new K3CloudError(ERROR_CODES.VALIDATION, 'fieldKeys 必须为数组');
1825
+ }
1826
+ return fieldKeys.map((fieldKey) => {
1827
+ const baseKey = typeof fieldKey === 'string' ? fieldKey.split('.')[0] : '';
1828
+ const hit = this._fieldByKey.get(baseKey);
1829
+ if (!hit) {
1830
+ return {
1831
+ key: fieldKey,
1832
+ entity: null,
1833
+ name: null,
1834
+ fieldType: null,
1835
+ isLookup: false,
1836
+ lookupFormId: null,
1837
+ };
1838
+ }
1839
+ const field = hit.field;
1840
+ return {
1841
+ key: fieldKey,
1842
+ entity: hit.entry ? hit.entry.Key : null,
1843
+ name: Metadata.text(field.Name),
1844
+ fieldType: field.FieldType === undefined || field.FieldType === null ? null : field.FieldType,
1845
+ isLookup: this.isLookup(baseKey),
1846
+ lookupFormId: this.lookupFormId(baseKey),
1847
+ };
1848
+ });
1849
+ }
1850
+
1851
+ /**
1852
+ * 反向:按 fieldKeys 顺序把 ExecuteBillQuery 返回的行数组折叠为对象数组。
1853
+ *
1854
+ * 键为 FieldKey 原文(含 `FMaterialId.FNumber` 点路径形态,不拆解);
1855
+ * 越界取 null。rows 为空或非数组返回 []。
1856
+ *
1857
+ * @param {string[]} fieldKeys 与行元素一一对应的 FieldKeys
1858
+ * @param {Array<Array<*>>} rows 行数组
1859
+ * @returns {Array<object>}
1860
+ */
1861
+ mapRows(fieldKeys, rows) {
1862
+ if (!Array.isArray(fieldKeys)) {
1863
+ throw new K3CloudError(ERROR_CODES.VALIDATION, 'fieldKeys 必须为数组');
1864
+ }
1865
+ if (!Array.isArray(rows)) return [];
1866
+ return rows.map((row) => {
1867
+ const record = {};
1868
+ const values = Array.isArray(row) ? row : [];
1869
+ fieldKeys.forEach((key, index) => {
1870
+ record[key] = values[index] === undefined ? null : values[index];
1871
+ });
1872
+ return record;
1873
+ });
1874
+ }
1875
+
1876
+ /**
1877
+ * 反向:依据字段 EntityKey 把 View 返回的扁平对象拆分到各实体。
1878
+ *
1879
+ * 表头(FBillHead)字段归入 FBillHead 对象;实体键(如 FSaleOrderEntry)
1880
+ * 的值保留其原生形状(单据体为数组);无法归属实体的键保留在结果顶层。
1881
+ * data 为空或非对象返回 null。
1882
+ *
1883
+ * @param {*} data View 返回的扁平单据对象
1884
+ * @returns {object|null}
1885
+ */
1886
+ mapViewData(data) {
1887
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null;
1888
+ const grouped = new Map();
1889
+ const passthrough = {};
1890
+ for (const [key, value] of Object.entries(data)) {
1891
+ const hit = this._fieldByKey.get(key);
1892
+ if (hit && hit.entry && !this._entryByKey.has(key)) {
1893
+ const entityKey = hit.entry.Key;
1894
+ if (!grouped.has(entityKey)) {
1895
+ grouped.set(entityKey, Array.isArray(value) ? [] : {});
1896
+ }
1897
+ const bucket = grouped.get(entityKey);
1898
+ if (Array.isArray(bucket)) bucket.push(value);
1899
+ else bucket[key] = value;
1900
+ } else {
1901
+ passthrough[key] = value;
1902
+ }
1903
+ }
1904
+ return Object.assign({}, passthrough, Object.fromEntries(grouped));
1905
+ }
1906
+ /** 参与保存骨架的实体:结构完整且非视图表(TableName 不以 T_V_ 开头) */
1907
+ _saveEntrys() {
1908
+ return this._raw.Entrys.filter(
1909
+ (entry) =>
1910
+ entry &&
1911
+ typeof entry === 'object' &&
1912
+ typeof entry.Key === 'string' &&
1913
+ !(typeof entry.TableName === 'string' && entry.TableName.toUpperCase().startsWith(VIEW_TABLE_PREFIX)),
1914
+ );
1915
+ }
1916
+
1917
+ /** ParentKey 指向 parentKey 的子实体(仅参与保存的实体) */
1918
+ _childEntrysOf(parentKey) {
1919
+ return this._saveEntrys().filter((entry) => entry.ParentKey === parentKey);
1920
+ }
1921
+
1922
+ /** 实体在 Model 中的键名:优先 EntryName,缺省用实体 Key */
1923
+ _entryName(entry) {
1924
+ return typeof entry.EntryName === 'string' && entry.EntryName !== '' ? entry.EntryName : entry.Key;
1925
+ }
1926
+
1927
+ /** 实体全部字段的骨架值映射 */
1928
+ _fieldSkeletons(entry) {
1929
+ const out = {};
1930
+ for (const field of Array.isArray(entry.Fields) ? entry.Fields : []) {
1931
+ if (!field || typeof field.Key !== 'string') continue;
1932
+ out[field.Key] = this._skeletonValue(field);
1933
+ }
1934
+ return out;
1935
+ }
1936
+
1937
+ /** 单字段骨架值:基础资料 { FNumber: null };下拉带 DefValue;其余 null */
1938
+ _skeletonValue(field) {
1939
+ const lookupId = field.LookUpObjectFormId;
1940
+ if (typeof lookupId === 'string' && lookupId !== '') return { FNumber: null };
1941
+ if (Array.isArray(field.Extends) && field.Extends.length > 0) {
1942
+ return field.DefValue === undefined || field.DefValue === null ? null : field.DefValue;
1943
+ }
1944
+ return null;
1945
+ }
1946
+
1947
+ /** 单行骨架:实体字段 + 子实体数组嵌套 */
1948
+ _buildRowSkeleton(entry) {
1949
+ const row = this._fieldSkeletons(entry);
1950
+ for (const child of this._childEntrysOf(entry.Key)) {
1951
+ row[this._entryName(child)] = [this._buildRowSkeleton(child)];
1952
+ }
1953
+ return row;
1954
+ }
1955
+ }
1956
+
1957
+ formMetadata = { FormMetadata, VIEW_TABLE_PREFIX };
1958
+ return formMetadata;
1959
+ }
1960
+
1472
1961
  var metadata;
1473
1962
  var hasRequiredMetadata;
1474
1963
 
@@ -1478,6 +1967,7 @@ function requireMetadata () {
1478
1967
 
1479
1968
  const { SERVICES, METHODS, buildEndpoint } = requireConstants();
1480
1969
  const { K3CloudError, ERROR_CODES } = requireErrors();
1970
+ const { FormMetadata } = requireFormMetadata();
1481
1971
 
1482
1972
  /** 元数据服务 endpoint */
1483
1973
  const METADATA_ENDPOINTS = Object.freeze({
@@ -1537,8 +2027,10 @@ function requireMetadata () {
1537
2027
  const parseResponse =
1538
2028
  typeof opts.parseResponse === 'function' ? opts.parseResponse : defaultParseMetadata;
1539
2029
  const cacheEnabled = opts.cache !== false;
1540
- /** 实例内缓存:formId -> 查询 Promise */
2030
+ /** 实例内缓存:formId -> 查询 Promise(原始对象,T7 语义) */
1541
2031
  const cache = new Map();
2032
+ /** 实例内缓存:formId -> FormMetadata Promise(与原始对象缓存隔离) */
2033
+ const formCache = new Map();
1542
2034
 
1543
2035
  if (typeof transport !== 'function') {
1544
2036
  throw new K3CloudError(ERROR_CODES.VALIDATION, '元数据服务需要注入传输层');
@@ -1564,7 +2056,7 @@ function requireMetadata () {
1564
2056
  }
1565
2057
 
1566
2058
  /**
1567
- * 查询单据元数据。
2059
+ * 查询单据元数据(原始对象)。
1568
2060
  * @param {string} formId 单据标识
1569
2061
  * @param {object} [options] 调用选项
1570
2062
  * @param {boolean} [options.cache] 为 `false` 时跳过实例内缓存
@@ -1580,7 +2072,23 @@ function requireMetadata () {
1580
2072
  return pending;
1581
2073
  }
1582
2074
 
1583
- return { queryBusinessInfo };
2075
+ /**
2076
+ * 查询表单元数据并对象化为 `FormMetadata`(独立实例内缓存)。
2077
+ * @param {string} formId 单据标识
2078
+ * @param {object} [options] 调用选项,`cache: false` 语义与 `queryBusinessInfo` 一致
2079
+ * @returns {Promise<FormMetadata>}
2080
+ */
2081
+ function getFormMetadata(formId, options) {
2082
+ const useCache = cacheEnabled && !(options && options.cache === false);
2083
+ if (useCache && formCache.has(formId)) return formCache.get(formId);
2084
+ const pending = request(formId).then((raw) => new FormMetadata(raw));
2085
+ if (!useCache) return pending;
2086
+ formCache.set(formId, pending);
2087
+ pending.catch(() => formCache.delete(formId));
2088
+ return pending;
2089
+ }
2090
+
2091
+ return { queryBusinessInfo, getFormMetadata };
1584
2092
  }
1585
2093
 
1586
2094
  metadata = {
@@ -1615,8 +2123,12 @@ function requireClient () {
1615
2123
 
1616
2124
  /**
1617
2125
  * 从原始响应提取小写键名的响应头。
2126
+ *
2127
+ * fetch 的 `Headers` 迭代会把多条 `Set-Cookie` 用 `", "` 拼成一个字符串,
2128
+ * 这里优先经 `getSetCookie()` 取回按条分离的数组,保证登录层
2129
+ * 「取 `set-cookie[0]` 原样回传」的语义与 axios 等客户端一致。
1618
2130
  * @param {object} raw 原始响应
1619
- * @returns {Object<string, string>}
2131
+ * @returns {Object<string, string|string[]>}
1620
2132
  */
1621
2133
  function extractHeaders(raw) {
1622
2134
  if (!raw || !raw.headers) return {};
@@ -1626,6 +2138,10 @@ function requireClient () {
1626
2138
  headers.forEach((value, key) => {
1627
2139
  result[key] = typeof value === 'string' ? value : String(value);
1628
2140
  });
2141
+ if (typeof headers.getSetCookie === 'function') {
2142
+ const cookies = headers.getSetCookie();
2143
+ if (cookies.length > 0) result['set-cookie'] = cookies;
2144
+ }
1629
2145
  return result;
1630
2146
  }
1631
2147
  return { ...headers };
@@ -1730,6 +2246,73 @@ function requireClient () {
1730
2246
  return client;
1731
2247
  }
1732
2248
 
2249
+ var envLoader;
2250
+ var hasRequiredEnvLoader;
2251
+
2252
+ function requireEnvLoader () {
2253
+ if (hasRequiredEnvLoader) return envLoader;
2254
+ hasRequiredEnvLoader = 1;
2255
+
2256
+ const fs = require$$0;
2257
+ const path = require$$1;
2258
+
2259
+ const { fromEnvVars } = requireConfig();
2260
+
2261
+ /** `.env` 文件名 */
2262
+ const ENV_FILE_NAME = '.env';
2263
+
2264
+ /**
2265
+ * 解析 `.env` 文本为键值对。
2266
+ *
2267
+ * 支持 `KEY=VALUE`、双引号包裹值、`#` 注释行与空行。
2268
+ * @param {string} text
2269
+ * @returns {Object<string, string>}
2270
+ */
2271
+ function parseEnv(text) {
2272
+ const result = {};
2273
+ for (const rawLine of String(text).split(/\r?\n/)) {
2274
+ const line = rawLine.trim();
2275
+ if (line === '' || line.startsWith('#')) continue;
2276
+ const eq = line.indexOf('=');
2277
+ if (eq === -1) continue;
2278
+ const key = line.slice(0, eq).trim();
2279
+ if (key === '') continue;
2280
+ let value = line.slice(eq + 1).trim();
2281
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
2282
+ value = value.slice(1, -1);
2283
+ }
2284
+ result[key] = value;
2285
+ }
2286
+ return result;
2287
+ }
2288
+
2289
+ /**
2290
+ * 读取目录下的 `.env` 并写入目标对象,默认不覆盖已存在的键。
2291
+ * @param {string} [dir] 默认为当前工作目录
2292
+ * @param {{ target?: Object<string, string>, override?: boolean }} [options]
2293
+ * @returns {Object<string, string>} 目标对象
2294
+ */
2295
+ function loadEnvFile(dir = process.cwd(), options = {}) {
2296
+ const target = options.target === undefined ? process.env : options.target;
2297
+ const override = options.override === true;
2298
+ let text;
2299
+ try {
2300
+ text = fs.readFileSync(path.join(dir, ENV_FILE_NAME), 'utf8');
2301
+ } catch (err) {
2302
+ if (err && err.code === 'ENOENT') return target;
2303
+ throw err;
2304
+ }
2305
+ const parsed = parseEnv(text);
2306
+ for (const [key, value] of Object.entries(parsed)) {
2307
+ if (override || target[key] === undefined) target[key] = value;
2308
+ }
2309
+ return target;
2310
+ }
2311
+
2312
+ envLoader = { ENV_FILE_NAME, parseEnv, loadEnvFile, fromEnvVars };
2313
+ return envLoader;
2314
+ }
2315
+
1733
2316
  var src;
1734
2317
  var hasRequiredSrc;
1735
2318
 
@@ -1738,10 +2321,28 @@ function requireSrc () {
1738
2321
  hasRequiredSrc = 1;
1739
2322
 
1740
2323
  const { SDK_VERSION } = requireVersion();
1741
- const { K3CloudError } = requireErrors();
2324
+ const { K3CloudError, ERROR_CODES } = requireErrors();
1742
2325
  const { createClient, createClientFromEnv } = requireClient();
1743
-
1744
- src = { SDK_VERSION, K3CloudError, createClient, createClientFromEnv };
2326
+ const { ENV_FILE_NAME, parseEnv, loadEnvFile } = requireEnvLoader();
2327
+ const { LOG_LEVELS, nullLogger, createLogger } = requireLogger();
2328
+ const { Metadata } = requireMetadataBase();
2329
+ const { FormMetadata } = requireFormMetadata();
2330
+
2331
+ src = {
2332
+ SDK_VERSION,
2333
+ K3CloudError,
2334
+ ERROR_CODES,
2335
+ createClient,
2336
+ createClientFromEnv,
2337
+ ENV_FILE_NAME,
2338
+ parseEnv,
2339
+ loadEnvFile,
2340
+ LOG_LEVELS,
2341
+ nullLogger,
2342
+ createLogger,
2343
+ Metadata,
2344
+ FormMetadata,
2345
+ };
1745
2346
  return src;
1746
2347
  }
1747
2348
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cn-quickotp/k3cloud-webapi-sdk",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Kingdee K3Cloud (金蝶云星空) WebAPI SDK for JavaScript — CommonJS, zero-framework core.",
5
5
  "main": "dist/index.js",
6
6
  "types": "types/index.d.ts",
package/types/index.d.ts CHANGED
@@ -63,6 +63,7 @@ export interface BillService {
63
63
 
64
64
  export interface MetadataService {
65
65
  queryBusinessInfo(formId: string, options?: { cache?: boolean }): Promise<object>;
66
+ getFormMetadata(formId: string, options?: { cache?: boolean }): Promise<FormMetadata>;
66
67
  }
67
68
 
68
69
  export interface SessionState {
@@ -97,3 +98,74 @@ export declare class K3CloudError extends Error {
97
98
  export declare function createClient(config?: ClientConfig): K3CloudClient;
98
99
 
99
100
  export declare function createClientFromEnv(env?: Record<string, string>): K3CloudClient;
101
+
102
+ export declare const ENV_FILE_NAME: string;
103
+
104
+ export declare function parseEnv(text: string): Record<string, string>;
105
+
106
+ export declare function loadEnvFile(
107
+ dir?: string,
108
+ options?: { target?: Record<string, string>; override?: boolean },
109
+ ): Record<string, string>;
110
+
111
+ export declare const ERROR_CODES: Readonly<Record<string, string>>;
112
+
113
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
114
+
115
+ export declare const LOG_LEVELS: readonly LogLevel[];
116
+
117
+ export declare const nullLogger: Readonly<Record<LogLevel, (record: Record<string, unknown>) => void>>;
118
+
119
+ export declare function createLogger(sink?: object): Readonly<Record<LogLevel, (record: Record<string, unknown>) => void>>;
120
+
121
+ export declare class Metadata {
122
+ constructor(raw: Record<string, unknown>);
123
+ get raw(): Record<string, unknown>;
124
+ get id(): string;
125
+ toObject(): Record<string, unknown>;
126
+ toJSON(): Record<string, unknown>;
127
+ static text(
128
+ names: Array<{ Key: number; Value: string }> | null | undefined,
129
+ lcid?: number,
130
+ ): string | null;
131
+ }
132
+
133
+ export declare class FormMetadata extends Metadata {
134
+ entrys(): Array<Record<string, unknown>>;
135
+ entities(): Array<{
136
+ key: string;
137
+ name: string | null;
138
+ tableName: string | null;
139
+ parentKey: string | null;
140
+ pkField: string | null;
141
+ }>;
142
+ entity(key: string): Record<string, unknown> | null;
143
+ fields(entityKey?: string): Array<Record<string, unknown>>;
144
+ fieldsOf(entityKey: string): Array<Record<string, unknown>>;
145
+ field(fieldKey: string): Record<string, unknown> | null;
146
+ extends(fieldKey: string): Array<Record<string, unknown>> | null;
147
+ enums(fieldKey: string): Array<{
148
+ value: unknown;
149
+ caption: unknown;
150
+ seq: unknown;
151
+ invalid: boolean;
152
+ }>;
153
+ isLookup(fieldKey: string): boolean;
154
+ lookupFormId(fieldKey: string): string | null;
155
+ operations(): Array<Record<string, unknown>>;
156
+ operationNumbers(): string[];
157
+ requiredFields(): string[];
158
+ linkSet(): Record<string, unknown> | null;
159
+ toSaveModel(entryKey?: string): Record<string, unknown>;
160
+ toFieldKeys(entityKey?: string): string[];
161
+ describeFields(fieldKeys: string[]): Array<{
162
+ key: string;
163
+ entity: string | null;
164
+ name: string | null;
165
+ fieldType: unknown;
166
+ isLookup: boolean;
167
+ lookupFormId: string | null;
168
+ }>;
169
+ mapRows(fieldKeys: string[], rows: unknown[][]): Array<Record<string, unknown>>;
170
+ mapViewData(data: object | null | undefined): Record<string, unknown> | null;
171
+ }