Commit 2f29f6dc by liimin

refactor: 统一代码风格并优化签名函数逻辑

- 调整导入顺序,将 `import` 语句标准化
- 统一缩进为制表符(tabs),替换部分空格缩进
- 优化 `sign.uts` 中循环逻辑,使用 `for...of` 替代传统 `for` 循环
- 修复 `qs.uts` 中类型定义和递归序列化逻辑,增强健壮性
- 将登录页特定分辨率背景色从蓝色改为红色
1 parent d5e0c173
...@@ -3,107 +3,167 @@ ...@@ -3,107 +3,167 @@
* 仅支持简单对象序列化,不处理复杂嵌套 * 仅支持简单对象序列化,不处理复杂嵌套
*/ */
interface StringifyOptions { export type Encoder = (str: string) => string
export type Sorter = (a: any, b: any) => number
export type GenerateArrayPrefix = (prefix: string, key: string) => string
export type Formatter = (str: string) => string
export type SerializeDate = (date: Date) => string
export type Filter = (prefix: string, value: any) => any
export type StringifyOptions = {
allowDots?: boolean
encoder?: Encoder
encodeValuesOnly?: boolean
filter?: any // Function | Array<string>
formatter?: Formatter
generateArrayPrefix?: GenerateArrayPrefix
prefix?: string prefix?: string
encoder?: Function serializeDate?: SerializeDate
filter?: Function | Array<string>
sort?: Function
strictNullHandling?: boolean
skipNulls?: boolean skipNulls?: boolean
encodeValuesOnly?: boolean sort?: Sorter
generateArrayPrefix?: Function strictNullHandling?: boolean
allowDots?: boolean }
serializeDate?: Function
formatter?: Function function defaultEncoder(str: string): string {
const res = encodeURIComponent(str);
return res ?? str;
}
function defaultGenerateArrayPrefix(p: string, k: string): string {
return `${p}[${k}]`;
}
function defaultFormatter(str: string): string {
return str;
}
function defaultSerializeDate(date: Date): string {
return date.toISOString();
} }
function stringifyRecursive( function stringifyRecursive(
obj: any, obj: any | null,
options: StringifyOptions = {} options: StringifyOptions
): string { ): string {
const prefix = options.prefix ?? '' const prefix = options.prefix ?? "";
const encoder = options.encoder || encodeURIComponent const encoder = options.encoder != null ? options.encoder! : (str: string): string => defaultEncoder(str);
const filter = options.filter const filter = options.filter;
const sort = options.sort const sort = options.sort;
const strictNullHandling = options.strictNullHandling ?? false const strictNullHandling = options.strictNullHandling ?? false;
const skipNulls = options.skipNulls ?? false const skipNulls = options.skipNulls ?? false;
const encodeValuesOnly = options.encodeValuesOnly ?? false const encodeValuesOnly = options.encodeValuesOnly ?? false;
const generateArrayPrefix = options.generateArrayPrefix || ((p: string, k: string) => `${p}[${k}]`) const generateArrayPrefix = options.generateArrayPrefix != null ? options.generateArrayPrefix! : (p: string, k: string): string => defaultGenerateArrayPrefix(p, k);
const allowDots = options.allowDots ?? false const allowDots = options.allowDots ?? false;
const formatter = options.formatter || ((str: string) => str) const formatter = options.formatter != null ? options.formatter! : (str: string): string => defaultFormatter(str);
const serializeDate = options.serializeDate || ((date: Date) => date.toISOString()) const serializeDate = options.serializeDate != null ? options.serializeDate! : (date: Date): string => defaultSerializeDate(date);
let processedObj: any = obj let processedObj: any | null = obj;
if (typeof filter === 'function') { if (typeof filter === "function") {
processedObj = filter(prefix, obj) const filterFn = filter as Filter;
// UTS requires parameter types to match exactly, but 'obj' is 'any | null'
// and Filter expects 'any'. Casting 'obj' to 'any' is safe here.
processedObj = filterFn(prefix, obj as any);
} else if (obj instanceof Date) { } else if (obj instanceof Date) {
processedObj = serializeDate(obj) processedObj = serializeDate(obj);
} else if (obj === null) { } else if (obj === null) {
if (strictNullHandling) { if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix) : prefix return encoder(prefix);
} }
processedObj = '' processedObj = "";
} }
if (typeof processedObj === 'string' || if (typeof processedObj === "string" ||
typeof processedObj === 'number' || typeof processedObj === "number" ||
typeof processedObj === 'boolean') { typeof processedObj === "boolean") {
if (encoder) { const keyValue = encodeValuesOnly ? prefix : encoder(prefix);
const keyValue = encodeValuesOnly ? prefix : encoder(prefix) const valueStr = typeof processedObj === "string" ? processedObj as string : `${processedObj}`;
return `${formatter(keyValue)}=${formatter(encoder(processedObj))}` return `${formatter(keyValue)}=${formatter(encoder(valueStr))}`;
}
return `${formatter(prefix)}=${formatter(String(processedObj))}`
} }
const values: Array<string> = [] const values: string[] = [];
if (typeof processedObj === 'undefined') { if (processedObj == null) {
return '' return "";
} }
let objKeys: Array<string> = [] let objKeys: string[] = [];
let targetObj: any | null = processedObj;
if (Array.isArray(filter)) { if (Array.isArray(filter)) {
objKeys = filter as Array<string> objKeys = filter as string[];
// If filter is array, we still need to know how to access processedObj
// If processedObj is not array/map, we might need to convert it to be accessible
if (!Array.isArray(processedObj) && !(processedObj instanceof UTSJSONObject)) {
targetObj = new UTSJSONObject(processedObj);
}
} else { } else {
const keys = Object.keys(processedObj) if (processedObj != null) {
objKeys = sort ? keys.sort(sort) : keys if (Array.isArray(processedObj)) {
const arr = processedObj as any[];
for (let i = 0; i < arr.length; i++) {
objKeys.push(`${i}`);
} }
} else if (processedObj instanceof UTSJSONObject) {
for (let i = 0; i < objKeys.length; i++) { const objMap = (processedObj as UTSJSONObject).toMap();
const key = objKeys[i] objMap.forEach((_, key) => {
objKeys.push(key);
if (skipNulls && processedObj[key] === null) { });
continue } else {
const json = new UTSJSONObject(processedObj);
targetObj = json;
const objMap = json.toMap();
objMap.forEach((_, key) => {
objKeys.push(key);
});
} }
if (sort != null) {
if (Array.isArray(processedObj)) { objKeys = objKeys.sort(sort);
const result = stringifyRecursive(
processedObj[key],
{
...options,
prefix: prefix ? generateArrayPrefix(prefix, key) : key
} }
) }
if (result) { }
values.push(result)
for (const key of objKeys) {
let value: any | null = null;
if (Array.isArray(targetObj)) {
const idx = Number.parseInt(key);
if (!isNaN(idx)) {
value = (targetObj as any[])[idx];
} }
} else { } else {
const result = stringifyRecursive( value = (targetObj as UTSJSONObject)[key];
processedObj[key],
{
...options,
prefix: prefix ? prefix + (allowDots ? '.' + key : '[' + key + ']') : key
} }
)
if (result) { if (skipNulls && value === null) {
values.push(result) continue;
} }
const nextPrefix = Array.isArray(targetObj)
? (prefix != "" ? generateArrayPrefix(prefix, key) : key)
: (prefix != "" ? prefix + (allowDots ? `.${key}` : `[${key}]`) : key);
const newOptions: StringifyOptions = {
prefix: nextPrefix,
encoder,
filter,
sort,
strictNullHandling,
skipNulls,
encodeValuesOnly,
generateArrayPrefix,
allowDots,
serializeDate,
formatter
};
const result = stringifyRecursive(value, newOptions);
if (result != "") {
values.push(result);
} }
} }
return values.join('&') return values.join("&");
} }
/** /**
...@@ -114,7 +174,7 @@ function stringifyRecursive( ...@@ -114,7 +174,7 @@ function stringifyRecursive(
*/ */
export function stringify( export function stringify(
obj: UTSJSONObject, obj: UTSJSONObject,
options: StringifyOptions = {} options: StringifyOptions = {} as StringifyOptions
): string { ): string {
return stringifyRecursive(obj, options) return stringifyRecursive(obj, options);
} }
import { stringify as qsStringify, StringifyOptions } from "./qs.uts";
import { sha1 } from "./sha1.uts"; import { sha1 } from "./sha1.uts";
import { stringify as qsStringify } from "./qs.uts";
/** /**
* 参数签名方法(完全对齐 gl_tape/api/request/sign.js) * 参数签名方法(完全对齐 gl_tape/api/request/sign.js)
...@@ -16,25 +16,26 @@ import { stringify as qsStringify } from "./qs.uts"; ...@@ -16,25 +16,26 @@ import { stringify as qsStringify } from "./qs.uts";
export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] = []): UTSJSONObject { export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] = []): UTSJSONObject {
// 1. 用 qs.stringify 序列化(encodeValuesOnly: true) // 1. 用 qs.stringify 序列化(encodeValuesOnly: true)
const objStr = qsStringify(params,{ const options = {
arrayFormat: 'indices', // arrayFormat: 'indices', // UTS qs implementation doesn't support arrayFormat yet, default is indices-like
allowDots: true, allowDots: true,
encodeValuesOnly: true encodeValuesOnly: true
}); } as StringifyOptions;
console.log(objStr,'===')
const objStr = qsStringify(params, options);
console.log(objStr, "===");
// 2. split('&') 拆开 // 2. split('&') 拆开
const objVal = objStr.split('&'); const objVal = objStr.split("&");
// 3. 解码并重建对象(用于签名计算) // 3. 解码并重建对象(用于签名计算)
const realObj: UTSJSONObject = {}; const realObj: UTSJSONObject = {};
for (let i = 0; i < objVal.length; i++) { for (const item of objVal) {
const item = objVal[i]; const idx = item.indexOf("=");
const idx = item.indexOf('='); if (idx === -1) {
if (idx < 0) {
continue; continue;
} }
const key = item.substring(0, idx); const key = item.slice(0, Math.max(0, idx));
const val = decodeURIComponent(item.substring(idx + 1)); const val = decodeURIComponent(item.slice(Math.max(0, idx + 1)));
realObj[key] = val; realObj[key] = val;
} }
...@@ -49,13 +50,12 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] ...@@ -49,13 +50,12 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
sortedKeys.sort(); sortedKeys.sort();
// 5. 归一化 value:null -> "",对象 -> JSON 字符串 // 5. 归一化 value:null -> "",对象 -> JSON 字符串
for (let i = 0; i < sortedKeys.length; i++) { for (const key of sortedKeys) {
const key = sortedKeys[i];
let obj: any | null = realObj[key]; let obj: any | null = realObj[key];
if (obj == null) { if (obj == null) {
obj = ""; obj = "";
} else if (typeof obj == "object") { } else if (typeof obj === "object") {
obj = JSON.stringify(obj); obj = JSON.stringify(obj);
} }
...@@ -64,8 +64,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] ...@@ -64,8 +64,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
// 6. 组装待签名字符串(排除 noSignAttr 指定的字段) // 6. 组装待签名字符串(排除 noSignAttr 指定的字段)
const segments: string[] = []; const segments: string[] = [];
for (let i = 0; i < sortedKeys.length; i++) { for (const key of sortedKeys) {
const key = sortedKeys[i];
if (noSignAttr.indexOf(key) >= 0) { if (noSignAttr.indexOf(key) >= 0) {
continue; continue;
} }
...@@ -78,7 +77,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] ...@@ -78,7 +77,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
const signVal = sha1(signSrc).toUpperCase(); const signVal = sha1(signSrc).toUpperCase();
// 8. 把 sign 挂到 realObj 上,返回全字符串的对象(和老项目保持一致) // 8. 把 sign 挂到 realObj 上,返回全字符串的对象(和老项目保持一致)
realObj["sign"] = signVal; realObj.sign = signVal;
return realObj; return realObj;
} }
import { ResponsiveImage } from "./types/index.uts";
import { getResponsiveImage } from "./core.uts"; import { getResponsiveImage } from "./core.uts";
import { ResponsiveImage } from "./types/index.uts";
/** /**
* 获取响应式图片处理函数 * 获取响应式图片处理函数
......
...@@ -5,7 +5,7 @@ export { IResolutionAdapter, resolutionAdapters } from "./adapter.uts"; ...@@ -5,7 +5,7 @@ export { IResolutionAdapter, resolutionAdapters } from "./adapter.uts";
export { getResponsiveImage, updateResolutionConfig, useResolutionConfig } from "./core.uts"; export { getResponsiveImage, updateResolutionConfig, useResolutionConfig } from "./core.uts";
// 导出 Hooks // 导出 Hooks
export { useResponsiveImage } from './hooks.uts'; export { useResponsiveImage } from "./hooks.uts";
// 导出注册表 // 导出注册表
export { initRegistry, landscapeMap, portraitMap } from "./registry.uts"; export { initRegistry, landscapeMap, portraitMap } from "./registry.uts";
......
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
/* 针对 1174x768 的样式 */ /* 针对 1174x768 的样式 */
&.layout-landscape-1174x768 { &.layout-landscape-1174x768 {
.login { .login {
background-color: blue; background-color: red;
} }
.title{ .title{
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!