@devicechain/widgets 1.5.0 → 1.6.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 (113) hide show
  1. package/README.md +14 -1
  2. package/dist/access-strings.d.ts +1 -1
  3. package/dist/aggregate-strings.d.ts +3 -1
  4. package/dist/alarm-strings.d.ts +4 -1
  5. package/dist/chunks/{aggregate-feed-HCF5FYIJ.js → aggregate-feed-QJRO7Y4V.js} +7 -4
  6. package/dist/chunks/aggregate-feed-QJRO7Y4V.js.map +7 -0
  7. package/dist/chunks/{aggregate-widgets-IFZUFYXV.js → aggregate-widgets-SHPHUHNL.js} +39 -62
  8. package/dist/chunks/aggregate-widgets-SHPHUHNL.js.map +7 -0
  9. package/dist/chunks/{alarm-widgets-TTQYBKMZ.js → alarm-widgets-DQEITFVN.js} +2 -2
  10. package/dist/chunks/alarm-widgets-DQEITFVN.js.map +7 -0
  11. package/dist/chunks/{chunk-FM7OI5TQ.js → chunk-2GMBZTQD.js} +44 -5
  12. package/dist/chunks/chunk-2GMBZTQD.js.map +7 -0
  13. package/dist/chunks/{chunk-AF4M5OXQ.js → chunk-4BEFYYM3.js} +3 -3
  14. package/dist/chunks/chunk-5UDZ5R5F.js +60 -0
  15. package/dist/chunks/chunk-5UDZ5R5F.js.map +7 -0
  16. package/dist/chunks/{chunk-VTGKDO44.js → chunk-7TEFJ64H.js} +19 -5
  17. package/dist/chunks/chunk-7TEFJ64H.js.map +7 -0
  18. package/dist/chunks/{chunk-GUCEPNGM.js → chunk-EFTUK5YX.js} +1 -1
  19. package/dist/chunks/chunk-EFTUK5YX.js.map +7 -0
  20. package/dist/chunks/{chunk-EQOWBDS7.js → chunk-G5UBMPMX.js} +2 -2
  21. package/dist/chunks/{chunk-EQOWBDS7.js.map → chunk-G5UBMPMX.js.map} +2 -2
  22. package/dist/chunks/{chunk-RG2AYYKO.js → chunk-GWH5AHG3.js} +6 -4
  23. package/dist/chunks/chunk-GWH5AHG3.js.map +7 -0
  24. package/dist/chunks/{chunk-XJ7UF2CP.js → chunk-O763YMOG.js} +1 -1
  25. package/dist/chunks/chunk-O763YMOG.js.map +7 -0
  26. package/dist/chunks/{chunk-ZX4K3GT5.js → chunk-R2XEYQEJ.js} +45 -24
  27. package/dist/chunks/chunk-R2XEYQEJ.js.map +7 -0
  28. package/dist/chunks/{chunk-JVC6JYUR.js → chunk-RLVZXNPJ.js} +1 -1
  29. package/dist/chunks/{chunk-JVC6JYUR.js.map → chunk-RLVZXNPJ.js.map} +1 -1
  30. package/dist/chunks/{chunk-QHTO5ZEM.js → chunk-UDQVBVXJ.js} +1 -1
  31. package/dist/chunks/chunk-UDQVBVXJ.js.map +7 -0
  32. package/dist/chunks/chunk-UVLEBGAC.js +17 -0
  33. package/dist/chunks/chunk-UVLEBGAC.js.map +7 -0
  34. package/dist/chunks/chunk-VR6643C7.js +119 -0
  35. package/dist/chunks/chunk-VR6643C7.js.map +7 -0
  36. package/dist/chunks/{chunk-ZR74ORIT.js → chunk-XDHKONWK.js} +1 -1
  37. package/dist/chunks/chunk-XDHKONWK.js.map +7 -0
  38. package/dist/chunks/{chunk-3FSXS67N.js → chunk-ZKR5WDF5.js} +68 -18
  39. package/dist/chunks/chunk-ZKR5WDF5.js.map +7 -0
  40. package/dist/chunks/{compare-feed-MLHG7YFN.js → compare-feed-K46QVE5D.js} +28 -16
  41. package/dist/chunks/compare-feed-K46QVE5D.js.map +7 -0
  42. package/dist/chunks/{control-widgets-KTH6BWMH.js → control-widgets-VMWBTRC6.js} +70 -34
  43. package/dist/chunks/control-widgets-VMWBTRC6.js.map +7 -0
  44. package/dist/chunks/entity-selector-IRUFUDQ6.js +7 -0
  45. package/dist/chunks/{event-markers-feed-BQO4T367.js → event-markers-feed-TOAQ53YC.js} +29 -11
  46. package/dist/chunks/event-markers-feed-TOAQ53YC.js.map +7 -0
  47. package/dist/chunks/{export-rows-OEWIBIUY.js → export-rows-XKIVLOM3.js} +3 -3
  48. package/dist/chunks/{fleet-feed-AKJ7QIMP.js → fleet-feed-AYNL3CC2.js} +6 -6
  49. package/dist/chunks/{history-widgets-7GNKTE5X.js → history-widgets-WJ4KRTG7.js} +55 -20
  50. package/dist/chunks/history-widgets-WJ4KRTG7.js.map +7 -0
  51. package/dist/chunks/{level-widgets-DKCQT2XF.js → level-widgets-3SRESJYW.js} +46 -14
  52. package/dist/chunks/level-widgets-3SRESJYW.js.map +7 -0
  53. package/dist/chunks/{natural-earth-data-VMKQ6LY3.js → natural-earth-data-R7NPQARR.js} +1 -1
  54. package/dist/chunks/natural-earth-data-R7NPQARR.js.map +7 -0
  55. package/dist/chunks/{no-reading-B4MPXAS2.js → no-reading-CTQCMNYA.js} +4 -4
  56. package/dist/chunks/{presence-widgets-7OGANOLB.js → presence-widgets-P2H3A2SD.js} +34 -16
  57. package/dist/chunks/presence-widgets-P2H3A2SD.js.map +7 -0
  58. package/dist/chunks/table-HAKFOUMS.js +8 -0
  59. package/dist/command-control-strings.d.ts +1 -1
  60. package/dist/compare-strings.d.ts +1 -1
  61. package/dist/event-markers-strings.d.ts +1 -1
  62. package/dist/fleet-strings.d.ts +1 -1
  63. package/dist/history-strings.d.ts +1 -1
  64. package/dist/host-context.js +1 -1
  65. package/dist/index.d.ts +112 -4
  66. package/dist/index.js +338 -131
  67. package/dist/index.js.map +4 -4
  68. package/dist/level-strings.d.ts +1 -1
  69. package/dist/presence-strings.d.ts +1 -1
  70. package/dist/registry.d.ts +2 -0
  71. package/dist/scada-strings.d.ts +1 -1
  72. package/dist/selection-strings.d.ts +10 -0
  73. package/dist/shared-strings.d.ts +38 -0
  74. package/dist/state-timeline-strings.d.ts +1 -1
  75. package/dist/status-grid-strings.d.ts +1 -1
  76. package/dist/table-strings.d.ts +1 -1
  77. package/dist/time-range-bar.d.ts +1 -2
  78. package/dist/time-range-strings.d.ts +8 -0
  79. package/dist/vite.js.map +1 -1
  80. package/dist/widgets/command-status.d.ts +1 -0
  81. package/dist/widgets/map-geometry.d.ts +2 -0
  82. package/package.json +8 -8
  83. package/dist/chunks/aggregate-feed-HCF5FYIJ.js.map +0 -7
  84. package/dist/chunks/aggregate-widgets-IFZUFYXV.js.map +0 -7
  85. package/dist/chunks/alarm-widgets-TTQYBKMZ.js.map +0 -7
  86. package/dist/chunks/chunk-3FSXS67N.js.map +0 -7
  87. package/dist/chunks/chunk-BRH66T5F.js +0 -15
  88. package/dist/chunks/chunk-BRH66T5F.js.map +0 -7
  89. package/dist/chunks/chunk-FM7OI5TQ.js.map +0 -7
  90. package/dist/chunks/chunk-GUCEPNGM.js.map +0 -7
  91. package/dist/chunks/chunk-QHTO5ZEM.js.map +0 -7
  92. package/dist/chunks/chunk-QMGKB6J3.js +0 -84
  93. package/dist/chunks/chunk-QMGKB6J3.js.map +0 -7
  94. package/dist/chunks/chunk-RG2AYYKO.js.map +0 -7
  95. package/dist/chunks/chunk-VTGKDO44.js.map +0 -7
  96. package/dist/chunks/chunk-XJ7UF2CP.js.map +0 -7
  97. package/dist/chunks/chunk-ZR74ORIT.js.map +0 -7
  98. package/dist/chunks/chunk-ZX4K3GT5.js.map +0 -7
  99. package/dist/chunks/compare-feed-MLHG7YFN.js.map +0 -7
  100. package/dist/chunks/control-widgets-KTH6BWMH.js.map +0 -7
  101. package/dist/chunks/entity-selector-3JJFI4DT.js +0 -7
  102. package/dist/chunks/event-markers-feed-BQO4T367.js.map +0 -7
  103. package/dist/chunks/history-widgets-7GNKTE5X.js.map +0 -7
  104. package/dist/chunks/level-widgets-DKCQT2XF.js.map +0 -7
  105. package/dist/chunks/natural-earth-data-VMKQ6LY3.js.map +0 -7
  106. package/dist/chunks/presence-widgets-7OGANOLB.js.map +0 -7
  107. package/dist/chunks/table-2UGM2Q4H.js +0 -8
  108. /package/dist/chunks/{chunk-AF4M5OXQ.js.map → chunk-4BEFYYM3.js.map} +0 -0
  109. /package/dist/chunks/{entity-selector-3JJFI4DT.js.map → entity-selector-IRUFUDQ6.js.map} +0 -0
  110. /package/dist/chunks/{export-rows-OEWIBIUY.js.map → export-rows-XKIVLOM3.js.map} +0 -0
  111. /package/dist/chunks/{fleet-feed-AKJ7QIMP.js.map → fleet-feed-AYNL3CC2.js.map} +0 -0
  112. /package/dist/chunks/{no-reading-B4MPXAS2.js.map → no-reading-CTQCMNYA.js.map} +0 -0
  113. /package/dist/chunks/{table-2UGM2Q4H.js.map → table-HAKFOUMS.js.map} +0 -0
@@ -2,7 +2,7 @@ import {
2
2
  bucketLabel,
3
3
  roundTo,
4
4
  stamp
5
- } from "./chunk-XJ7UF2CP.js";
5
+ } from "./chunk-O763YMOG.js";
6
6
  import {
7
7
  cellFor,
8
8
  deviceLabel,
@@ -28,7 +28,7 @@ var WORDS = {
28
28
  },
29
29
  es: {
30
30
  time: "Hora (UTC)",
31
- measurement: "Medici\xF3n",
31
+ measurement: "Medición",
32
32
  series: "Serie",
33
33
  value: "Valor",
34
34
  basis: "Base",
@@ -37,11 +37,25 @@ var WORDS = {
37
37
  device: "Dispositivo",
38
38
  deviceToken: "Token del dispositivo",
39
39
  readingTime: "hora de la lectura (UTC)",
40
- latest: "\xFAltima"
40
+ latest: "última"
41
+ },
42
+ "zh-CN": {
43
+ time: "时间(UTC)",
44
+ measurement: "测量项",
45
+ series: "序列",
46
+ value: "值",
47
+ basis: "数据依据",
48
+ reading: "读数",
49
+ average: (bucket) => `每 ${bucket} 的平均值`,
50
+ device: "设备",
51
+ deviceToken: "设备标识",
52
+ readingTime: "读数时间(UTC)",
53
+ latest: "最新值"
41
54
  }
42
55
  };
43
56
  function words() {
44
- return viewerLocale()?.toLowerCase().startsWith("es") ? WORDS.es : WORDS.en;
57
+ const language = viewerLocale()?.toLowerCase().split("-")[0];
58
+ return language === "es" ? WORDS.es : language === "zh" ? WORDS["zh-CN"] : WORDS.en;
45
59
  }
46
60
  function isoOrEmpty(value) {
47
61
  if (!value) return "";
@@ -84,4 +98,4 @@ export {
84
98
  samplesExport,
85
99
  fleetExport
86
100
  };
87
- //# sourceMappingURL=chunk-VTGKDO44.js.map
101
+ //# sourceMappingURL=chunk-7TEFJ64H.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/export-rows.ts"],
4
+ "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The tables the chart and the fleet table hand their frame to export (the frame's \"Download CSV\"):\n// built from the state the widget is rendering, at the moment the viewer asks. The history table's own\n// is in history-model.ts. Loaded on demand (the chart reaches this through a dynamic import), so none\n// of it is part of a board's first download.\n//\n// 🔴 AN EXPORT IS WHAT THE WIDGET SHOWS. It holds the samples on screen, not a new question to the\n// store, and its file name says which span they cover and what they are: \"avg per 1m\" for a point that\n// is a stored bucket's average, \"readings\" for one that arrived live. The two are told apart by the\n// sample itself (`bucketSeconds`), never guessed.\n\nimport { spanLabel, type FleetMember, type MeasurementSample } from '@devicechain/dashboards';\nimport { viewerLocale, type WidgetExportCell, type WidgetExportTable } from '@devicechain/widget-sdk';\n\nimport { cellFor, deviceLabel, sortMembers, type SortKey } from './fleet-model';\nimport { bucketLabel, roundTo, stamp } from './history-model';\n\ninterface ExportWords {\n time: string;\n measurement: string;\n series: string;\n value: string;\n basis: string;\n reading: string;\n average: (bucket: string) => string;\n device: string;\n deviceToken: string;\n readingTime: string;\n latest: string;\n}\n\nconst WORDS: Record<'en' | 'es' | 'zh-CN', ExportWords> = {\n en: {\n time: 'Time (UTC)',\n measurement: 'Measurement',\n series: 'Series',\n value: 'Value',\n basis: 'Basis',\n reading: 'reading',\n average: (bucket) => `avg per ${bucket}`,\n device: 'Device',\n deviceToken: 'Device token',\n readingTime: 'reading time (UTC)',\n latest: 'latest',\n },\n es: {\n time: 'Hora (UTC)',\n measurement: 'Medición',\n series: 'Serie',\n value: 'Valor',\n basis: 'Base',\n reading: 'lectura',\n average: (bucket) => `prom. por ${bucket}`,\n device: 'Dispositivo',\n deviceToken: 'Token del dispositivo',\n readingTime: 'hora de la lectura (UTC)',\n latest: 'última',\n },\n 'zh-CN': {\n time: '时间(UTC)', measurement: '测量项', series: '序列', value: '值', basis: '数据依据', reading: '读数',\n average: (bucket) => `每 ${bucket} 的平均值`, device: '设备', deviceToken: '设备标识', readingTime: '读数时间(UTC)', latest: '最新值',\n },\n};\n\nfunction words(): ExportWords {\n const language = viewerLocale()?.toLowerCase().split('-')[0];\n return language === 'es' ? WORDS.es : language === 'zh' ? WORDS['zh-CN'] : WORDS.en;\n}\n\nfunction isoOrEmpty(value: string | null): string {\n if (!value) return '';\n const at = Date.parse(value);\n return Number.isNaN(at) ? '' : new Date(at).toISOString();\n}\n\nexport interface SamplesExportInputs {\n // What the file is called after: the widget's title, else its device.\n subject: string;\n samples: readonly MeasurementSample[];\n unit?: string;\n precision?: number;\n // The first heading of the series column: the measurement (one device) or the device (a compare).\n seriesIs: 'measurement' | 'device';\n // The span the widget draws, when it knows one (the board's range or its own pin).\n spanSeconds?: number;\n}\n\n// The samples a chart draws, long: one row per point, oldest first, `Time, Measurement|Series, Value\n// (unit), Basis`. Long rather than wide because a chart's measurements do not share instants.\nexport function samplesExport(i: SamplesExportInputs): WidgetExportTable {\n const w = words();\n const points = i.samples\n .filter((s) => s.value !== null && s.occurredTime && !Number.isNaN(Date.parse(s.occurredTime)))\n .map((s) => ({ s, at: Date.parse(s.occurredTime as string) }))\n .sort((a, b) => a.at - b.at || (a.s.name < b.s.name ? -1 : a.s.name > b.s.name ? 1 : 0));\n const basis = (s: MeasurementSample): string => (s.bucketSeconds !== undefined ? w.average(bucketLabel(s.bucketSeconds)) : w.reading);\n // The file says what it holds: the buckets' widths and whether live readings are in it.\n const kinds = [...new Set(points.map(({ s }) => basis(s)))];\n const first = points[0]?.s.occurredTime;\n const last = points[points.length - 1]?.s.occurredTime;\n const parts = [i.subject, i.spanSeconds !== undefined ? spanLabel(i.spanSeconds) : undefined, first ? stamp(first) : undefined, last ? stamp(last) : undefined, ...kinds].filter(Boolean);\n return {\n name: parts.join('-'),\n columns: [w.time, i.seriesIs === 'device' ? w.series : w.measurement, `${w.value}${i.unit ? ` (${i.unit})` : ''}`, w.basis],\n rows: points.map(({ s, at }): WidgetExportCell[] => [new Date(at).toISOString(), s.name, roundTo(s.value as number, i.precision), basis(s)]),\n };\n}\n\nexport interface FleetExportInputs {\n subject: string;\n members: readonly FleetMember[];\n total: number;\n // The measurement columns as the table shows them, in order, with their formats.\n columns: ReadonlyArray<{ name: string; heading: string; precision?: number }>;\n sort: SortKey;\n}\n\n// The fleet table, wide: a row per device in the order on screen (all of them, not the page), the\n// device's name and token, then each measurement's latest reading and the instant it was taken. A\n// cell with no reading is empty; the table says why on screen, and an empty cell is never a zero.\nexport function fleetExport(i: FleetExportInputs): WidgetExportTable {\n const w = words();\n const rows = sortMembers(i.members, i.sort).map((m): WidgetExportCell[] => [\n deviceLabel(m),\n m.token,\n ...i.columns.flatMap((c) => {\n const cell = cellFor(m, c.name);\n return cell.kind === 'value' ? [roundTo(cell.value, c.precision), isoOrEmpty(cell.sample.occurredTime)] : [null, null];\n }),\n ]);\n // A fleet past what the resolver read says so in the name, as the table does on screen.\n const partial = i.members.length < i.total ? `first-${i.members.length}-of-${i.total}` : undefined;\n return {\n name: [i.subject, w.latest, partial, stamp(new Date().toISOString())].filter(Boolean).join('-'),\n columns: [w.device, w.deviceToken, ...i.columns.flatMap((c) => [`${c.heading} (${w.latest})`, `${c.heading} ${w.readingTime}`])],\n rows,\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;AAaA,SAAS,iBAA2D;AACpE,SAAS,oBAAmE;AAmB5E,IAAM,QAAoD;AAAA,EACxD,IAAI;AAAA,IACF,MAAM;AAAA,IACN,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,OAAO;AAAA,IACP,SAAS;AAAA,IACT,SAAS,CAAC,WAAW,WAAW,MAAM;AAAA,IACtC,QAAQ;AAAA,IACR,aAAa;AAAA,IACb,aAAa;AAAA,IACb,QAAQ;AAAA,EACV;AAAA,EACA,IAAI;AAAA,IACF,MA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K,OAAO,YAAY,CAAC,IAAI,CAAC,MAAM,IAAI;AAAA,IACvH,CAAC;AAAA,EACH,CAAC;AAED,QAAM,UAAU,EAAE,QAAQ,SAAS,EAAE,QAAQ,SAAS,EAAE,QAAQ,MAAM,OAAO,EAAE,KAAK,KAAK;AACzF,SAAO;AAAA,IACL,MAAM,CAAC,EAAE,SAAS,EAAE,QAAQ,SAAS,OAAM,oBAAI,KAAK,GAAE,YAAY,CAAC,CAAC,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG;AAAA,IAC9F,SAAS,CAAC,EAAE,QAAQ,EAAE,aAAa,GAAG,EAAE,QAAQ,QAAQ,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,KAAK,EAAE,MAAM,KAAK,GAAG,EAAE,OAAO,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;AAAA,IAC/H;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -94,4 +94,4 @@ export {
94
94
  wantsEventMarkers,
95
95
  takesHistorySeed
96
96
  };
97
- //# sourceMappingURL=chunk-GUCEPNGM.js.map
97
+ //# sourceMappingURL=chunk-EFTUK5YX.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/binding-policy.ts"],
4
+ "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The channel adapters' half of a widget's declarative binding policy: turn the descriptor's\n// `binding` (typed constants and references to declared option keys) plus the widget's stored\n// options into the subscription arguments a hub channel takes. This is the ONLY place that\n// reads a policy-referenced option, so it reads them by the NAME the descriptor declares —\n// no widget id is consulted, and an extension that declares `{ option: 'rows' }` is honored\n// exactly as a built-in declaring `{ option: 'maxRows' }` is.\n\nimport {\n isValidSpanSeconds,\n type AlarmSubscription,\n type CommandSubscription,\n type WidgetDescriptor,\n type WidgetInstance,\n} from '@devicechain/dashboards';\n\nimport { optBoolean, optNumber, optString } from '@devicechain/widget-sdk';\n\n// The shapes a policy value takes at runtime (the descriptor is validated at registration,\n// so a ref names a declared option of a compatible kind; the value stored in a widget may\n// still be absent or the wrong type, in which case the ref's default applies).\ninterface NumberBinding {\n const?: number;\n option?: string;\n default?: number;\n min?: number;\n}\ninterface StringBinding {\n option?: string;\n default?: string;\n}\n\nfunction numberValue(binding: NumberBinding | undefined, options: WidgetInstance['options']): number | undefined {\n if (!binding) return undefined;\n let value: number | undefined;\n if (typeof binding.const === 'number') value = binding.const;\n else if (binding.option !== undefined) value = optNumber(options, binding.option) ?? binding.default;\n if (value === undefined) return undefined;\n return binding.min !== undefined ? Math.max(binding.min, value) : value;\n}\n\nfunction stringValue(binding: StringBinding | undefined, options: WidgetInstance['options']): string | undefined {\n if (!binding || binding.option === undefined) return undefined;\n return optString(options, binding.option) ?? binding.default;\n}\n\nfunction policy(descriptor: WidgetDescriptor): Record<string, unknown> {\n return descriptor.binding as Record<string, unknown>;\n}\n\n// The rolling-window size a measurement widget asked for, or undefined for the hook default.\nexport function measurementWindow(descriptor: WidgetDescriptor, widget: WidgetInstance): number | undefined {\n return numberValue(policy(descriptor).window as NumberBinding | undefined, widget.options);\n}\n\n// The span (seconds) a TIME-RANGED measurement widget draws, or undefined for one that is not.\n// A widget is time-ranged by declaring `binding.windowSeconds`. Its option pins the span when set\n// to a usable one; otherwise the widget follows the board's range (`boardSpan`, which a viewer\n// can change). An option that is set but not a usable span (under a minute, over a week, not a\n// whole number) is ignored rather than clamped, for the reason the parser gives for the board's\n// own default: clamping turns a typo into a window nobody wrote.\nexport function measurementSpan(\n descriptor: WidgetDescriptor,\n widget: WidgetInstance,\n boardSpan: number | undefined,\n): number | undefined {\n const binding = policy(descriptor).windowSeconds as NumberBinding | undefined;\n if (!binding) return undefined;\n const pinned = numberValue({ ...binding, min: undefined }, widget.options);\n return isValidSpanSeconds(pinned) ? pinned : boardSpan;\n}\n\n// Whether a measurement widget reads its datasource MEMBER BY MEMBER (a fleet widget: a row or a\n// bar per device of an anchor) rather than as one stream keyed by measurement name. The descriptor\n// says so with `binding.members`: always (`const`), or when a declared option holds a given value\n// (a bar chart set to one bar per device).\nexport function membersMode(descriptor: WidgetDescriptor, widget: WidgetInstance): boolean {\n const members = policy(descriptor).members as { const?: boolean; option?: string; equals?: string } | undefined;\n if (!members) return false;\n if (members.const === true) return true;\n return members.option !== undefined && optString(widget.options, members.option) === members.equals;\n}\n\n// Whether a widget's `measurement` option is the one its MEMBERS mode compares, and so means nothing\n// outside that mode: the descriptor gates members mode on an option (a chart set to one line or one\n// bar per device) rather than always reading member by member. Read one device at a time, such a\n// widget draws every measurement its datasource selects, so a `measurement` left stored from the\n// members mode must not narrow anything (its freshness is the newest of what it draws).\nexport function measurementIsMembersOnly(descriptor: WidgetDescriptor): boolean {\n const members = policy(descriptor).members as { const?: boolean; option?: string } | undefined;\n return members !== undefined && members.const !== true && members.option !== undefined;\n}\n\n// Whether a measurement widget reads its devices' CONNECTIVITY (online or offline, last seen) rather\n// than their readings. The descriptor says so with `binding.presence`. The feed that reads it is its\n// own chunk (presence-feed.tsx), loaded only for such a widget.\nexport function presenceMode(descriptor: WidgetDescriptor): boolean {\n return (policy(descriptor).presence as { const?: boolean } | undefined)?.const === true;\n}\n\n// Whether a measurement widget reads one device's STORED HISTORY in time buckets rather than the live\n// feed (`binding.history`). The feed that reads it is its own chunk (history-feed.tsx), loaded only for\n// such a widget.\nexport function historyMode(descriptor: WidgetDescriptor): boolean {\n return (policy(descriptor).history as { const?: boolean } | undefined)?.const === true;\n}\n\n// The acknowledged filter is stored as 'true' / 'false' (or absent = any).\nfunction parseAcknowledged(value: string | undefined): boolean | undefined {\n if (value === 'true') return true;\n if (value === 'false') return false;\n return undefined;\n}\n\n// An alarm widget's scope + filters. The datasource (undefined = tenant-wide) is the\n// renderer's; the page size and filters come from the policy.\nexport function alarmSubscription(descriptor: WidgetDescriptor, widget: WidgetInstance): AlarmSubscription {\n const p = policy(descriptor);\n const deviceType = stringValue(p.deviceType as StringBinding | undefined, widget.options);\n return {\n datasource: widget.datasource,\n state: stringValue(p.state as StringBinding | undefined, widget.options),\n severity: stringValue(p.severity as StringBinding | undefined, widget.options),\n acknowledged: parseAcknowledged(stringValue(p.acknowledged as StringBinding | undefined, widget.options)),\n pageSize: numberValue(p.pageSize as NumberBinding | undefined, widget.options) ?? 1,\n // A widget that declares `binding.countBySeverity` reads counts, not rows; `binding.deviceType`\n // narrows them to one device type (a blank option is no type).\n ...((p.countBySeverity as { const?: boolean } | undefined)?.const === true ? { countBySeverity: true } : {}),\n ...(deviceType ? { deviceType } : {}),\n };\n}\n\n// Whether an alarm widget groups its alarms by the originating device's type (a tab strip). The\n// descriptor says so with `binding.groupBy`: a declared option holding a given value turns it on.\nexport function groupsAlarmsByDeviceType(descriptor: WidgetDescriptor, widget: WidgetInstance): boolean {\n const groupBy = policy(descriptor).groupBy as { option?: string; equals?: string } | undefined;\n return groupBy?.option !== undefined && optString(widget.options, groupBy.option) === groupBy.equals;\n}\n\n// A command widget's target scope and how many recent commands its history shows.\nexport function commandSubscription(descriptor: WidgetDescriptor, widget: WidgetInstance): CommandSubscription {\n return {\n datasource: widget.datasource,\n pageSize: numberValue(policy(descriptor).pageSize as NumberBinding | undefined, widget.options) ?? 1,\n };\n}\n\n// Whether a measurement widget draws alarm or command markers: its descriptor declares the marker\n// options and one of them is on. The feed that reads them is its own chunk (event-markers-feed.tsx),\n// loaded only when this is true.\nexport function wantsEventMarkers(descriptor: WidgetDescriptor, widget: WidgetInstance): boolean {\n const declared = descriptor.options as Record<string, unknown>;\n return (\n (declared.markAlarms !== undefined && optBoolean(widget.options, 'markAlarms') === true) ||\n (declared.markCommands !== undefined && optBoolean(widget.options, 'markCommands') === true)\n );\n}\n\n// Whether a widget takes the stored history as a seed. Every measurement widget does. An aggregate\n// widget reads its own aggregates and takes none, except a card showing the LATEST reading: the live\n// stream only delivers what arrives after the board opens, so a device that reports every few\n// minutes would leave it saying there is no data while its readings are stored.\nexport function takesHistorySeed(descriptor: WidgetDescriptor, widget: WidgetInstance): boolean {\n return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W;AAC5B,SACG,SAAS,eAAe,UAAa,WAAW,OAAO,SAAS,YAAY,MAAM,QAClF,SAAS,iBAAiB,UAAa,WAAW,OAAO,SAAS,cAAc,MAAM;AAE3F;AAMO,SAAS,iBAAiB,YAA8B,QAAiC;AAC9F,SAAO,WAAW,YAAY,iBAAkB,WAAW,YAAY,eAAe,UAAU,OAAO,SAAS,MAAM,MAAM;AAC9H;",
6
+ "names": []
7
+ }
@@ -9,7 +9,7 @@ import {
9
9
  useStickyChars
10
10
  } from "@devicechain/widget-sdk";
11
11
  import { jsx, jsxs } from "react/jsx-runtime";
12
- var MARKER = { above: "\u25B2", below: "\u25BC" };
12
+ var MARKER = { above: "▲", below: "▼" };
13
13
  function LevelReadout({ text, unit, color, position, size, scale, strings }) {
14
14
  const hasUnit = unit !== void 0 && unit !== "";
15
15
  const marked = position === "above" || position === "below";
@@ -73,4 +73,4 @@ export {
73
73
  LevelReadout,
74
74
  LevelEmpty
75
75
  };
76
- //# sourceMappingURL=chunk-EQOWBDS7.js.map
76
+ //# sourceMappingURL=chunk-G5UBMPMX.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/level-readout.tsx"],
4
- "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The fitted DOM readout and the explained empty state the level-and-indicator widgets share.\n// DOM, not canvas text, so the readability gate can measure it.\n\nimport {\n css,\n fitValueFont,\n fitValueFontCss,\n FIT_MIN_FONT_PX,\n fontVar,\n spaceVar,\n useStickyChars,\n} from '@devicechain/widget-sdk';\n\nimport type { LevelStrings } from './level-strings';\nimport type { ScalePosition } from './value-scale';\n\n// The room the readout may fill (a box inside the frame's content column) and the density scale.\nexport interface ReadoutRoom {\n size: { width: number; height: number };\n scale: number;\n}\n\n// The words the off-scale marker is labelled with; the only strings the readout itself reads.\nexport type MarkerStrings = Pick<LevelStrings, 'aboveScale' | 'belowScale'>;\n\n// A readout that can be marked off-scale must be handed the marker's label, so an unlabelled\n// marker cannot be written; one that is never marked (the gauge) needs no strings at all, which\n// keeps the level-strings table out of an eager widget's bundle.\nexport type LevelReadoutProps = ReadoutRoom & {\n text: string;\n unit?: string;\n color?: string;\n} & (\n | {\n // Set when the value lies off the scale: a marker is drawn beside it.\n position?: ScalePosition;\n strings: MarkerStrings;\n }\n | { position?: undefined; strings?: undefined }\n );\n\nconst MARKER = { above: '\u25B2', below: '\u25BC' } as const;\n\nexport function LevelReadout({ text, unit, color, position, size, scale, strings }: LevelReadoutProps) {\n const hasUnit = unit !== undefined && unit !== '';\n const marked = position === 'above' || position === 'below';\n // The unit and the marker render at half size, so each counts for half its characters.\n const chars = useStickyChars(text.length + (hasUnit ? Math.ceil(unit.length / 2) + 1 : 0) + (marked ? 1 : 0));\n const floor = Math.round(FIT_MIN_FONT_PX * scale);\n const measured = size.width > 0 && size.height > 0;\n const px = measured ? fitValueFont(size, chars, { floor }) : undefined;\n const font = px ?? fitValueFontCss(chars, { floor });\n const half = px !== undefined ? Math.round(px / 2) : `calc(${font} / 2)`;\n return (\n <div\n data-level-readout=\"\"\n style={{\n fontSize: font,\n fontWeight: 600,\n lineHeight: 1.1,\n whiteSpace: 'nowrap',\n fontVariantNumeric: 'tabular-nums',\n color: color ?? css('foreground'),\n textAlign: 'center',\n }}\n >\n {text}\n {hasUnit ? (\n <span style={{ fontSize: half, color: css('muted-foreground'), marginLeft: spaceVar(1) }}>{unit}</span>\n ) : null}\n {marked ? (\n <span\n role=\"img\"\n aria-label={position === 'above' ? strings.aboveScale : strings.belowScale}\n title={position === 'above' ? strings.aboveScale : strings.belowScale}\n style={{ fontSize: half, color: css('muted-foreground'), marginLeft: spaceVar(1) }}\n >\n {MARKER[position]}\n </span>\n ) : null}\n </div>\n );\n}\n\n// Why there is nothing to draw: a short sentence in the widget's own box, never a fake value.\nexport function LevelEmpty({ message }: { message: string }) {\n return (\n <div\n data-level-empty=\"\"\n style={{\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n height: '100%',\n textAlign: 'center',\n color: css('muted-foreground'),\n fontSize: fontVar('sm'),\n overflowWrap: 'anywhere',\n }}\n >\n {message}\n </div>\n );\n}\n\n"],
5
- "mappings": ";AAMA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA2CH,SAcI,KAdJ;AAbJ,IAAM,SAAS,EAAE,OAAO,UAAK,OAAO,SAAI;AAEjC,SAAS,aAAa,EAAE,MAAM,MAAM,OAAO,UAAU,MAAM,OAAO,QAAQ,GAAsB;AACrG,QAAM,UAAU,SAAS,UAAa,SAAS;AAC/C,QAAM,SAAS,aAAa,WAAW,aAAa;AAEpD,QAAM,QAAQ,eAAe,KAAK,UAAU,UAAU,KAAK,KAAK,KAAK,SAAS,CAAC,IAAI,IAAI,MAAM,SAAS,IAAI,EAAE;AAC5G,QAAM,QAAQ,KAAK,MAAM,kBAAkB,KAAK;AAChD,QAAM,WAAW,KAAK,QAAQ,KAAK,KAAK,SAAS;AACjD,QAAM,KAAK,WAAW,aAAa,MAAM,OAAO,EAAE,MAAM,CAAC,IAAI;AAC7D,QAAM,OAAO,MAAM,gBAAgB,OAAO,EAAE,MAAM,CAAC;AACnD,QAAM,OAAO,OAAO,SAAY,KAAK,MAAM,KAAK,CAAC,IAAI,QAAQ,IAAI;AACjE,SACE;AAAA,IAAC;AAAA;AAAA,MACC,sBAAmB;AAAA,MACnB,OAAO;AAAA,QACL,UAAU;AAAA,QACV,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,oBAAoB;AAAA,QACpB,OAAO,SAAS,IAAI,YAAY;AAAA,QAChC,WAAW;AAAA,MACb;AAAA,MAEC;AAAA;AAAA,QACA,UACC,oBAAC,UAAK,OAAO,EAAE,UAAU,MAAM,OAAO,IAAI,kBAAkB,GAAG,YAAY,SAAS,CAAC,EAAE,GAAI,gBAAK,IAC9F;AAAA,QACH,SACC;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,cAAY,aAAa,UAAU,QAAQ,aAAa,QAAQ;AAAA,YAChE,OAAO,aAAa,UAAU,QAAQ,aAAa,QAAQ;AAAA,YAC3D,OAAO,EAAE,UAAU,MAAM,OAAO,IAAI,kBAAkB,GAAG,YAAY,SAAS,CAAC,EAAE;AAAA,YAEhF,iBAAO,QAAQ;AAAA;AAAA,QAClB,IACE;AAAA;AAAA;AAAA,EACN;AAEJ;AAGO,SAAS,WAAW,EAAE,QAAQ,GAAwB;AAC3D,SACE;AAAA,IAAC;AAAA;AAAA,MACC,oBAAiB;AAAA,MACjB,OAAO;AAAA,QACL,SAAS;AAAA,QACT,YAAY;AAAA,QACZ,gBAAgB;AAAA,QAChB,QAAQ;AAAA,QACR,WAAW;AAAA,QACX,OAAO,IAAI,kBAAkB;AAAA,QAC7B,UAAU,QAAQ,IAAI;AAAA,QACtB,cAAc;AAAA,MAChB;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;",
4
+ "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The fitted DOM readout and the explained empty state the level-and-indicator widgets share.\n// DOM, not canvas text, so the readability gate can measure it.\n\nimport {\n css,\n fitValueFont,\n fitValueFontCss,\n FIT_MIN_FONT_PX,\n fontVar,\n spaceVar,\n useStickyChars,\n} from '@devicechain/widget-sdk';\n\nimport type { LevelStrings } from './level-strings';\nimport type { ScalePosition } from './value-scale';\n\n// The room the readout may fill (a box inside the frame's content column) and the density scale.\nexport interface ReadoutRoom {\n size: { width: number; height: number };\n scale: number;\n}\n\n// The words the off-scale marker is labelled with; the only strings the readout itself reads.\nexport type MarkerStrings = Pick<LevelStrings, 'aboveScale' | 'belowScale'>;\n\n// A readout that can be marked off-scale must be handed the marker's label, so an unlabelled\n// marker cannot be written; one that is never marked (the gauge) needs no strings at all, which\n// keeps the level-strings table out of an eager widget's bundle.\nexport type LevelReadoutProps = ReadoutRoom & {\n text: string;\n unit?: string;\n color?: string;\n} & (\n | {\n // Set when the value lies off the scale: a marker is drawn beside it.\n position?: ScalePosition;\n strings: MarkerStrings;\n }\n | { position?: undefined; strings?: undefined }\n );\n\nconst MARKER = { above: '▲', below: '▼' } as const;\n\nexport function LevelReadout({ text, unit, color, position, size, scale, strings }: LevelReadoutProps) {\n const hasUnit = unit !== undefined && unit !== '';\n const marked = position === 'above' || position === 'below';\n // The unit and the marker render at half size, so each counts for half its characters.\n const chars = useStickyChars(text.length + (hasUnit ? Math.ceil(unit.length / 2) + 1 : 0) + (marked ? 1 : 0));\n const floor = Math.round(FIT_MIN_FONT_PX * scale);\n const measured = size.width > 0 && size.height > 0;\n const px = measured ? fitValueFont(size, chars, { floor }) : undefined;\n const font = px ?? fitValueFontCss(chars, { floor });\n const half = px !== undefined ? Math.round(px / 2) : `calc(${font} / 2)`;\n return (\n <div\n data-level-readout=\"\"\n style={{\n fontSize: font,\n fontWeight: 600,\n lineHeight: 1.1,\n whiteSpace: 'nowrap',\n fontVariantNumeric: 'tabular-nums',\n color: color ?? css('foreground'),\n textAlign: 'center',\n }}\n >\n {text}\n {hasUnit ? (\n <span style={{ fontSize: half, color: css('muted-foreground'), marginLeft: spaceVar(1) }}>{unit}</span>\n ) : null}\n {marked ? (\n <span\n role=\"img\"\n aria-label={position === 'above' ? strings.aboveScale : strings.belowScale}\n title={position === 'above' ? strings.aboveScale : strings.belowScale}\n style={{ fontSize: half, color: css('muted-foreground'), marginLeft: spaceVar(1) }}\n >\n {MARKER[position]}\n </span>\n ) : null}\n </div>\n );\n}\n\n// Why there is nothing to draw: a short sentence in the widget's own box, never a fake value.\nexport function LevelEmpty({ message }: { message: string }) {\n return (\n <div\n data-level-empty=\"\"\n style={{\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n height: '100%',\n textAlign: 'center',\n color: css('muted-foreground'),\n fontSize: fontVar('sm'),\n overflowWrap: 'anywhere',\n }}\n >\n {message}\n </div>\n );\n}\n\n"],
5
+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QAAQ;AAAA,YAC3D,OAAO,EAAE,UAAU,MAAM,OAAO,IAAI,kBAAkB,GAAG,YAAY,SAAS,CAAC,EAAE;AAAA,YAEhF,iBAAO,QAAQ;AAAA;AAAA,QAClB,IACE;AAAA;AAAA;AAAA,EACN;AAEJ;AAGO,SAAS,WAAW,EAAE,QAAQ,GAAwB;AAC3D,SACE;AAAA,IAAC;AAAA;AAAA,MACC,oBAAiB;AAAA,MACjB,OAAO;AAAA,QACL,SAAS;AAAA,QACT,YAAY;AAAA,QACZ,gBAAgB;AAAA,QAChB,QAAQ;AAAA,QACR,WAAW;AAAA,QACX,OAAO,IAAI,kBAAkB;AAAA,QAC7B,UAAU,QAAQ,IAAI;AAAA,QACtB,cAAc;AAAA,MAChB;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  NoReading
3
- } from "./chunk-JVC6JYUR.js";
3
+ } from "./chunk-RLVZXNPJ.js";
4
4
 
5
5
  // src/widgets/table.tsx
6
6
  import {
@@ -20,10 +20,12 @@ import {
20
20
  import { viewerLocale } from "@devicechain/widget-sdk";
21
21
  var TABLE_STRINGS = {
22
22
  en: { measurement: "Measurement", value: "Value", time: "Time" },
23
- es: { measurement: "Medici\xF3n", value: "Valor", time: "Hora" }
23
+ es: { measurement: "Medición", value: "Valor", time: "Hora" },
24
+ "zh-CN": { measurement: "测量项", value: "值", time: "时间" }
24
25
  };
25
26
  function tableStrings(locale = viewerLocale()) {
26
- return locale?.toLowerCase().split("-")[0] === "es" ? TABLE_STRINGS.es : TABLE_STRINGS.en;
27
+ const language = locale?.toLowerCase().split("-")[0];
28
+ return language === "es" ? TABLE_STRINGS.es : language === "zh" ? TABLE_STRINGS["zh-CN"] : TABLE_STRINGS.en;
27
29
  }
28
30
 
29
31
  // src/widgets/table.tsx
@@ -73,4 +75,4 @@ function Table({ widget, data }) {
73
75
  export {
74
76
  Table
75
77
  };
76
- //# sourceMappingURL=chunk-RG2AYYKO.js.map
78
+ //# sourceMappingURL=chunk-GWH5AHG3.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/widgets/table.tsx", "../../src/table-strings.ts"],
4
+ "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// table — the latest value of every measurement the datasource carries, one row\n// per measurement name.\n\nimport type { CSSProperties } from 'react';\n\nimport {\n css,\n fontVar,\n spaceVar,\n FlashValue,\n formatTimestamp,\n optBoolean,\n optNumber,\n optString,\n useWidgetTimeZone,\n WidgetFrame,\n type WidgetProps,\n} from '@devicechain/widget-sdk';\n\nimport { NoReading } from '../no-reading-core';\nimport { tableStrings } from '../table-strings';\n\nconst cell: CSSProperties = { padding: `${spaceVar(1)} ${spaceVar(3)}`, textAlign: 'left' };\nconst headCell: CSSProperties = {\n ...cell,\n fontSize: fontVar('xs'),\n fontWeight: 600,\n textTransform: 'uppercase',\n letterSpacing: '0.04em',\n color: css('muted-foreground'),\n borderBottom: `1px solid ${css('border')}`,\n};\n\nexport function Table({ widget, data }: WidgetProps) {\n const timeZone = useWidgetTimeZone();\n const words = tableStrings();\n const rows = Object.values(data.latest).sort((a, b) => a.name.localeCompare(b.name));\n // Round to a fixed number of decimals when configured; unset keeps the raw value\n // (formatValue's default). A live sensor value is otherwise a wall of digits.\n const precision = optNumber(widget.options, 'precision');\n // Opt-in directional flash per row (keyed by measurement name, so each value's cue is\n // independent — see FlashValue).\n const flash = optBoolean(widget.options, 'flashOnChange');\n\n if (rows.length === 0) {\n const asked = widget.datasource?.measurements;\n return (\n <WidgetFrame title={optString(widget.options, 'title')}>\n <NoReading unbound={widget.datasource?.kind === 'unbound'} measurement={asked?.length === 1 ? asked[0] : undefined} precision={precision} />\n </WidgetFrame>\n );\n }\n\n return (\n <WidgetFrame title={optString(widget.options, 'title')} flush>\n <div style={{ height: '100%', overflow: 'auto' }}>\n <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: fontVar('md'), color: css('foreground') }}>\n <thead>\n <tr>\n <th style={headCell}>{words.measurement}</th>\n <th style={headCell}>{words.value}</th>\n <th style={headCell}>{words.time}</th>\n </tr>\n </thead>\n <tbody>\n {rows.map((row) => (\n <tr key={row.name}>\n <td style={cell}>{row.name}</td>\n <td style={{ ...cell, fontVariantNumeric: 'tabular-nums' }}>\n <FlashValue\n value={row.value}\n precision={precision}\n enabled={flash}\n identity={`${row.deviceToken}:${row.name}`}\n />\n {/* classifier is deliberately NOT shown: it is the bound metric\n definition's internal id (ADR-016), not a user-facing label —\n appending it rendered as spurious digits after the value. */}\n </td>\n <td style={{ ...cell, color: css('muted-foreground') }}>{formatTimestamp(row.occurredTime, timeZone)}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n </WidgetFrame>\n );\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The telemetry table's column headers. The rows themselves are the tenant's own measurement\n// names and values, which are never translated.\n\nimport { viewerLocale } from '@devicechain/widget-sdk';\n\nexport interface TableStrings {\n measurement: string;\n value: string;\n time: string;\n}\n\nexport const TABLE_STRINGS: Record<'en' | 'es' | 'zh-CN', TableStrings> = {\n en: { measurement: 'Measurement', value: 'Value', time: 'Time' },\n es: { measurement: 'Medición', value: 'Valor', time: 'Hora' },\n 'zh-CN': { measurement: '测量项', value: '值', time: '时间' },\n};\n\nexport function tableStrings(locale: string | undefined = viewerLocale()): TableStrings {\n const language = locale?.toLowerCase().split('-')[0];\n return language === 'es' ? TABLE_STRINGS.es : language === 'zh' ? TABLE_STRINGS['zh-CN'] : TABLE_STRINGS.en;\n}\n"],
5
+ "mappings": ";;;;;AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;ACdP,SAAS,oBAAoB;AAQtB,IAAM,gBAA6D;AAAA,EACxE,IAAI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eAAY,OAAO,UAAU,OAAO,SAAS,OAAO,GAAG,OAAK,MAC3D,8BAAC,SAAI,OAAO,EAAE,QAAQ,QAAQ,UAAU,OAAO,GAC7C,+BAAC,WAAM,OAAO,EAAE,OAAO,QAAQ,gBAAgB,YAAY,UAAU,QAAQ,IAAI,GAAG,OAAO,IAAI,YAAY,EAAE,GAC3G;AAAA,wBAAC,WACC,+BAAC,QACC;AAAA,0BAAC,QAAG,OAAO,UAAW,gBAAM,aAAY;AAAA,MACxC,oBAAC,QAAG,OAAO,UAAW,gBAAM,OAAM;AAAA,MAClC,oBAAC,QAAG,OAAO,UAAW,gBAAM,MAAK;AAAA,OACnC,GACF;AAAA,IACA,oBAAC,WACE,eAAK,IAAI,CAAC,QACP,qBAAC,QACC;AAAA,0BAAC,QAAG,OAAO,MAAO,cAAI,MAAK;AAAA,MAC3B,oBAAC,QAAG,OAAO,EAAE,GAAG,MAAM,oBAAoB,eAAe,GACvD;AAAA,QAAC;AAAA;AAAA,UACC,OAAO,IAAI;AAAA,UACX;AAAA,UACA,SAAS;AAAA,UACT,UAAU,GAAG,IAAI,WAAW,IAAI,IAAI,IAAI;AAAA;AAAA,MAC1C,GAIF;AAAA,MACA,oBAAC,QAAG,OAAO,EAAE,GAAG,MAAM,OAAO,IAAI,kBAAkB,EAAE,GAAI,0BAAgB,IAAI,cAAc,QAAQ,GAAE;AAAA,SAb9F,IAAI,IAcb,CACD,GACL;AAAA,KACF,GACF,GACF;AAEJ;",
6
+ "names": []
7
+ }
@@ -87,4 +87,4 @@ export {
87
87
  historyExport,
88
88
  spansDays
89
89
  };
90
- //# sourceMappingURL=chunk-XJ7UF2CP.js.map
90
+ //# sourceMappingURL=chunk-O763YMOG.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/history-model.ts"],
4
+ "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The history table's state, decided apart from the drawing and from the hub: which window it reads,\n// how the store's buckets become rows, how the rows are ordered and paged, and the CSV it exports.\n// Pure, so each rule is a test.\n//\n// 🔴 EVERY NUMBER HERE IS A BUCKET AVERAGE. The store answers a history read with buckets (a count, a\n// minimum, a maximum and a sum of the readings in a time slot) and this table shows each bucket's\n// average. It is never a reading and never the device's state at that time, so everything that names\n// it (the footer, the column headings, the export's headings and file name) says \"avg per <bucket>\".\n\nimport { bucketSecondsFor, spanLabel, type HistoryWindow, type MeasurementBucket } from '@devicechain/dashboards';\nimport type { WidgetExportTable } from '@devicechain/widget-sdk';\n\nimport { clampPage, pageCount, seedWindow } from './fleet-model';\n\nexport { clampPage, pageCount };\n\nexport const DEFAULT_PAGE_SIZE = 10;\n\n// What the feed hands the table: the buckets it read for a window, or why it has none.\nexport type HistoryView =\n | { status: 'loading' | 'unbound' | 'forbidden' | 'unsupported' | 'failed' }\n | { status: 'ready'; buckets: readonly MeasurementBucket[]; window: HistoryWindow };\n\n// How a column is presented: its heading, its unit, and its precision. By measurement name.\nexport interface HistoryColumn {\n name: string;\n label?: string;\n unit?: string;\n precision?: number;\n}\n\n// One row: a bucket's start and the average of each measurement in it. A measurement with no readings\n// in the bucket has no entry (not zero, not the previous value).\nexport interface HistoryRow {\n // RFC 3339, as the store returned it.\n bucketStart: string;\n at: number;\n averages: ReadonlyMap<string, number>;\n}\n\n// The window a history table over `spanSeconds` reads at `at` (epoch ms): whole minutes, in the\n// buckets of the span's chart (bucketSecondsFor). Delegates to the fleet seed window, which every\n// board widget reading a span uses, so the table reads exactly the buckets a chart over the same span\n// draws.\nexport function historyWindow(spanSeconds: number, at: number): HistoryWindow {\n return seedWindow(spanSeconds, at);\n}\n\n// How often a live table reads again: one bucket of its span, never more often than once a minute. A\n// bucket cannot change between two reads inside it by more than the readings of that slice, and a\n// week's span re-read every few seconds would scan a week of summaries to move by a few seconds.\nexport function historyRefreshMs(spanSeconds: number): number {\n return bucketSecondsFor(spanSeconds) * 1000;\n}\n\n// The bucket width as the sentence's unit: `5m`, `1h`, `42m`. Always exact (spanLabel).\nexport function bucketLabel(bucketSeconds: number): string {\n return spanLabel(bucketSeconds);\n}\n\n// The columns to show: the author's list if it names any, else the datasource's measurements, else\n// whatever the buckets hold (sorted, so the order is stable between reads).\nexport function historyColumns(\n authored: readonly HistoryColumn[],\n datasource: readonly string[],\n observed: Iterable<string>,\n): HistoryColumn[] {\n if (authored.length > 0) return [...authored];\n const names = datasource.length > 0 ? datasource : [...new Set(observed)].sort();\n return names.map((name) => ({ name }));\n}\n\n// Pivots the store's buckets into rows, one per bucket start. A bucket without an average (it holds\n// no readings) contributes nothing, and a start with no average for any column is no row. Newest\n// first unless `oldestFirst`.\nexport function historyRows(buckets: readonly MeasurementBucket[], columns: readonly string[], oldestFirst: boolean): HistoryRow[] {\n const shown = new Set(columns);\n const byStart = new Map<string, Map<string, number>>();\n for (const b of buckets) {\n if (!shown.has(b.name) || b.avg == null || !Number.isFinite(b.avg)) continue;\n let row = byStart.get(b.bucketStart);\n if (!row) byStart.set(b.bucketStart, (row = new Map()));\n row.set(b.name, b.avg);\n }\n const rows: HistoryRow[] = [];\n for (const [bucketStart, averages] of byStart) {\n const at = Date.parse(bucketStart);\n if (Number.isNaN(at)) continue;\n rows.push({ bucketStart, at, averages });\n }\n rows.sort((a, b) => (oldestFirst ? a.at - b.at : b.at - a.at));\n return rows;\n}\n\n// Every measurement name the buckets hold (for a table whose columns come from what was read).\nexport function observedNames(buckets: readonly MeasurementBucket[]): string[] {\n return [...new Set(buckets.filter((b) => b.avg != null).map((b) => b.name))];\n}\n\n// The heading of a column: its label (else the measurement's name) and its unit.\nexport function columnHeading(c: HistoryColumn): string {\n return `${c.label ?? c.name}${c.unit ? ` (${c.unit})` : ''}`;\n}\n\n// A stored value at the column's precision, or at the board-wide one: what the cell prints, as a\n// number, so the export carries what the table shows. With neither set the value is exact.\nexport function roundTo(value: number, precision: number | undefined): number {\n if (precision === undefined) return value;\n const places = Math.min(100, Math.max(0, Math.trunc(precision)));\n return Number(value.toFixed(places));\n}\n\n// `2026-10-22T14:05:00.000Z` -> `20261022T1405Z`, the way a file name carries a time: UTC, to the\n// nearest minute (a window's end is the instant just before its boundary, and names the boundary).\nexport function stamp(iso: string): string {\n const minute = Math.round(Date.parse(iso) / 60_000) * 60_000;\n return new Date(minute).toISOString().replace(/[-:]/g, '').replace(/\\d\\d\\.\\d+Z$/, 'Z');\n}\n\nexport interface HistoryExportInputs {\n // The widget's title, else its device: what the file is called after.\n subject: string;\n columns: readonly HistoryColumn[];\n rows: readonly HistoryRow[];\n window: Pick<HistoryWindow, 'startTime' | 'endTime' | 'intervalSeconds'>;\n precision: number | undefined;\n heading: { time: string; average: (bucket: string) => string };\n}\n\n// The CSV of what the table holds: EVERY row (not the page on screen), in the order on screen, one\n// column per measurement. The time is the bucket's start as an ISO-8601 instant in UTC (`Z`), and each\n// heading carries the unit and says it is an average per bucket. The file name carries the subject,\n// the bucket and the window it covers, so a file found later says which span and which bucket it holds.\nexport function historyExport(i: HistoryExportInputs): WidgetExportTable {\n const bucket = bucketLabel(i.window.intervalSeconds);\n return {\n name: `${i.subject}-avg-per-${bucket}-${stamp(i.window.startTime)}-${stamp(i.window.endTime)}`,\n columns: [i.heading.time, ...i.columns.map((c) => `${columnHeading(c)} ${i.heading.average(bucket)}`)],\n rows: i.rows.map((r) => [\n new Date(r.at).toISOString(),\n ...i.columns.map((c) => {\n const v = r.averages.get(c.name);\n return v === undefined ? null : roundTo(v, c.precision ?? i.precision);\n }),\n ]),\n };\n}\n\n// A date is printed only when it tells the rows apart: a table whose buckets all fall on one day\n// (in the zone shown) prints times; one that crosses midnight prints dates and times.\nexport function spansDays(rows: readonly HistoryRow[], timeZone: string | undefined): boolean {\n if (rows.length < 2) return false;\n const day = (at: number) => new Date(at).toLocaleDateString(undefined, timeZone ? { timeZone } : undefined);\n const first = day(rows[0].at);\n return rows.some((r) => day(r.at) !== first);\n}\n"],
5
+ "mappings": ";;;;;AAYA,SAAS,kBAAkB,iBAA6D;AAOjF,IA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AA,MACvE,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;AAIO,SAAS,UAAU,MAA6B,UAAuC;AAC5F,MAAI,KAAK,SAAS,EAAG,QAAO;AAC5B,QAAM,MAAM,CAAC,OAAe,IAAI,KAAK,EAAE,EAAE,mBAAmB,QAAW,WAAW,EAAE,SAAS,IAAI,MAAS;AAC1G,QAAM,QAAQ,IAAI,KAAK,CAAC,EAAE,EAAE;AAC5B,SAAO,KAAK,KAAK,CAAC,MAAM,IAAI,EAAE,EAAE,MAAM,KAAK;AAC7C;",
6
+ "names": []
7
+ }
@@ -6,22 +6,22 @@ import { viewerLocale } from "@devicechain/widget-sdk";
6
6
  var COMMAND_STRINGS = {
7
7
  en: {
8
8
  send: (label) => `Send ${label}`,
9
- sending: "Sending\u2026",
9
+ sending: "Sending…",
10
10
  noCommand: "No command configured.",
11
- noPermission: "You don\u2019t have permission to issue commands.",
12
- noSeam: "Commands aren\u2019t available in this view.",
11
+ noPermission: "You don’t have permission to issue commands.",
12
+ noSeam: "Commands aren’t available in this view.",
13
13
  noDevice: "No device is selected for this command.",
14
- sendFailed: "Couldn\u2019t issue the command. Try again.",
15
- historyFailed: "Couldn\u2019t load command history.",
16
- loading: "Loading\u2026",
14
+ sendFailed: "Couldn’t issue the command. Try again.",
15
+ historyFailed: "Couldn’t load command history.",
16
+ loading: "Loading…",
17
17
  empty: "No commands issued yet.",
18
- structuredHint: (required) => `${required ? "required " : ""}structured parameter \u2014 not supported here.`,
19
- structured: "Structured parameter \u2014 not supported here",
18
+ structuredHint: (required) => `${required ? "required " : ""}structured parameter — not supported here.`,
19
+ structured: "Structured parameter — not supported here",
20
20
  required: "Required",
21
21
  number: "Must be a number",
22
22
  integer: "Must be a whole number",
23
- minimum: (value) => `Must be \u2265 ${value}`,
24
- maximum: (value) => `Must be \u2264 ${value}`,
23
+ minimum: (value) => `Must be ≥ ${value}`,
24
+ maximum: (value) => `Must be ≤ ${value}`,
25
25
  status: {
26
26
  QUEUED: "Queued",
27
27
  SENT: "Sent",
@@ -36,22 +36,22 @@ var COMMAND_STRINGS = {
36
36
  },
37
37
  es: {
38
38
  send: (label) => `Enviar ${label}`,
39
- sending: "Enviando\u2026",
39
+ sending: "Enviando…",
40
40
  noCommand: "No hay un comando configurado.",
41
41
  noPermission: "No tienes permiso para enviar comandos.",
42
- noSeam: "Los comandos no est\xE1n disponibles en esta vista.",
42
+ noSeam: "Los comandos no están disponibles en esta vista.",
43
43
  noDevice: "No hay un dispositivo seleccionado para este comando.",
44
- sendFailed: "No se pudo enviar el comando. Int\xE9ntalo de nuevo.",
44
+ sendFailed: "No se pudo enviar el comando. Inténtalo de nuevo.",
45
45
  historyFailed: "No se pudo cargar el historial de comandos.",
46
- loading: "Cargando\u2026",
47
- empty: "A\xFAn no se ha enviado ning\xFAn comando.",
48
- structuredHint: (required) => `par\xE1metro estructurado${required ? " obligatorio" : ""} \u2014 no compatible aqu\xED.`,
49
- structured: "Par\xE1metro estructurado \u2014 no compatible aqu\xED",
46
+ loading: "Cargando…",
47
+ empty: "Aún no se ha enviado ningún comando.",
48
+ structuredHint: (required) => `parámetro estructurado${required ? " obligatorio" : ""} — no compatible aquí.`,
49
+ structured: "Parámetro estructurado — no compatible aquí",
50
50
  required: "Obligatorio",
51
- number: "Debe ser un n\xFAmero",
52
- integer: "Debe ser un n\xFAmero entero",
53
- minimum: (value) => `Debe ser \u2265 ${value}`,
54
- maximum: (value) => `Debe ser \u2264 ${value}`,
51
+ number: "Debe ser un número",
52
+ integer: "Debe ser un número entero",
53
+ minimum: (value) => `Debe ser ≥ ${value}`,
54
+ maximum: (value) => `Debe ser ≤ ${value}`,
55
55
  status: {
56
56
  QUEUED: "En cola",
57
57
  SENT: "Enviado",
@@ -63,10 +63,31 @@ var COMMAND_STRINGS = {
63
63
  EXPIRED: "Caducado",
64
64
  CANCELLED: "Cancelado"
65
65
  }
66
+ },
67
+ "zh-CN": {
68
+ send: (label) => `发送 ${label}`,
69
+ sending: "正在发送…",
70
+ noCommand: "尚未配置命令。",
71
+ noPermission: "您没有下发命令的权限。",
72
+ noSeam: "此视图中无法使用命令。",
73
+ noDevice: "尚未为此命令选择设备。",
74
+ sendFailed: "无法下发命令,请重试。",
75
+ historyFailed: "无法加载命令历史记录。",
76
+ loading: "正在加载…",
77
+ empty: "尚未下发任何命令。",
78
+ structuredHint: (required) => `${required ? "必填的" : ""}结构化参数,此处暂不支持。`,
79
+ structured: "结构化参数,此处暂不支持",
80
+ required: "必填",
81
+ number: "必须为数字",
82
+ integer: "必须为整数",
83
+ minimum: (value) => `必须 ≥ ${value}`,
84
+ maximum: (value) => `必须 ≤ ${value}`,
85
+ status: { QUEUED: "已排队", SENT: "已发送", HELD: "已暂缓", PARKED: "已搁置", SUCCESSFUL: "成功", FAILED: "失败", TIMEOUT: "超时", EXPIRED: "已过期", CANCELLED: "已取消" }
66
86
  }
67
87
  };
68
88
  function commandStrings(locale = viewerLocale()) {
69
- return locale?.toLowerCase().split("-")[0] === "es" ? COMMAND_STRINGS.es : COMMAND_STRINGS.en;
89
+ const language = locale?.toLowerCase().split("-")[0];
90
+ return language === "es" ? COMMAND_STRINGS.es : language === "zh" ? COMMAND_STRINGS["zh-CN"] : COMMAND_STRINGS.en;
70
91
  }
71
92
 
72
93
  // src/widgets/command-status.ts
@@ -373,7 +394,7 @@ function ParamInput({
373
394
  }) {
374
395
  if (param.enum && param.enum.length > 0) {
375
396
  return /* @__PURE__ */ jsxs("select", { id, style: inputStyle, value, disabled, onChange: (e) => onChange(e.target.value), children: [
376
- !param.required ? /* @__PURE__ */ jsx("option", { value: "", children: "\u2014" }) : null,
397
+ !param.required ? /* @__PURE__ */ jsx("option", { value: "", children: "—" }) : null,
377
398
  param.enum.map((opt) => /* @__PURE__ */ jsx("option", { value: opt, children: opt }, opt))
378
399
  ] });
379
400
  }
@@ -502,4 +523,4 @@ export {
502
523
  buildPayload,
503
524
  CommandButton
504
525
  };
505
- //# sourceMappingURL=chunk-ZX4K3GT5.js.map
526
+ //# sourceMappingURL=chunk-R2XEYQEJ.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/widgets/command-status.ts", "../../src/command-strings.ts", "../../src/widgets/command-params.ts", "../../src/widgets/command-button.tsx"],
4
+ "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Command delivery-status presentation for the command-button widget (command-delivery\n// lifecycle: QUEUED → SENT → SUCCESSFUL | FAILED, with HELD for a dispatch withheld from\n// a known-absent device, PARKED for one published to a device that turned out to be\n// unreachable, and TIMEOUT / EXPIRED / CANCELLED as the other terminals).\n// Status color is SEMANTIC (good/working/waiting/bad), deliberately fixed rather than\n// derived from the dashboard accent, so the same status reads the same on every theme —\n// and it mirrors the console's DeviceCommandsPanel status variants (success /\n// destructive / outline / in-flight) so an operator reads the same signal on both\n// surfaces.\n\nimport { isTerminalCommandStatus } from '@devicechain/dashboards';\nimport { commandStrings } from '../command-strings';\n\n// 🔴 EVERY STATUS NEEDS AN ENTRY, INCLUDING THE ONES THAT LOOK NEUTRAL. UNKNOWN_COLOR\n// below is the same slate as EXPIRED, so a status with no entry does not merely fall\n// back — it becomes INDISTINGUISHABLE from \"lapsed before it was sent\". HELD and PARKED\n// (the command is still coming) rendered in EXPIRED's slate tell an operator the opposite\n// of the truth, which is why they, and CANCELLED, are spelled out rather than left to the\n// fallback.\n//\n// The scheme is by MEANING, not by lifecycle position: sky = moving under its own steam,\n// amber = waiting on a device that isn't there. HELD and PARKED share the amber family\n// because they are the same answer to \"why hasn't it arrived?\" — the device is away — and\n// take different shades because they are different answers to \"what did the platform\n// already try?\": HELD never left the platform, PARKED was published and found nobody home.\nconst STATUS_COLORS: Record<string, string> = {\n SUCCESSFUL: '#16a34a', // green-600 — acknowledged by the device\n FAILED: '#dc2626', // red-600\n TIMEOUT: '#dc2626', // red-600 — never acknowledged in time\n EXPIRED: '#64748b', // slate-500 — lapsed before it was ever sent\n CANCELLED: '#7c3aed', // violet-600 — deliberately called off; a decision, not a failure\n QUEUED: '#0284c7', // sky-600 — in flight\n SENT: '#0284c7',\n HELD: '#d97706', // amber-600 — withheld: the device is absent, the command still stands\n PARKED: '#f59e0b', // amber-500 — published, nobody home; held for the device's return\n};\n\nconst UNKNOWN_COLOR = '#64748b';\n\n// commandStatusColor maps a status to its badge color, falling back to muted slate for\n// an unrecognized value (a future/hand-edited status).\nexport function commandStatusColor(status: string): string {\n return STATUS_COLORS[status] ?? UNKNOWN_COLOR;\n}\n\n// isTerminalStatus reports whether a command has reached a state it can't leave — the\n// widget stops treating it as in-flight.\n//\n// It is NOT the question \"can this still be cancelled?\": SENT is non-terminal and is not\n// cancellable, so a host gating a cancel control must ask @devicechain/dashboards'\n// isCancellableCommandStatus instead of negating this.\n//\n// It is an alias, not a second definition: the terminal set lives in @devicechain/dashboards\n// so the console, this package and the preview cannot disagree about it. The name is kept\n// because it is part of this package's published surface.\n/** @deprecated Use isTerminalCommandStatus from `@devicechain/dashboards` instead. */\nexport function isTerminalStatus(status: string): boolean {\n return isTerminalCommandStatus(status);\n}\n\n// Known statuses are localized for the viewer; future values keep a readable title-case\n// fallback. The published signature is unchanged: the locale comes from the viewer.\nexport function commandStatusLabel(status: string): string {\n return commandStatusLabelIn(status);\n}\n\n/** commandStatusLabel for an explicit locale (module-internal; not part of the package API). */\nexport function commandStatusLabelIn(status: string, locale?: string): string {\n if (!status) return '';\n return commandStrings(locale).status[status]\n ?? status.charAt(0).toUpperCase() + status.slice(1).toLowerCase().replace(/_/g, ' ');\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { viewerLocale } from '@devicechain/widget-sdk';\n\ninterface CommandStrings {\n send: (label: string) => string;\n sending: string;\n noCommand: string;\n noPermission: string;\n noSeam: string;\n noDevice: string;\n sendFailed: string;\n historyFailed: string;\n loading: string;\n empty: string;\n structuredHint: (required: boolean) => string;\n structured: string;\n required: string;\n number: string;\n integer: string;\n minimum: (value: number) => string;\n maximum: (value: number) => string;\n status: Record<string, string>;\n}\n\nconst COMMAND_STRINGS: Record<'en' | 'es' | 'zh-CN', CommandStrings> = {\n en: {\n send: (label) => `Send ${label}`,\n sending: 'Sending…',\n noCommand: 'No command configured.',\n noPermission: 'You don’t have permission to issue commands.',\n noSeam: 'Commands aren’t available in this view.',\n noDevice: 'No device is selected for this command.',\n sendFailed: 'Couldn’t issue the command. Try again.',\n historyFailed: 'Couldn’t load command history.',\n loading: 'Loading…',\n empty: 'No commands issued yet.',\n structuredHint: (required) => `${required ? 'required ' : ''}structured parameter — not supported here.`,\n structured: 'Structured parameter — not supported here',\n required: 'Required',\n number: 'Must be a number',\n integer: 'Must be a whole number',\n minimum: (value) => `Must be ≥ ${value}`,\n maximum: (value) => `Must be ≤ ${value}`,\n status: {\n QUEUED: 'Queued', SENT: 'Sent', HELD: 'Held', PARKED: 'Parked',\n SUCCESSFUL: 'Successful', FAILED: 'Failed', TIMEOUT: 'Timeout',\n EXPIRED: 'Expired', CANCELLED: 'Cancelled',\n },\n },\n es: {\n send: (label) => `Enviar ${label}`,\n sending: 'Enviando…',\n noCommand: 'No hay un comando configurado.',\n noPermission: 'No tienes permiso para enviar comandos.',\n noSeam: 'Los comandos no están disponibles en esta vista.',\n noDevice: 'No hay un dispositivo seleccionado para este comando.',\n sendFailed: 'No se pudo enviar el comando. Inténtalo de nuevo.',\n historyFailed: 'No se pudo cargar el historial de comandos.',\n loading: 'Cargando…',\n empty: 'Aún no se ha enviado ningún comando.',\n structuredHint: (required) => `parámetro estructurado${required ? ' obligatorio' : ''} — no compatible aquí.`,\n structured: 'Parámetro estructurado — no compatible aquí',\n required: 'Obligatorio',\n number: 'Debe ser un número',\n integer: 'Debe ser un número entero',\n minimum: (value) => `Debe ser ≥ ${value}`,\n maximum: (value) => `Debe ser ≤ ${value}`,\n status: {\n QUEUED: 'En cola', SENT: 'Enviado', HELD: 'Retenido', PARKED: 'En espera',\n SUCCESSFUL: 'Exitoso', FAILED: 'Fallido', TIMEOUT: 'Tiempo agotado',\n EXPIRED: 'Caducado', CANCELLED: 'Cancelado',\n },\n },\n 'zh-CN': {\n send: (label) => `发送 ${label}`, sending: '正在发送…', noCommand: '尚未配置命令。',\n noPermission: '您没有下发命令的权限。', noSeam: '此视图中无法使用命令。', noDevice: '尚未为此命令选择设备。',\n sendFailed: '无法下发命令,请重试。', historyFailed: '无法加载命令历史记录。', loading: '正在加载…', empty: '尚未下发任何命令。',\n structuredHint: (required) => `${required ? '必填的' : ''}结构化参数,此处暂不支持。`,\n structured: '结构化参数,此处暂不支持', required: '必填', number: '必须为数字', integer: '必须为整数',\n minimum: (value) => `必须 ≥ ${value}`, maximum: (value) => `必须 ≤ ${value}`,\n status: { QUEUED: '已排队', SENT: '已发送', HELD: '已暂缓', PARKED: '已搁置', SUCCESSFUL: '成功', FAILED: '失败', TIMEOUT: '超时', EXPIRED: '已过期', CANCELLED: '已取消' },\n },\n};\n\nexport function commandStrings(locale: string | undefined = viewerLocale()): CommandStrings {\n const language = locale?.toLowerCase().split('-')[0];\n return language === 'es' ? COMMAND_STRINGS.es : language === 'zh' ? COMMAND_STRINGS['zh-CN'] : COMMAND_STRINGS.en;\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Pure form logic for the command-button widget's typed parameter form (ADR-043). The\n// console bakes a command definition's `parameterSchema` (a JSON string) into the\n// widget's options; these helpers parse it, seed defaults, validate operator input, and\n// serialize the typed values back to the JSON payload command-delivery sends the device.\n// Kept separate from the widget so the coercion/validation is unit-tested in isolation.\n//\n// SCOPE: the form types top-level SCALAR parameters (DOUBLE / INT / BOOLEAN / STRING,\n// with enum / bounds / required / default). OBJECT (nested) parameters are not\n// form-editable — the form blocks sending when one is REQUIRED (it can't be satisfied\n// here) and otherwise omits it. The payload is a flat JSON object keyed by parameter name.\n\nimport type { CommandParameter } from '@devicechain/dashboards';\nimport { commandStrings } from '../command-strings';\n\nconst DATA_TYPES = new Set(['DOUBLE', 'INT', 'BOOLEAN', 'STRING']);\n\n// parseParameterSchema turns the baked JSON string into descriptors, defensively:\n// a null/empty/malformed schema (or a non-array root) yields an empty list so a command\n// with no arguments (or a hand-broken schema) renders as a bare Send button, never throws.\n// Each descriptor is NORMALIZED (enum→string[], default→string, bounds→finite number,\n// kind/dataType→known value) so a hand-edited dashboard definition with wrong-typed fields\n// (e.g. `enum: \"on\"` or `default: 5`) can't crash the form at render/send time.\nexport function parseParameterSchema(schema: string | null | undefined): CommandParameter[] {\n if (!schema) return [];\n let parsed: unknown;\n try {\n parsed = JSON.parse(schema);\n } catch {\n return [];\n }\n if (!Array.isArray(parsed)) return [];\n const out: CommandParameter[] = [];\n for (const raw of parsed) {\n const norm = normalizeParam(raw);\n if (norm) out.push(norm);\n }\n return out;\n}\n\n// normalizeParam validates one descriptor and coerces every field to its expected type,\n// dropping the descriptor entirely if it has no string `name`. Unknown/wrong-typed fields\n// are discarded rather than trusted, so downstream code never sees a non-array enum or a\n// numeric default.\nfunction normalizeParam(raw: unknown): CommandParameter | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const r = raw as Record<string, unknown>;\n if (typeof r.name !== 'string') return null;\n\n const param: CommandParameter = { name: r.name };\n if (typeof r.description === 'string') param.description = r.description;\n if (r.kind === 'OBJECT') param.kind = 'OBJECT';\n else if (r.kind === 'SCALAR') param.kind = 'SCALAR';\n if (typeof r.dataType === 'string' && DATA_TYPES.has(r.dataType)) {\n param.dataType = r.dataType as CommandParameter['dataType'];\n }\n if (typeof r.unit === 'string') param.unit = r.unit;\n if (r.required === true) param.required = true;\n if (typeof r.default === 'string') param.default = r.default;\n if (typeof r.minValue === 'number' && Number.isFinite(r.minValue)) param.minValue = r.minValue;\n if (typeof r.maxValue === 'number' && Number.isFinite(r.maxValue)) param.maxValue = r.maxValue;\n if (Array.isArray(r.enum)) {\n const values = r.enum.filter((v): v is string => typeof v === 'string');\n if (values.length > 0) param.enum = values;\n }\n return param;\n}\n\n// isScalar reports whether a parameter is a typed single value the form renders an input\n// for. Kind absent means SCALAR (the Go default); only an explicit OBJECT is nested.\nexport function isScalar(param: CommandParameter): boolean {\n return param.kind !== 'OBJECT';\n}\n\n// parseBool interprets a schema/string boolean the way the server's strconv.ParseBool\n// does (accepting '1'/'t'/'true'/'yes'/'on', case-insensitively) so a definition default\n// of \"True\" doesn't silently render — and send — as false.\nexport function parseBool(raw: string): boolean {\n const s = raw.trim().toLowerCase();\n return s === 'true' || s === '1' || s === 't' || s === 'yes' || s === 'on';\n}\n\n// defaultValues seeds the form's value map from each scalar parameter. A BOOLEAN always\n// gets a concrete 'true'/'false' (default false) — a checkbox is never \"empty\", so the\n// value must reflect the box's state exactly. Other scalars seed from their declared\n// default (as a string — inputs are string-backed), else start empty.\nexport function defaultValues(params: CommandParameter[]): Record<string, string> {\n const values: Record<string, string> = {};\n for (const p of params) {\n if (!isScalar(p)) continue;\n if (p.dataType === 'BOOLEAN') values[p.name] = parseBool(p.default ?? '') ? 'true' : 'false';\n else if (p.default != null) values[p.name] = p.default;\n }\n return values;\n}\n\n// validateParams returns a per-parameter error map (empty = valid). It enforces required\n// (a missing value on a required scalar; a BOOLEAN always has a value so is never\n// \"required-missing\"), numeric validity/bounds for INT/DOUBLE, and blocks a REQUIRED\n// OBJECT parameter (it can't be supplied through the typed form).\nexport function validateParams(params: CommandParameter[], values: Record<string, string>): Record<string, string> {\n return validateParamsIn(params, values);\n}\n\n/** validateParams for an explicit locale (module-internal; not part of the package API). */\nexport function validateParamsIn(\n params: CommandParameter[],\n values: Record<string, string>,\n locale?: string,\n): Record<string, string> {\n const strings = commandStrings(locale);\n const errors: Record<string, string> = {};\n for (const p of params) {\n if (!isScalar(p)) {\n // A required structured parameter can't be satisfied here — refuse to send an\n // incomplete command rather than silently omitting it.\n if (p.required) errors[p.name] = strings.structured;\n continue;\n }\n if (p.dataType === 'BOOLEAN') continue; // a checkbox always carries a valid value\n const raw = (values[p.name] ?? '').trim();\n if (raw === '') {\n if (p.required) errors[p.name] = strings.required;\n continue; // an empty optional value is fine — it's just omitted from the payload\n }\n if (p.dataType === 'INT' || p.dataType === 'DOUBLE') {\n const n = Number(raw);\n if (!Number.isFinite(n)) {\n errors[p.name] = strings.number;\n } else if (p.dataType === 'INT' && !Number.isInteger(n)) {\n errors[p.name] = strings.integer;\n } else if (p.minValue != null && n < p.minValue) {\n errors[p.name] = strings.minimum(p.minValue);\n } else if (p.maxValue != null && n > p.maxValue) {\n errors[p.name] = strings.maximum(p.maxValue);\n }\n }\n }\n return errors;\n}\n\n// buildPayload serializes the typed values to the JSON payload string command-delivery\n// sends the device — coercing each scalar to its declared type (INT/DOUBLE → number,\n// BOOLEAN → boolean, STRING → string). A BOOLEAN is always included (its checkbox state\n// is meaningful); other empty optional values are omitted. OBJECT parameters are omitted\n// (validateParams blocks a required one first). Returns undefined when no parameter\n// contributes a value (a parameterless command sends no payload).\nexport function buildPayload(\n params: CommandParameter[],\n values: Record<string, string>,\n): string | undefined {\n const payload: Record<string, unknown> = {};\n for (const p of params) {\n if (!isScalar(p)) continue;\n const raw = (values[p.name] ?? '').trim();\n if (p.dataType === 'BOOLEAN') {\n payload[p.name] = parseBool(raw);\n continue;\n }\n if (raw === '') continue;\n payload[p.name] = coerce(p, raw);\n }\n return Object.keys(payload).length === 0 ? undefined : JSON.stringify(payload);\n}\n\nfunction coerce(param: CommandParameter, raw: string): unknown {\n switch (param.dataType) {\n case 'INT':\n case 'DOUBLE': {\n const n = Number(raw);\n return Number.isFinite(n) ? n : raw; // validation gates this; fall back to raw defensively\n }\n case 'BOOLEAN':\n return parseBool(raw);\n default:\n return raw; // STRING (and untyped)\n }\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// command-button — issue a device command from the dashboard and watch its delivery\n// lifecycle (command-delivery). The console bakes a command definition into the widget's\n// options at author time (its name + parameterSchema); this renders a typed form from\n// that schema, issues via the action seam (gated on command:write), and shows the recent\n// commands for the target device with live status (QUEUED → SENT →\n// SUCCESSFUL / FAILED …), so an operator can see whether a command was acted on rather\n// than only that it was sent. Bound through the hub's control channel, so it renders identically from live\n// data or the synthetic preview source.\n//\n// The baked schema is a SNAPSHOT taken when the author picked the command: a later edit\n// to the profile's command definition (a changed schema, or a deleted command) leaves\n// this widget's form stale until the author re-picks it. That's acceptable — dashboards\n// are opaque snapshots — and a since-removed command fails visibly at the delivery\n// boundary (the server validates device existence and JSON); it isn't silently wrong.\n\nimport type { CommandDispatch, CommandParameter } from '@devicechain/dashboards';\nimport { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';\n\nimport {\n type CommandStreamState,\n css,\n fontVar,\n formatDateTime,\n optString,\n useWidgetTimeZone,\n WidgetFrame,\n type WidgetProps,\n} from '@devicechain/widget-sdk';\n\nimport { commandStatusColor, commandStatusLabel } from './command-status';\nimport { commandStrings } from '../command-strings';\nimport {\n buildPayload,\n defaultValues,\n isScalar,\n parseBool,\n parseParameterSchema,\n validateParams,\n} from './command-params';\n\nexport function CommandButton({ widget, data, actions }: WidgetProps<CommandStreamState>) {\n const strings = commandStrings();\n const commandName = optString(widget.options, 'commandName');\n const commandLabel = optString(widget.options, 'commandLabel') ?? commandName;\n const parameterSchema = optString(widget.options, 'parameterSchema') ?? null;\n\n const params = useMemo(() => parseParameterSchema(parameterSchema), [parameterSchema]);\n // A stable key over the configured command: reset the form when the author repoints\n // the widget at a different command (or edits its schema).\n const schemaKey = `${commandName ?? ''}::${parameterSchema ?? ''}`;\n\n const [values, setValues] = useState<Record<string, string>>(() => defaultValues(params));\n const [errors, setErrors] = useState<Record<string, string>>({});\n const [pending, setPending] = useState(false);\n const [sendError, setSendError] = useState<string | null>(null);\n const [sentToken, setSentToken] = useState<string | null>(null);\n // Bumped whenever the configured command changes; an in-flight send captures the\n // current value and drops its result if it settles after a repoint (so command A's\n // dispatch token/error can't land under a freshly-configured command B).\n const sendGen = useRef(0);\n\n // Reset the form to the schema's defaults whenever the configured command changes.\n useEffect(() => {\n sendGen.current += 1;\n setValues(defaultValues(params));\n setErrors({});\n setSendError(null);\n setSentToken(null);\n // params is derived from schemaKey; keying on schemaKey avoids re-running on an\n // equal-but-new params array reference.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [schemaKey]);\n\n const canWrite = actions?.can('command:write') ?? false;\n const hasSeam = typeof actions?.sendCommand === 'function';\n // A viewer the host KNOWS lacks command:write (a host supplied the seam and said no) is not\n // offered the control. A mount with no seam at all (a preview, the widget gallery) still shows\n // the form, disabled, so the author can see what the widget looks like.\n const denied = !!actions && !canWrite;\n const deviceToken = data.deviceToken;\n // The form is operable only when the viewer may write AND the runtime supplies the send\n // seam; a read-only mount shows the form disabled. Sending additionally needs a bound\n // target device and a configured command.\n const formDisabled = !canWrite || !hasSeam || pending;\n const canSend = !formDisabled && !!deviceToken && !!commandName;\n\n const setField = (name: string, value: string) => {\n setValues((prev) => ({ ...prev, [name]: value }));\n // Clear a field's error as the operator edits it.\n setErrors((prev) => (prev[name] ? { ...prev, [name]: '' } : prev));\n setSendError(null);\n };\n\n const send = () => {\n if (!deviceToken || !commandName || !actions?.sendCommand) return;\n const found = validateParams(params, values);\n const active = Object.fromEntries(Object.entries(found).filter(([, v]) => v));\n if (Object.keys(active).length > 0) {\n setErrors(active);\n return;\n }\n const payload = buildPayload(params, values);\n const gen = sendGen.current; // capture: drop the result if the command is repointed mid-flight\n setPending(true);\n setSendError(null);\n // Call synchronously so a dispatch is observable, but guard a synchronous throw so a\n // misbehaving seam can't leave the button stuck-disabled.\n let promise: Promise<CommandDispatch>;\n try {\n promise = actions.sendCommand(deviceToken, commandName, payload);\n } catch {\n setSendError(strings.sendFailed);\n setPending(false);\n return;\n }\n promise\n .then((dispatch) => {\n if (gen !== sendGen.current) return;\n // 🔴 A REFUSAL IS SHOWN, A FAILURE IS NOT. The server decided this command was\n // wrong and said why in client-safe terms (an unknown command for this device, a\n // parameter that violates the schema, the tenant's held-command ceiling) — that\n // reason is the whole point of the answer, and an operator can act on it. A\n // thrown error, below, is an availability failure: it says nothing about the\n // command, and its text is internal, so it gets one fixed message instead.\n if (dispatch.status === 'rejected') {\n setSendError(dispatch.reason);\n return;\n }\n setSentToken(dispatch.token);\n })\n .catch(() => {\n if (gen === sendGen.current) setSendError(strings.sendFailed);\n })\n .finally(() => {\n if (gen === sendGen.current) setPending(false);\n });\n };\n\n return (\n <WidgetFrame title={optString(widget.options, 'title')}>\n {/* A short widget (its minimum is two rows, and a cell on a phone is ~56 px) scrolls the\n form down rather than cutting off the send button or the line explaining why it is off. */}\n <div style={{ display: 'flex', flexDirection: 'column', height: '100%', gap: 10, overflowY: 'auto' }}>\n {!commandName ? (\n <div style={{ ...hint, margin: 'auto' }}>{strings.noCommand}</div>\n ) : denied ? (\n // A viewer without command:write is not offered the control at all: a form and a\n // Send button that can never work read as a broken board. The reason stands in its\n // place, and the delivery history (read-only) stays.\n <>\n <div role=\"note\" style={{ ...hint, flexShrink: 0 }}>\n {strings.noPermission}\n </div>\n <CommandHistory commands={data.commands} sentToken={sentToken} loading={data.loading} error={data.error} />\n </>\n ) : (\n <>\n {/* Typed parameter form. */}\n <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flexShrink: 0 }}>\n {params.map((param) =>\n isScalar(param) ? (\n <ParamField\n key={param.name}\n widgetId={widget.id}\n param={param}\n value={values[param.name] ?? ''}\n error={errors[param.name]}\n disabled={formDisabled}\n onChange={(v) => setField(param.name, v)}\n />\n ) : (\n // A structured (OBJECT) parameter isn't form-editable. A REQUIRED one\n // blocks sending (validateParams flags it); flag that in the note.\n <div key={param.name} style={{ ...hint, color: param.required ? commandStatusColor('FAILED') : css('muted-foreground') }}>\n {param.name}: {strings.structuredHint(!!param.required)}\n </div>\n ),\n )}\n\n <button\n type=\"button\"\n style={{ ...sendButton, opacity: canSend ? 1 : 0.55, cursor: canSend ? 'pointer' : 'not-allowed' }}\n disabled={!canSend}\n aria-busy={pending}\n onClick={send}\n >\n {pending ? strings.sending : strings.send(commandLabel ?? '')}\n </button>\n\n {!canWrite ? (\n <div style={hint}>{strings.noPermission}</div>\n ) : !hasSeam ? (\n <div style={hint}>{strings.noSeam}</div>\n ) : !deviceToken ? (\n <div style={hint}>{strings.noDevice}</div>\n ) : null}\n {sendError ? (\n <div role=\"alert\" style={{ ...hint, color: commandStatusColor('FAILED') }}>\n {sendError}\n </div>\n ) : null}\n </div>\n\n {/* Recent-command history with live delivery status. */}\n <CommandHistory commands={data.commands} sentToken={sentToken} loading={data.loading} error={data.error} />\n </>\n )}\n </div>\n </WidgetFrame>\n );\n}\n\n// ── Parameter field ──────────────────────────────────────────────────────\n\nfunction ParamField({\n widgetId,\n param,\n value,\n error,\n disabled,\n onChange,\n}: {\n widgetId: string;\n param: CommandParameter;\n value: string;\n error?: string;\n disabled: boolean;\n onChange: (value: string) => void;\n}) {\n // Scope the input id to the widget so two command-buttons sharing a parameter name\n // don't produce duplicate DOM ids (which would misdirect a label click to the first).\n const labelId = `cmd-${widgetId}-${param.name}`;\n const unit = param.unit ? ` (${param.unit})` : '';\n return (\n <label htmlFor={labelId} style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>\n <span style={{ fontSize: fontVar('sm'), color: css('muted-foreground') }}>\n {param.name}\n {unit}\n {param.required ? <span style={{ color: commandStatusColor('FAILED') }}> *</span> : null}\n </span>\n <ParamInput id={labelId} param={param} value={value} disabled={disabled} onChange={onChange} />\n {error ? (\n <span style={{ fontSize: fontVar('xs'), color: commandStatusColor('FAILED') }}>{error}</span>\n ) : null}\n </label>\n );\n}\n\nfunction ParamInput({\n id,\n param,\n value,\n disabled,\n onChange,\n}: {\n id: string;\n param: CommandParameter;\n value: string;\n disabled: boolean;\n onChange: (value: string) => void;\n}) {\n // An enum (of any data type) → a select; a boolean → a checkbox; a number → a numeric\n // input with the declared bounds; everything else → text.\n if (param.enum && param.enum.length > 0) {\n return (\n <select id={id} style={inputStyle} value={value} disabled={disabled} onChange={(e) => onChange(e.target.value)}>\n {!param.required ? <option value=\"\">—</option> : null}\n {param.enum.map((opt) => (\n <option key={opt} value={opt}>\n {opt}\n </option>\n ))}\n </select>\n );\n }\n if (param.dataType === 'BOOLEAN') {\n return (\n <input\n id={id}\n type=\"checkbox\"\n style={{ width: 16, height: 16 }}\n checked={parseBool(value)}\n disabled={disabled}\n onChange={(e) => onChange(e.target.checked ? 'true' : 'false')}\n />\n );\n }\n const numeric = param.dataType === 'INT' || param.dataType === 'DOUBLE';\n return (\n <input\n id={id}\n type={numeric ? 'number' : 'text'}\n style={inputStyle}\n value={value}\n disabled={disabled}\n min={param.minValue ?? undefined}\n max={param.maxValue ?? undefined}\n step={param.dataType === 'INT' ? 1 : 'any'}\n placeholder={param.default ?? undefined}\n onChange={(e) => onChange(e.target.value)}\n />\n );\n}\n\n// ── History ────────────────────────────────────────────────────────────────\n\nfunction CommandHistory({\n commands,\n sentToken,\n loading,\n error,\n}: {\n commands: CommandStreamState['commands'];\n sentToken: string | null;\n loading: boolean;\n error: unknown;\n}) {\n // An error is shown inline here (not by replacing the whole widget) so a transient poll\n // blip never tears down the still-usable send form. Last-good rows stay on screen when\n // present; only an empty-and-errored history shows the notice.\n const empty = commands.length === 0;\n const strings = commandStrings();\n const timeZone = useWidgetTimeZone();\n return (\n <div\n style={{\n flex: 1,\n minHeight: 0,\n overflow: 'auto',\n borderTop: `1px solid ${css('border')}`,\n paddingTop: 6,\n }}\n >\n {empty ? (\n <div style={{ ...hint, textAlign: 'center', color: error ? commandStatusColor('FAILED') : css('muted-foreground') }}>\n {error ? strings.historyFailed : loading ? strings.loading : strings.empty}\n </div>\n ) : (\n <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 4 }}>\n {commands.map((command) => (\n <li\n key={command.token}\n style={{\n display: 'flex',\n alignItems: 'center',\n gap: 8,\n fontSize: fontVar('sm'),\n // Highlight the command just issued from this widget.\n fontWeight: command.token === sentToken ? 600 : 400,\n }}\n >\n <StatusBadge status={command.status} />\n <span style={{ color: css('foreground'), whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>\n {command.name}\n </span>\n <span style={{ marginLeft: 'auto', color: css('muted-foreground'), whiteSpace: 'nowrap' }}>\n {formatDateTime(command.queuedTime, timeZone)}\n </span>\n </li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n\nfunction StatusBadge({ status }: { status: string }) {\n const color = commandStatusColor(status);\n return (\n <span\n style={{\n display: 'inline-flex',\n alignItems: 'center',\n gap: 4,\n flexShrink: 0,\n fontSize: fontVar('xs'),\n fontWeight: 600,\n color,\n }}\n >\n <span aria-hidden=\"true\" style={{ width: 7, height: 7, borderRadius: '50%', background: color }} />\n {commandStatusLabel(status)}\n </span>\n );\n}\n\n// ── styles / helpers ─────────────────────────────────────────────────────\n\nconst hint: CSSProperties = { fontSize: fontVar('xs'), color: css('muted-foreground') };\n\nconst inputStyle: CSSProperties = {\n width: '100%',\n boxSizing: 'border-box',\n padding: '4px 8px',\n fontSize: fontVar('md'),\n borderRadius: 4,\n border: `1px solid ${css('border')}`,\n background: css('background'),\n color: css('foreground'),\n};\n\nconst sendButton: CSSProperties = {\n padding: '6px 12px',\n fontSize: fontVar('md'),\n fontWeight: 600,\n borderRadius: 4,\n border: 'none',\n background: css('primary'),\n color: css('background'),\n marginTop: 2,\n};\n"],
5
+ "mappings": ";AAaA,SAAS,+BAA+B;;;ACVxC,SAAS,oBAAoB;AAuB7B,IAAM,kBAAiE;AAAA,EACrE,IAAI;AAAA,IACF,MAAM,CAAC,UAAU,QAAQ,KAAK;AAAA,IAC9B,SAAS;AAAA,IACT,WAAW;AAAA,IACX,cAAc;AAAA,IACd,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,YAAY;AAAA,IACZ,eAAe;AAAA,IACf,SAAS;AAAA,IACT,OAAO;AAAA,IACP,gBAAgB,CAAC,aAAa,GAAG,WAAW,cAAc,EAAE;AAAA,IAC5D,YAAY;AAAA,IACZ,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,SAAS,CAAC,UAAU,aAAa,KA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AI,kBAAkB,EAAE;AAEtF,IAAM,aAA4B;AAAA,EAChC,OAAO;AAAA,EACP,WAAW;AAAA,EACX,SAAS;AAAA,EACT,UAAU,QAAQ,IAAI;AAAA,EACtB,cAAc;AAAA,EACd,QAAQ,aAAa,IAAI,QAAQ,CAAC;AAAA,EAClC,YAAY,IAAI,YAAY;AAAA,EAC5B,OAAO,IAAI,YAAY;AACzB;AAEA,IAAM,aAA4B;AAAA,EAChC,SAAS;AAAA,EACT,UAAU,QAAQ,IAAI;AAAA,EACtB,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,QAAQ;AAAA,EACR,YAAY,IAAI,SAAS;AAAA,EACzB,OAAO,IAAI,YAAY;AAAA,EACvB,WAAW;AACb;",
6
+ "names": []
7
+ }
@@ -45,4 +45,4 @@ export {
45
45
  lastReadingHint,
46
46
  NoReading
47
47
  };
48
- //# sourceMappingURL=chunk-JVC6JYUR.js.map
48
+ //# sourceMappingURL=chunk-RLVZXNPJ.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/no-reading-core.tsx"],
4
- "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// What a single-device widget shows when it has no reading to draw, and WHY. One decision shared by\n// every built-in, so a board does not explain the same absence three ways:\n//\n// the slot has no device bound -> unbound\n// the device's active profile does not declare it -> not-reported (it will never report this)\n// otherwise -> no-data (declared, but nothing in the window)\n//\n// \"Declared\" is asked of the host only when this renders (useWidgetDeclaredMetrics.ask), so a board\n// whose widgets have data pays nothing. While the answer is pending, or when the host cannot give\n// one, the declaration is unknown, and unknown is read as declared: the widget says \"no data\" rather\n// than confidently claiming the device never reports it. A reading of the measurement that the\n// widget does hold (outside its window) proves the device reports it, whatever the profile says.\n//\n// It is apart from no-reading.tsx (the level and fleet wrappers) so a widget needing only this,\n// the table, does not pull the wrappers' imports into its chunk: that one edge moved part of the\n// first download into a chunk of its own in the replay build, about 600 B gzip.\n\nimport type { MeasurementSample } from '@devicechain/dashboards';\nimport { formatAge, formatValue, useWidgetDeclaredMetrics } from '@devicechain/widget-sdk';\nimport { lastValueHint, WidgetEmptyState, type WidgetEmptyKind } from '@devicechain/widget-sdk/empty-state';\nimport { useEffect, useState } from 'react';\n\n// How long a widget stays empty before it asks the host what the device's profile declares.\nexport const ASK_DELAY_MS = 300;\n\n// How long a widget with no reading stays blank before it says why. A board that is loading has no\n// reading yet, and \"nothing was reported in this range\" would be false for the moment it takes the\n// first one to arrive. A caller that has already waited (or knows the read has settled) passes 0.\nexport const SETTLE_MS = 1500;\n\nexport function emptyKindFor(input: {\n unbound: boolean;\n measurement: string | undefined;\n declared: readonly string[] | null | undefined;\n // The widget holds a reading of the measurement (outside what it shows): the device reports it.\n reported?: boolean;\n}): Extract<WidgetEmptyKind, 'unbound' | 'not-reported' | 'no-data'> {\n if (input.unbound) return 'unbound';\n if (input.reported) return 'no-data';\n if (input.measurement !== undefined && input.declared && !input.declared.includes(input.measurement)) return 'not-reported';\n return 'no-data';\n}\n\n// \"Last value 21.4 \u00B0C \u00B7 3 days ago\", for a reading that exists but lies outside what the widget shows.\nexport function lastReadingHint(\n sample: MeasurementSample | undefined,\n options: { unit?: string; precision?: number; now?: number } = {},\n): string | undefined {\n if (!sample || sample.value == null) return undefined;\n const value = formatValue(sample.value, options.precision);\n const at = sample.occurredTime ? Date.parse(sample.occurredTime) : NaN;\n if (Number.isNaN(at)) return undefined;\n const age = Math.max(0, Math.floor(((options.now ?? Date.now()) - at) / 1000));\n return lastValueHint(options.unit ? `${value} ${options.unit}` : value, formatAge(age));\n}\n\nexport interface NoReadingProps {\n // The slot has no device bound.\n unbound: boolean;\n // The measurement the widget was asked for; undefined when it shows whatever arrives.\n measurement: string | undefined;\n // A reading known to exist but outside the window, shown as the hint of a no-data state.\n lastSample?: MeasurementSample;\n unit?: string;\n precision?: number;\n // Replaces the stock no-data explanation (a stat card's \"No readings in the last 1h\").\n detail?: string;\n // How long to stay blank before explaining (SETTLE_MS when omitted). An unbound slot never waits.\n waitMs?: number;\n}\n\nexport function NoReading({ unbound, measurement, lastSample, unit, precision, detail, waitMs = SETTLE_MS }: NoReadingProps) {\n const { declared, ask } = useWidgetDeclaredMetrics();\n const [settled, setSettled] = useState(waitMs <= 0);\n useEffect(() => {\n if (settled || unbound) return;\n const timer = setTimeout(() => setSettled(true), waitMs);\n return () => clearTimeout(timer);\n }, [settled, unbound, waitMs]);\n // After a moment, not at once: on a board that is loading, the reading is about to arrive and the\n // lookup would be for nothing.\n useEffect(() => {\n if (unbound || measurement === undefined) return;\n const timer = setTimeout(ask, ASK_DELAY_MS);\n return () => clearTimeout(timer);\n }, [ask, unbound, measurement]);\n if (!unbound && !settled) return <div data-empty-pending=\"\" aria-hidden=\"true\" style={{ width: '100%', height: '100%' }} />;\n const kind = emptyKindFor({ unbound, measurement, declared, reported: lastSample !== undefined });\n const hint = kind === 'no-data' ? lastReadingHint(lastSample, { unit, precision }) : undefined;\n return <WidgetEmptyState kind={kind} measurement={measurement} hint={hint} detail={kind === 'no-data' ? detail : undefined} />;\n}\n\n"],
4
+ "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// What a single-device widget shows when it has no reading to draw, and WHY. One decision shared by\n// every built-in, so a board does not explain the same absence three ways:\n//\n// the slot has no device bound -> unbound\n// the device's active profile does not declare it -> not-reported (it will never report this)\n// otherwise -> no-data (declared, but nothing in the window)\n//\n// \"Declared\" is asked of the host only when this renders (useWidgetDeclaredMetrics.ask), so a board\n// whose widgets have data pays nothing. While the answer is pending, or when the host cannot give\n// one, the declaration is unknown, and unknown is read as declared: the widget says \"no data\" rather\n// than confidently claiming the device never reports it. A reading of the measurement that the\n// widget does hold (outside its window) proves the device reports it, whatever the profile says.\n//\n// It is apart from no-reading.tsx (the level and fleet wrappers) so a widget needing only this,\n// the table, does not pull the wrappers' imports into its chunk: that one edge moved part of the\n// first download into a chunk of its own in the replay build, about 600 B gzip.\n\nimport type { MeasurementSample } from '@devicechain/dashboards';\nimport { formatAge, formatValue, useWidgetDeclaredMetrics } from '@devicechain/widget-sdk';\nimport { lastValueHint, WidgetEmptyState, type WidgetEmptyKind } from '@devicechain/widget-sdk/empty-state';\nimport { useEffect, useState } from 'react';\n\n// How long a widget stays empty before it asks the host what the device's profile declares.\nexport const ASK_DELAY_MS = 300;\n\n// How long a widget with no reading stays blank before it says why. A board that is loading has no\n// reading yet, and \"nothing was reported in this range\" would be false for the moment it takes the\n// first one to arrive. A caller that has already waited (or knows the read has settled) passes 0.\nexport const SETTLE_MS = 1500;\n\nexport function emptyKindFor(input: {\n unbound: boolean;\n measurement: string | undefined;\n declared: readonly string[] | null | undefined;\n // The widget holds a reading of the measurement (outside what it shows): the device reports it.\n reported?: boolean;\n}): Extract<WidgetEmptyKind, 'unbound' | 'not-reported' | 'no-data'> {\n if (input.unbound) return 'unbound';\n if (input.reported) return 'no-data';\n if (input.measurement !== undefined && input.declared && !input.declared.includes(input.measurement)) return 'not-reported';\n return 'no-data';\n}\n\n// \"Last value 21.4 °C · 3 days ago\", for a reading that exists but lies outside what the widget shows.\nexport function lastReadingHint(\n sample: MeasurementSample | undefined,\n options: { unit?: string; precision?: number; now?: number } = {},\n): string | undefined {\n if (!sample || sample.value == null) return undefined;\n const value = formatValue(sample.value, options.precision);\n const at = sample.occurredTime ? Date.parse(sample.occurredTime) : NaN;\n if (Number.isNaN(at)) return undefined;\n const age = Math.max(0, Math.floor(((options.now ?? Date.now()) - at) / 1000));\n return lastValueHint(options.unit ? `${value} ${options.unit}` : value, formatAge(age));\n}\n\nexport interface NoReadingProps {\n // The slot has no device bound.\n unbound: boolean;\n // The measurement the widget was asked for; undefined when it shows whatever arrives.\n measurement: string | undefined;\n // A reading known to exist but outside the window, shown as the hint of a no-data state.\n lastSample?: MeasurementSample;\n unit?: string;\n precision?: number;\n // Replaces the stock no-data explanation (a stat card's \"No readings in the last 1h\").\n detail?: string;\n // How long to stay blank before explaining (SETTLE_MS when omitted). An unbound slot never waits.\n waitMs?: number;\n}\n\nexport function NoReading({ unbound, measurement, lastSample, unit, precision, detail, waitMs = SETTLE_MS }: NoReadingProps) {\n const { declared, ask } = useWidgetDeclaredMetrics();\n const [settled, setSettled] = useState(waitMs <= 0);\n useEffect(() => {\n if (settled || unbound) return;\n const timer = setTimeout(() => setSettled(true), waitMs);\n return () => clearTimeout(timer);\n }, [settled, unbound, waitMs]);\n // After a moment, not at once: on a board that is loading, the reading is about to arrive and the\n // lookup would be for nothing.\n useEffect(() => {\n if (unbound || measurement === undefined) return;\n const timer = setTimeout(ask, ASK_DELAY_MS);\n return () => clearTimeout(timer);\n }, [ask, unbound, measurement]);\n if (!unbound && !settled) return <div data-empty-pending=\"\" aria-hidden=\"true\" style={{ width: '100%', height: '100%' }} />;\n const kind = emptyKindFor({ unbound, measurement, declared, reported: lastSample !== undefined });\n const hint = kind === 'no-data' ? lastReadingHint(lastSample, { unit, precision }) : undefined;\n return <WidgetEmptyState kind={kind} measurement={measurement} hint={hint} detail={kind === 'no-data' ? detail : undefined} />;\n}\n\n"],
5
5
  "mappings": ";AAqBA,SAAS,WAAW,aAAa,gCAAgC;AACjE,SAAS,eAAe,wBAA8C;AACtE,SAAS,WAAW,gBAAgB;AAkED;AA/D5B,IAAM,eAAe;AAKrB,IAAM,YAAY;AAElB,SAAS,aAAa,OAMwC;AACnE,MAAI,MAAM,QAAS,QAAO;AAC1B,MAAI,MAAM,SAAU,QAAO;AAC3B,MAAI,MAAM,gBAAgB,UAAa,MAAM,YAAY,CAAC,MAAM,SAAS,SAAS,MAAM,WAAW,EAAG,QAAO;AAC7G,SAAO;AACT;AAGO,SAAS,gBACd,QACA,UAA+D,CAAC,GAC5C;AACpB,MAAI,CAAC,UAAU,OAAO,SAAS,KAAM,QAAO;AAC5C,QAAM,QAAQ,YAAY,OAAO,OAAO,QAAQ,SAAS;AACzD,QAAM,KAAK,OAAO,eAAe,KAAK,MAAM,OAAO,YAAY,IAAI;AACnE,MAAI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5ZEM.js.map
35
+ //# sourceMappingURL=chunk-UDQVBVXJ.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/basemap-context.tsx", "../../src/map-runtime-context.tsx"],
4
+ "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The tenant basemap, threaded to map widgets as ambient environment (ADR-079).\n//\n// 🔴 Why context rather than a new field on WidgetProps. A widget is contractually a\n// pure function of (widget, data): the props carry what the widget SHOWS. A tenant's\n// tile source is not data — it is environment, like the theme — and putting it in the\n// props would change the contract for all fifteen widgets to serve one of them.\n//\n// The default is null, deliberately. A host that installs no provider (widgetlab, the\n// synthetic preview, every existing test) behaves exactly as before: the map falls\n// back to its per-widget options, and to a plain panel when it has none. Adding the\n// provider is what turns a tenant's configured basemap on; nothing breaks without it.\n\nimport { createContext, useContext, type ReactNode } from 'react';\nimport type { Basemap } from '@devicechain/client';\n\nconst TenantBasemapContext = createContext<Basemap | null>(null);\n\n/**\n * Supplies the tenant's effective basemap to every map widget beneath it.\n *\n * Both hosts install this ONCE, high in the tree, rather than at each place they\n * render a widget: the console from its TenantProvider, the /dash viewer app from the\n * one place it mounts a DashboardRenderer.\n *\n * 🔴 That placement is the whole safety argument, because a host that forgets this\n * does NOT fail loudly — its maps simply render as they did before the tenant setting\n * existed, on that surface only. Wrapping individual render sites is the version that\n * silently half-works; there is no render site to forget from the top of the tree.\n */\nexport function TenantBasemapProvider({\n basemap,\n children,\n}: {\n basemap: Basemap | null;\n children: ReactNode;\n}) {\n return <TenantBasemapContext.Provider value={basemap}>{children}</TenantBasemapContext.Provider>;\n}\n\n/**\n * The tenant's effective basemap, or null when no host supplied one.\n *\n * Null means \"no tenant basemap in force\" — either the host installs no provider, or\n * neither the tenant nor the operator has configured one. Both cases resolve the same\n * way downstream (fall back to the per-widget override, then to a plain panel), so\n * callers do not need to distinguish them.\n */\nexport function useTenantBasemap(): Basemap | null {\n return useContext(TenantBasemapContext);\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The map runtime: the pieces of MapLibre that only the HOST'S BUNDLER can produce.\n//\n// 🔴 WHY THIS EXISTS AT ALL. MapLibre parses tiles and geometry off the main thread, and\n// left to itself it derives the worker's URL at runtime from its own module URL —\n// `new URL('./maplibre-gl-worker.mjs', import.meta.url)`. That is a string no bundler can\n// follow, so nothing emits the file, the browser resolves it to a 404, and `new Worker()`\n// does not throw on one: the failure arrives later as an async error event. The map builds,\n// type-checks, passes every test, and renders nothing.\n//\n// The only thing that can emit that file is the application's own bundler, using its own\n// dialect — Vite spells it `?worker&url`, webpack and Rollup each spell it differently.\n// So the URL is something a HOST computes and a LIBRARY cannot.\n//\n// 🔴 THIS PACKAGE USED TO WRITE VITE'S DIALECT ITSELF, and that is the defect this seam\n// removes. A published library containing `import('…?worker&url')` works under a consumer's\n// Vite and silently renders a blank map under anything else — and because the specifier is\n// externalized, no bundler ever tries to resolve it, so NOTHING IN ANY BUILD REPORTS IT.\n// A green pipeline over a broken artifact is strictly worse than a red one.\n//\n// ⚠️ HOW THIS DIFFERS FROM TenantBasemapProvider, which sits beside it and looks alike.\n// The basemap provider is OPTIONAL BY DESIGN: a host that installs none behaves exactly as\n// it did before the tenant setting existed, and that is a coherent state. This one is\n// REQUIRED, and a host that omits it gets a loud notice rather than a map. The asymmetry is\n// deliberate and is the whole point: a missing basemap is a configuration a viewer can read\n// off the screen, while a missing worker URL is invisible — it is the blank map above.\n// Copying the basemap's optional-by-default shape here would relocate that defect into\n// every unwired host instead of removing it.\n\nimport { createContext, useContext, type ReactNode } from 'react';\n\n/**\n * The bundler-produced runtime a map widget needs from its host.\n *\n * `workerUrl` is the emitted, host-resolvable URL of MapLibre's worker entry\n * (`maplibre-gl/dist/maplibre-gl-worker.mjs`). It is handed to MapLibre's `setWorkerUrl`\n * before the first `Map` is constructed.\n *\n * `loadStyles` is OPTIONAL, and imports MapLibre's stylesheet\n * (`maplibre-gl/dist/maplibre-gl.css`). Omit it and import the stylesheet yourself, the way\n * every map library asks you to — that is the ordinary path and nothing here second-guesses\n * it. Supplying it buys one thing: the CSS rides the renderer's lazy chunk instead of your\n * main stylesheet, which is worth **83 KB raw / 10.7 KB gzipped** to a viewer who never\n * opens a board with a map on it.\n *\n * 🔴 The size is measured against maplibre-gl 6.6.0, the version this package peers on. An\n * earlier draft said 70 KB \"measured, not estimated\" — measured, but against a stale\n * `node_modules` carrying 6.2.0. Measuring the right thing in the wrong tree reads exactly\n * like measuring, which is why the version is named here.\n *\n * 🔴 It is a FUNCTION rather than a boolean or a URL because the host's bundler owns its\n * CSS pipeline: only the host can say \"load this, lazily, your way\".\n */\nexport type MapRuntime = {\n workerUrl: string;\n loadStyles?: () => Promise<unknown>;\n};\n\nconst MapRuntimeContext = createContext<MapRuntime | null>(null);\n\n/**\n * Supplies the host's MapLibre runtime to every map widget beneath it.\n *\n * Install it ONCE, high in the tree, next to TenantBasemapProvider — the console from its\n * TenantProvider, the /dash viewer from the one place it mounts a DashboardRenderer.\n *\n * 🔑 ON VITE, DO NOT WRITE ANY OF THIS — import the ready-made runtime:\n *\n * ```tsx\n * import { viteMapRuntime } from '@devicechain/widgets/vite';\n *\n * <MapRuntimeProvider runtime={viteMapRuntime}>{children}</MapRuntimeProvider>\n * ```\n *\n * On any other bundler you supply the URL yourself, and there is ONE REQUIREMENT that\n * decides whether it works: MapLibre loads the URL as a MODULE worker, so whatever it\n * serves must be a module with no unresolved imports left in it.\n * `maplibre-gl/dist/maplibre-gl-worker.mjs` does not satisfy that on its own — its first\n * line is `import … from './maplibre-gl-shared.mjs'`.\n *\n * 🔴 SO DO NOT POINT AT A VERBATIM COPY OF THE WORKER FILE, and in particular do not\n * reach for `new URL('maplibre-gl/dist/maplibre-gl-worker.mjs', import.meta.url)`. That\n * looks exactly right and is wrong: webpack treats the target as an ASSET and copies it,\n * the sibling is never emitted, and the worker dies on its own first line. Measured\n * against webpack 5, from a packed tarball: the worker URL answered 200, both maps drew\n * canvases, all markers appeared, tiles loaded, THE BUILD EXITED 0 AND THE CONSOLE WAS\n * EMPTY — and the bundled basemap rendered ocean with no land on it.\n *\n * Two recipes that were measured working, in `hack/consumer-proof`:\n *\n * ```js\n * // webpack — make the worker a second ENTRY, so its imports are bundled into it.\n * entry: { main: './src/index.tsx', 'maplibre-worker': 'maplibre-gl/dist/maplibre-gl-worker.mjs' }\n * // …then: <MapRuntimeProvider runtime={{ workerUrl: '/maplibre-worker.js' }}>\n * ```\n *\n * ```js\n * // any bundler, or none — copy the worker AND ITS SIBLING, under their own names,\n * // into one served directory: maplibre-gl-worker.mjs + maplibre-gl-shared.mjs\n * // …then: <MapRuntimeProvider runtime={{ workerUrl: '/vendor/maplibre-gl-worker.mjs' }}>\n * ```\n *\n * 🔴 Hold the runtime in a MODULE CONSTANT, as above, rather than building it inline in\n * JSX. An object literal in the element is a new identity on every render, and while the\n * widget deliberately keys its effects on `workerUrl` rather than on the object to survive\n * that, a host that also passes it anywhere keyed on identity would tear down and rebuild\n * the map on every parent render. There is nothing per-render in it to justify the risk.\n *\n * 🔴 `maplibre-gl` is a PEER dependency of this package precisely so that the copy the host\n * takes the worker from is the same copy this package renders with. A worker built from one\n * version driving a main thread from another is the blank map again, by a different route.\n */\nexport function MapRuntimeProvider({\n runtime,\n children,\n}: {\n runtime: MapRuntime;\n children: ReactNode;\n}) {\n return <MapRuntimeContext.Provider value={runtime}>{children}</MapRuntimeContext.Provider>;\n}\n\n/**\n * The host's map runtime, or null when no host supplied one.\n *\n * 🔴 Callers MUST treat null as a refusal to render a map, not as a default to paper over.\n * There is no sensible fallback: the only alternative to a host-supplied URL is MapLibre's\n * own runtime derivation, which is the broken behaviour this seam exists to prevent.\n */\nexport function useMapRuntime(): MapRuntime | null {\n return useContext(MapRuntimeContext);\n}\n"],
5
+ "mappings": ";AAeA,SAAS,eAAe,kBAAkC;AAwBjD;AArBT,IAAM,uBAAuB,cAA8B,IAAI;AAcxD,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AACF,GAGG;AACD,SAAO,oBAAC,qBAAqB,UAArB,EAA8B,OAAO,SAAU,UAAS;AAClE;AAUO,SAAS,mBAAmC;AACjD,SAAO,WAAW,oBAAoB;AACxC;;;ACrBA,SAAS,iBAAAA,gBAAe,cAAAC,mBAAkC;AA0FjD,gBAAAC,YAAA;AA7DT,IAAM,oBAAoBF,eAAiC,IAAI;AAsDxD,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA;AACF,GAGG;AACD,SAAO,gBAAAE,KAAC,kBAAkB,UAAlB,EAA2B,OAAO,SAAU,UAAS;AAC/D;AASO,SAAS,gBAAmC;AACjD,SAAOD,YAAW,iBAAiB;AACrC;",
6
+ "names": ["createContext", "useContext", "jsx"]
7
+ }
@@ -0,0 +1,17 @@
1
+ // src/access-strings.ts
2
+ import { viewerLocale } from "@devicechain/widget-sdk";
3
+ var ACCESS_STRINGS = {
4
+ en: { forbidden: "You do not have access to this data" },
5
+ es: { forbidden: "No tiene acceso a estos datos" },
6
+ "zh-CN": { forbidden: "您无权访问这些数据" }
7
+ };
8
+ function accessStrings(locale = viewerLocale()) {
9
+ const language = locale?.toLowerCase().split("-")[0];
10
+ return language === "es" ? ACCESS_STRINGS.es : language === "zh" ? ACCESS_STRINGS["zh-CN"] : ACCESS_STRINGS.en;
11
+ }
12
+
13
+ export {
14
+ ACCESS_STRINGS,
15
+ accessStrings
16
+ };
17
+ //# sourceMappingURL=chunk-UVLEBGAC.js.map