@klarkxy/dsh-font 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -854,6 +854,281 @@ function registerSettingsSectionIcon(ctx, sectionId, order, component) {
854
854
  }, component));
855
855
  }
856
856
  //#endregion
857
+ //#region ../dsh-plugin-kit/src/log-shared.ts
858
+ const PLUGIN_LOG_LEVELS = [
859
+ "debug",
860
+ "info",
861
+ "warn",
862
+ "error",
863
+ "fault"
864
+ ];
865
+ const DEFAULT_PLUGIN_LOG_LEVEL = "info";
866
+ const PLUGIN_LOG_MAX_MESSAGE_CHARS = 16e3;
867
+ const SOURCE_RE = /^[a-z][a-z0-9-]{0,63}$/;
868
+ const EVENT_RE = /^[a-z][a-z0-9._-]{0,127}$/;
869
+ const CONTEXT_KEY_RE = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/;
870
+ const SECRET_KEY_RE = /(?:api[_-]?key|access[_-]?token|refresh[_-]?token|bearer|authorization|cookie|set[_-]?cookie|nonce|credential|private[_-]?key|password|secret|app[_-]?secret|client[_-]?secret|z_c0|d_c0)$/i;
871
+ const CHAT_PAYLOAD_RE = /"role"\s*:\s*"(?:system|user|assistant|tool)"|"(?:messages|content|prompt|input_text|input_image|image_url)"\s*:\s*[\[{"']/i;
872
+ const CREDENTIAL_BODY_RE = /-----BEGIN (?:RSA |EC |OPENSSH |PRIVATE )?PRIVATE KEY-----|"type"\s*:\s*"service_account"|credentials\.json|\.dsh[/\\](?:credentials|auth)/i;
873
+ const AUTH_HEADER_RE = /\b(Authorization|Proxy-Authorization|Cookie|Set-Cookie)\s*:\s*[^\r\n]*/gi;
874
+ const BEARER_RE = /\bBearer\s+[A-Za-z0-9._\-+=/]{8,}/g;
875
+ const SECRET_FIELD_RE = /(["']?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|bearer|authorization|cookie|set-cookie|nonce|credential|private[_-]?key|password|secret|app[_-]?secret|client[_-]?secret|password|z_c0|d_c0)["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,&;}]+)/gi;
876
+ const SECRET_QUERY_RE = /([?&](?:token|api[_-]?key|key|secret|password|bootstrap|code|sig|signature|credential|password)=)[^\s&#"']+/gi;
877
+ const URL_CREDENTIAL_RE = /\b(https?:\/\/)[^\s/:@]+:[^\s/@]+@/gi;
878
+ const BOOTSTRAP_RE = /\/bootstrap\/[^\s"'?&#]+/gi;
879
+ const KNOWN_TOKEN_RE = /\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{20,}|tvly-[A-Za-z0-9_-]{10,}|AKIA[0-9A-Z]{16})\b/g;
880
+ const PATH_RE = /(?:[A-Za-z]:\\|\\\\)[^\s"'`<>|]+|(?:\/(?:home|Users|tmp|var|root)\/|~\/)[^\s"'`<>|]+/g;
881
+ function isPluginLogLevel(value) {
882
+ return typeof value === "string" && PLUGIN_LOG_LEVELS.includes(value);
883
+ }
884
+ function pluginLogLevelEnabled(level, minimum) {
885
+ return PLUGIN_LOG_LEVELS.indexOf(level) >= PLUGIN_LOG_LEVELS.indexOf(minimum);
886
+ }
887
+ function normalizePluginLogSource(raw) {
888
+ const stripped = String(raw || "").trim().replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
889
+ const bounded = (/^[a-z]/.test(stripped) ? stripped : `p-${stripped}`).slice(0, 64).replace(/-+$/g, "");
890
+ return SOURCE_RE.test(bounded) ? bounded : "dsh-plugin";
891
+ }
892
+ function normalizePluginLogEvent(raw) {
893
+ const cleaned = String(raw || "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z]+/, "").slice(0, 128);
894
+ return EVENT_RE.test(cleaned) ? cleaned : "plugin.event";
895
+ }
896
+ /**
897
+ * Parse a level specification like `debug` or `dsh-zhihu=debug,dsh-dot:warn,info`.
898
+ * Source-specific rules win over a bare fallback level.
899
+ */
900
+ function parsePluginLogLevel(spec, source, fallback = DEFAULT_PLUGIN_LOG_LEVEL) {
901
+ if (!spec || typeof spec !== "string") return fallback;
902
+ const normalizedSource = source ? normalizePluginLogSource(source) : void 0;
903
+ let wildcard;
904
+ for (const token of spec.split(",").map((part) => part.trim()).filter(Boolean)) {
905
+ const lowered = token.toLowerCase();
906
+ if (isPluginLogLevel(lowered)) {
907
+ wildcard = lowered;
908
+ continue;
909
+ }
910
+ const match = /^([^=:]+)[=:]([a-z]+)$/i.exec(token);
911
+ if (!match) continue;
912
+ const target = match[1].trim();
913
+ const candidate = match[2].trim().toLowerCase();
914
+ if (!isPluginLogLevel(candidate)) continue;
915
+ if (target === "*") {
916
+ wildcard = candidate;
917
+ continue;
918
+ }
919
+ if (normalizedSource && normalizePluginLogSource(target) === normalizedSource) return candidate;
920
+ }
921
+ return wildcard ?? fallback;
922
+ }
923
+ function sanitizePluginLogText(text, maxChars = PLUGIN_LOG_MAX_MESSAGE_CHARS) {
924
+ if (!text) return "";
925
+ if (CREDENTIAL_BODY_RE.test(text)) return "[omitted credential material]";
926
+ if (CHAT_PAYLOAD_RE.test(text)) return "[omitted chat payload]";
927
+ return truncateLogText(text.replace(AUTH_HEADER_RE, "$1: [redacted]").replace(BEARER_RE, "Bearer [redacted]").replace(SECRET_FIELD_RE, (full, prefix) => {
928
+ const value = full.slice(prefix.length);
929
+ if (value.startsWith("\"")) return `${prefix}"[redacted]"`;
930
+ if (value.startsWith("'")) return `${prefix}'[redacted]'`;
931
+ return `${prefix}[redacted]`;
932
+ }).replace(SECRET_QUERY_RE, "$1[redacted]").replace(URL_CREDENTIAL_RE, "$1[redacted]@").replace(BOOTSTRAP_RE, "/bootstrap/[redacted]").replace(KNOWN_TOKEN_RE, "[redacted]").replace(PATH_RE, "[path]"), maxChars);
933
+ }
934
+ function sanitizePluginLogContext(input) {
935
+ if (!input) return void 0;
936
+ const output = {};
937
+ for (const [key, value] of Object.entries(input).slice(0, 32)) {
938
+ if (value === void 0 || !CONTEXT_KEY_RE.test(key)) continue;
939
+ if (typeof value === "number" && !Number.isFinite(value)) continue;
940
+ if (SECRET_KEY_RE.test(key)) {
941
+ output[key] = "[redacted]";
942
+ continue;
943
+ }
944
+ output[key] = typeof value === "string" ? sanitizePluginLogText(value, 1e3) : value;
945
+ }
946
+ if (!Object.keys(output).length) return void 0;
947
+ if (JSON.stringify(output).length <= 8e3) return output;
948
+ return {
949
+ omitted: true,
950
+ reason: "Diagnostic context exceeded its size limit."
951
+ };
952
+ }
953
+ function sanitizePluginLogError(error) {
954
+ if (error === void 0) return void 0;
955
+ const row = error && typeof error === "object" ? error : {};
956
+ const rawMessage = typeof row.message === "string" ? row.message : String(error);
957
+ const result = {
958
+ name: typeof row.name === "string" && row.name.trim() ? sanitizePluginLogText(row.name.trim(), 100) : "Error",
959
+ message: sanitizePluginLogText(rawMessage) || "Unknown error"
960
+ };
961
+ if (typeof row.stack === "string" && row.stack.trim()) result.stack = sanitizePluginLogText(row.stack, 24e3);
962
+ if (typeof row.code === "string" && /^[A-Za-z0-9_./:-]{1,100}$/.test(row.code)) result.code = sanitizePluginLogText(row.code, 100);
963
+ else if (typeof row.code === "number" && Number.isFinite(row.code)) result.code = String(row.code);
964
+ return result;
965
+ }
966
+ function mergePluginLogContext(base, extra) {
967
+ if (!base) return extra;
968
+ if (!extra) return base;
969
+ return {
970
+ ...base,
971
+ ...extra
972
+ };
973
+ }
974
+ function buildPluginLogEntry(input, meta) {
975
+ const entry = {
976
+ version: 1,
977
+ at: meta.at.toISOString(),
978
+ level: isPluginLogLevel(input.level) ? input.level : "info",
979
+ source: normalizePluginLogSource(meta.source),
980
+ surface: meta.surface,
981
+ ...meta.profile ? { profile: meta.profile } : {},
982
+ event: normalizePluginLogEvent(input.event),
983
+ message: sanitizePluginLogText(input.message || "No diagnostic message was provided.", PLUGIN_LOG_MAX_MESSAGE_CHARS),
984
+ ...meta.pid !== void 0 ? { pid: meta.pid } : {}
985
+ };
986
+ const context = sanitizePluginLogContext(mergePluginLogContext(meta.correlation, input.context));
987
+ if (context) entry.context = context;
988
+ const error = sanitizePluginLogError(input.error);
989
+ if (error) entry.error = error;
990
+ return entry;
991
+ }
992
+ function createChildPluginLogger(parent, bound) {
993
+ return {
994
+ get source() {
995
+ return parent.source;
996
+ },
997
+ get file() {
998
+ return parent.file;
999
+ },
1000
+ get lastWriteError() {
1001
+ return parent.lastWriteError;
1002
+ },
1003
+ debug: (event, message, context) => parent.debug(event, message, mergePluginLogContext(bound, context)),
1004
+ info: (event, message, context) => parent.info(event, message, mergePluginLogContext(bound, context)),
1005
+ warn: (event, message, error, context) => parent.warn(event, message, error, mergePluginLogContext(bound, context)),
1006
+ error: (event, message, error, context) => parent.error(event, message, error, mergePluginLogContext(bound, context)),
1007
+ fault: (event, message, error, context) => parent.fault(event, message, error, mergePluginLogContext(bound, context)),
1008
+ write: (input) => parent.write({
1009
+ ...input,
1010
+ context: mergePluginLogContext(bound, input.context)
1011
+ }),
1012
+ child: (next) => createChildPluginLogger(parent, mergePluginLogContext(bound, next) ?? {})
1013
+ };
1014
+ }
1015
+ function truncateLogText(text, maxChars) {
1016
+ if (text.length <= maxChars) return text;
1017
+ const marker = "[truncated]\n";
1018
+ if (maxChars <= 12) return text.slice(0, Math.max(0, maxChars));
1019
+ return `${marker}${text.slice(-(maxChars - 12))}`;
1020
+ }
1021
+ //#endregion
1022
+ //#region ../dsh-plugin-kit/src/client-logger.ts
1023
+ const CLIENT_PLUGIN_LOG_GLOBAL = "__KLARKXY_PLUGIN_LOGS__";
1024
+ function readStorageFlag(key) {
1025
+ try {
1026
+ const value = (globalThis.window?.localStorage)?.getItem?.(key);
1027
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1028
+ } catch {
1029
+ return;
1030
+ }
1031
+ }
1032
+ function sharedClientBuffer(limit) {
1033
+ const carrier = globalThis;
1034
+ if (!Array.isArray(carrier["__KLARKXY_PLUGIN_LOGS__"])) try {
1035
+ carrier[CLIENT_PLUGIN_LOG_GLOBAL] = [];
1036
+ } catch {
1037
+ return [];
1038
+ }
1039
+ const list = carrier[CLIENT_PLUGIN_LOG_GLOBAL];
1040
+ const overflow = list.length - limit;
1041
+ if (overflow > 0) list.splice(0, overflow);
1042
+ return list;
1043
+ }
1044
+ function createClientPluginLogger(source, ctx, options = {}) {
1045
+ const normalized = normalizePluginLogSource(source);
1046
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
1047
+ const limit = Math.max(10, options.bufferLimit ?? 500);
1048
+ const browserCtx = ctx && typeof ctx === "object" ? ctx : void 0;
1049
+ const resolveMinimum = () => {
1050
+ if (options.minimumLevel) return options.minimumLevel;
1051
+ return parsePluginLogLevel(readStorageFlag("dsh-plugin-log-level"), normalized, DEFAULT_PLUGIN_LOG_LEVEL);
1052
+ };
1053
+ const logger = {
1054
+ source: normalized,
1055
+ file: null,
1056
+ lastWriteError: null,
1057
+ debug: (event, message, context) => logger.write({
1058
+ level: "debug",
1059
+ event,
1060
+ message,
1061
+ ...context ? { context } : {}
1062
+ }),
1063
+ info: (event, message, context) => logger.write({
1064
+ level: "info",
1065
+ event,
1066
+ message,
1067
+ ...context ? { context } : {}
1068
+ }),
1069
+ warn: (event, message, error, context) => logger.write({
1070
+ level: "warn",
1071
+ event,
1072
+ message,
1073
+ ...error !== void 0 ? { error } : {},
1074
+ ...context ? { context } : {}
1075
+ }),
1076
+ error: (event, message, error, context) => logger.write({
1077
+ level: "error",
1078
+ event,
1079
+ message,
1080
+ ...error !== void 0 ? { error } : {},
1081
+ ...context ? { context } : {}
1082
+ }),
1083
+ fault: (event, message, error, context) => logger.write({
1084
+ level: "fault",
1085
+ event,
1086
+ message,
1087
+ ...error !== void 0 ? { error } : {},
1088
+ ...context ? { context } : {}
1089
+ }),
1090
+ child: (context) => createChildPluginLogger(logger, context),
1091
+ write(input) {
1092
+ try {
1093
+ if (!pluginLogLevelEnabled(input.level, resolveMinimum())) return false;
1094
+ const entry = buildPluginLogEntry(input, {
1095
+ at: now(),
1096
+ source: normalized,
1097
+ surface: "client"
1098
+ });
1099
+ const buffer = sharedClientBuffer(limit);
1100
+ buffer.push(entry);
1101
+ const overflow = buffer.length - limit;
1102
+ if (overflow > 0) buffer.splice(0, overflow);
1103
+ if (options.forwardToHostLogger !== false && browserCtx?.logger) {
1104
+ const summary = sanitizePluginLogText(`${normalized} [${entry.event}]: ${entry.message}`, 500);
1105
+ if (entry.level === "warn" && typeof browserCtx.logger.warn === "function") browserCtx.logger.warn(summary);
1106
+ else if ((entry.level === "error" || entry.level === "fault") && typeof browserCtx.logger.error === "function") browserCtx.logger.error(summary);
1107
+ }
1108
+ if (readStorageFlag("dsh-plugin-log-console") === "1") {
1109
+ const con = globalThis.console;
1110
+ (entry.level === "debug" ? con?.debug : entry.level === "info" ? con?.info : entry.level === "warn" ? con?.warn : con?.error)?.call(con, `[${normalized}] ${entry.event}: ${entry.message}`, entry);
1111
+ }
1112
+ return true;
1113
+ } catch {
1114
+ return false;
1115
+ }
1116
+ }
1117
+ };
1118
+ return logger;
1119
+ }
1120
+ function installClientPluginLogger(ctx, source, options = {}) {
1121
+ const logger = createClientPluginLogger(source, ctx, options);
1122
+ logger.info("client.loaded", "Client plugin initialized.", options.loadedContext);
1123
+ const browserCtx = ctx && typeof ctx === "object" ? ctx : void 0;
1124
+ if (typeof browserCtx?.effect === "function") try {
1125
+ browserCtx.effect(() => () => {
1126
+ logger.debug("client.disposed", "Client plugin disposed.");
1127
+ }, `${logger.source}.client-logger`);
1128
+ } catch {}
1129
+ return logger;
1130
+ }
1131
+ //#endregion
857
1132
  //#region src/client.tsx
858
1133
  const name = "dsh-font-client";
859
1134
  const inject = [
@@ -1144,6 +1419,7 @@ function FontSettingsGroup(props) {
1144
1419
  if (fontList.state === "loading") return;
1145
1420
  const query = globalThis.queryLocalFonts;
1146
1421
  if (typeof query !== "function") {
1422
+ createClientPluginLogger(PLUGIN_NAME).debug("system-fonts.unsupported", "Local Font Access API is not available in this browser.");
1147
1423
  setFontList({
1148
1424
  state: "denied",
1149
1425
  families: []
@@ -1155,12 +1431,14 @@ function FontSettingsGroup(props) {
1155
1431
  families: current.families
1156
1432
  }));
1157
1433
  try {
1158
- const fonts = await query();
1434
+ const families = uniqueSystemFonts(await query());
1435
+ createClientPluginLogger(PLUGIN_NAME).info("system-fonts.loaded", "Loaded system font families.", { count: families.length });
1159
1436
  setFontList({
1160
1437
  state: "ready",
1161
- families: uniqueSystemFonts(fonts)
1438
+ families
1162
1439
  });
1163
- } catch {
1440
+ } catch (error) {
1441
+ createClientPluginLogger(PLUGIN_NAME).warn("system-fonts.denied", "System font enumeration was denied or failed.", error);
1164
1442
  setFontList((current) => ({
1165
1443
  state: "denied",
1166
1444
  families: current.families
@@ -1310,6 +1588,7 @@ function FontSettingsGroup(props) {
1310
1588
  });
1311
1589
  }
1312
1590
  function apply(ctx) {
1591
+ const logger = installClientPluginLogger(ctx, PLUGIN_NAME);
1313
1592
  const client = ctx;
1314
1593
  const store = createFontSettingsStore(readStorage());
1315
1594
  const conversation = createConversationFontStore(readStorage());
@@ -1334,9 +1613,13 @@ function apply(ctx) {
1334
1613
  while (sheet.cssRules.length > 0) sheet.deleteRule(0);
1335
1614
  const declarations = conversationFontDeclarations(conversation.get(), fontTokenDeclarations(document.styleSheets ?? []));
1336
1615
  if (declarations.length === 0) return;
1337
- sheet.insertRule(`${CONVERSATION_FONT_SELECTOR}{}`);
1338
- const rule = sheet.cssRules[0];
1339
- for (const [name, value] of declarations) rule.style.setProperty(name, value);
1616
+ try {
1617
+ sheet.insertRule(`${CONVERSATION_FONT_SELECTOR}{}`);
1618
+ const rule = sheet.cssRules[0];
1619
+ for (const [name, value] of declarations) rule.style.setProperty(name, value);
1620
+ } catch (error) {
1621
+ logger.warn("conversation-font.rule-failed", "Failed to apply conversation font CSS rule.", error);
1622
+ }
1340
1623
  };
1341
1624
  write();
1342
1625
  const unsubscribe = conversation.subscribe(write);
package/lib/index.d.ts CHANGED
@@ -8,7 +8,7 @@ declare const name = "@klarkxy/dsh-font";
8
8
  * font persists browser-local, and every host-backed write goes through the
9
9
  * official `ctx.theme` entries. Nothing here needs a Host service.
10
10
  */
11
- declare function apply(_ctx: Context): void;
11
+ declare function apply(ctx: Context): void;
12
12
  //#endregion
13
13
  export { apply, name };
14
14
  //# sourceMappingURL=index.d.ts.map