All files / src/utils/typeGuards macklin.ts

92.23% Statements 95/103
100% Branches 18/18
90% Functions 9/10
92.23% Lines 95/103

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 2991x   1x               1x 1x                   1x                 1x 1x                 1x 1x 1x   1x                               1x 1x 12x 12x   1x 1x 1x 1x 1x   1x                               1x 1x 16x 16x   1x 1x 1x   1x                                 1x 1x 6x 6x   1x 1x 1x   1x                               1x 1x 7x 7x   1x                           1x 1x 16x 16x 16x 16x   1x                             1x 1x 10x 10x 10x           10x 10x 10x   1x 1x 1x   1x                                 1x 1x 13x 13x   1x                               1x 1x 14x   14x 14x 2x 2x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                 1x 1x 19x 19x   1x           1x 1x                    
import * as v from 'valibot';
 
/**
 * Macklin API paths used by the supplier module, relative to its API host.
 * @category Typeguards
 * @example
 * ```ts
 * ApiEndpoints.SEARCH; // "/api/item/search"
 * ```
 * @source
 */
export enum ApiEndpoints {
  TIMESTAMP = '/api/timestamp',
  SEARCH = '/api/item/search',
  USER_INFO = '/api/user/info',
  FRUIT_HEAD = '/api/fruit/head',
  FAVOURITE_ADD = '/api/favourite/add',
  FRUIT_ADD = '/api/fruit/add',
  QUICK_BUY = '/api/quick/buy',
}
 
/**
 * Macklin API paths that only respond to an authenticated session. Kept apart
 * from {@link ApiEndpoints} so callers can tell which requests need credentials.
 * @category Typeguards
 * @example
 * ```ts
 * AuthRequiredEndpoints.ORDER_LIST; // "/api/center/order_list"
 * ```
 * @source
 */
export enum AuthRequiredEndpoints {
  ORDER_LIST = '/api/center/order_list',
  EXPRESS = '/api/center/express',
  PREPAY = '/api/center/prepay',
  COUPON = '/api/center/coupon',
  ADDRESS_LIST = '/api/address/list',
  FRUIT_ORDER = '/api/fruit/order',
}
 
const timestampResponseSchema = v.object({
  timestamp: v.number(),
});
 
/**
 * Type guard to validate if data matches the Macklin timestamp response structure.
 * The timestamp endpoint returns the server's current Unix timestamp.
 *
 * @category Typeguards
 * @param data - The response data to validate
 * @returns Type predicate indicating if the data is a valid TimestampResponse
 * @example
 * ```typescript
 * const response = await fetch("/api/timestamp");
 * const data = await response.json();
 * if (isTimestampResponse(data.data)) {
 *   console.log("Server time:", data.data.timestamp);
 * }
 * ```
 * @source
 */
export function isTimestampResponse(data: unknown): data is TimestampResponse {
  return v.safeParse(timestampResponseSchema, data).success;
}
 
const macklinApiResponseSchema = v.object({
  code: v.number(),
  message: v.string(),
  data: v.custom((val) => val !== undefined),
});
 
/**
 * Validates if a response matches the Macklin API response format.
 * All API responses must have a code, message, and data field.
 *
 * @category Typeguards
 * @param data - The response to validate
 * @returns True if the response matches the MacklinApiResponse format
 * @example
 * ```ts
 * const response = await fetch('/api/item/search');
 * if (isMacklinApiResponse(response)) {
 *   // TypeScript now knows response has code, message, and data
 *   console.log(response.data);
 * }
 * ```
 * @source
 */
export function isMacklinApiResponse<T>(data: unknown): data is MacklinApiResponse<T> {
  return v.safeParse(macklinApiResponseSchema, data).success;
}
 
const macklinMsdsSearchResponseSchema = v.object({
  url: v.string(),
});
 
/**
 * Validates the unwrapped `data` payload of a successful MSDS search. `request`
 * strips the `{ code, message, data }` envelope, so a success yields `{ url }`
 * while error responses yield `[]`, which fails the `{ url }` shape — a positive
 * result therefore means an SDS URL is present.
 *
 * @category Typeguards
 * @param data - The unwrapped response data to validate
 * @returns Type predicate indicating the data is a successful MacklinMsdsSearchResponse
 * @example
 * ```ts
 * const data = await this.request("/api/msds/search", { params: { keyword } });
 * if (isMacklinMsdsSearchResponse(data)) {
 *   console.log(data.url);
 * }
 * ```
 * @source
 */
export function isMacklinMsdsSearchResponse(data: unknown): data is MacklinMsdsSearchResponse {
  return v.safeParse(macklinMsdsSearchResponseSchema, data).success;
}
 
const macklinProductInfoSchema = v.object({
  item: v.object({ chem_mw: v.string() }),
});
 
/**
 * Validates the `data` payload of the product info endpoint
 * (`POST /api/product/info`). Confirms `item.chem_mw` (the molecular weight) is
 * present so callers can safely read the chemistry fields.
 *
 * @category Typeguards
 * @param data - The unwrapped response data to validate
 * @returns Type predicate indicating the data is a valid MacklinProductInfo
 * @example
 * ```ts
 * const data = await this.request("/api/product/info", { method: "POST", body: { item_code } });
 * if (isMacklinProductInfo(data)) {
 *   builder.setMoleweight(data.item.chem_mw);
 * }
 * ```
 * @source
 */
export function isMacklinProductInfo(data: unknown): data is MacklinProductInfo {
  return v.safeParse(macklinProductInfoSchema, data).success;
}
 
/**
 * Validates if a URL requires authentication.
 * These endpoints require a valid user token in the X-User-Token header.
 *
 * @category Typeguards
 * @param url - The API endpoint URL to check
 * @returns True if the endpoint requires authentication
 * @example
 * ```ts
 * if (isAuthRequiredEndpoint('/api/center/order_list')) {
 *   // Add authentication headers
 * }
 * ```
 * @source
 */
export function isAuthRequiredEndpoint(url: string): boolean {
  // TS narrows enum-value arrays to the enum union; widen to string[] so
  // .includes accepts an arbitrary string argument.
  return (Object.values(AuthRequiredEndpoints) as string[]).includes(url);
}
 
/**
 * Validates if a URL is an authentication check endpoint.
 * These endpoints are used to verify the user's authentication status
 * and will return a specific error code (1005) if authentication fails.
 *
 * @category Typeguards
 * @param url - The API endpoint URL to check
 * @returns True if the endpoint is used for auth checks
 * @example
 * ```typescript
 * if (isAuthCheckEndpoint("/api/user/info")) {
 *   // Handle potential 1005 auth failure response
 * }
 * ```
 * @source
 */
export function isAuthCheckEndpoint(url: string): boolean {
  // Widen the enum-value array to string[] so .includes accepts an
  // arbitrary string argument (the array element type is the enum union).
  return (
    [
      ApiEndpoints.USER_INFO,
      ApiEndpoints.FRUIT_HEAD,
      ApiEndpoints.FAVOURITE_ADD,
      ApiEndpoints.FRUIT_ADD,
    ] as string[]
  ).includes(url);
}
 
const macklinSearchResultSchema = v.object({
  list: v.custom<object>((val) => typeof val === 'object' && val !== null),
});
 
/**
 * Validates if data matches the Macklin search result format.
 * Search results contain a list of products and a total count.
 * The list property is generic to support different product types.
 *
 * @category Typeguards
 * @param data - The data to validate
 * @returns True if the data matches the search result format
 * @example
 * ```ts
 * const response = await fetch('/api/item/search');
 * if (isMacklinSearchResult(response.data)) {
 *   // TypeScript now knows response.data has list and total
 *   console.log(response.data.total);
 * }
 * ```
 * @source
 */
export function isMacklinSearchResult<T>(data: unknown): data is MacklinSearchResult<T> {
  return v.safeParse(macklinSearchResultSchema, data).success;
}
 
/**
 * Validates if data matches the Macklin product details response format.
 * Product details response contains a list of product details.
 *
 * @category Typeguards
 * @param data - The data to validate
 * @returns True if the data matches the product details response format
 * @example
 * ```typescript
 * const response = await fetch("/api/product/list?code=B803083");
 * const data = await response.json();
 * if (isMacklinProductDetailsResponse(data.data)) {
 *   console.log("Products:", data.data.list.length);
 * }
 * ```
 * @source
 */
export function isMacklinProductDetailsResponse(
  data: unknown,
): data is MacklinProductDetailsResponse {
  if (typeof data !== 'object' || data === null) return false;
  if (!('list' in data) || !Array.isArray(data.list)) return false;
  return data.list.every(isMacklinProductDetails);
}
 
const macklinProductDetailsSchema = v.object({
  item_id: v.number(),
  item_code: v.string(),
  product_id: v.number(),
  product_code: v.string(),
  product_price: v.string(),
  product_unit: v.string(),
  product_locked_stock: v.string(),
  product_pack: v.string(),
  item_en_name: v.string(),
  product_stock: v.string(),
  chem_cas: v.string(),
  delivery_desc_show: v.string(),
});
 
/**
 * Validates if data matches the Macklin product details format.
 * Product details contain comprehensive information about a specific
 * product variant, including pricing, stock, and delivery information.
 *
 * @category Typeguards
 * @param data - The data to validate
 * @returns True if the data matches the product details format
 * @example
 * ```ts
 * const details = await fetch('/api/product/list?code=B803083');
 * if (isMacklinProductDetails(details)) {
 *   // TypeScript now knows details has all product information
 *   console.log(details.product_price);
 * }
 * ```
 * @source
 */
export function isMacklinProductDetails(data: unknown): data is MacklinProductDetails {
  return v.safeParse(macklinProductDetailsSchema, data).success;
}
 
/**
 * Type guard for TimestampStorage objects stored in local state.
 * @category Typeguards
 * @param data - The value to check
 * @returns Whether the value is a valid TimestampStorage
 * @source
 */
export function isTimestampStorage(data: unknown): data is TimestampStorage {
  return (
    typeof data === 'object' &&
    data !== null &&
    'serverTm' in data &&
    typeof data.serverTm === 'number' &&
    'clientTm' in data &&
    typeof data.clientTm === 'number'
  );
}