All files stringify.ts

100% Statements 30/30
89.65% Branches 26/29
100% Functions 3/3
100% Lines 29/29

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                  615x             1231x                     312x 305x 303x 303x 2x 1x   1x       310x 1x     309x 309x   309x 2x 1x     308x 312x   312x 312x 312x 312x 312x   312x 307x     308x 1x 1x       308x                                                                                                                                                                                                                                                                                                                    
import { defaults } from "./defaults.ts";
import { getEngine, toBuiltinLanguage } from "./engines.ts";
import type { GrayMatterFile, GrayMatterOptions } from "./types.ts";
import { isObject, isString } from "./utils.ts";
 
/**
 * Type guard for GrayMatterFile
 */
function isGrayMatterFile(val: unknown): val is GrayMatterFile {
  return isObject(val) && "content" in val && "data" in val;
}
 
/**
 * Ensure string ends with newline
 */
function newline(str: string): string {
  return str.slice(-1) !== "\n" ? str + "\n" : str;
}
 
/**
 * Stringify file object to string with front matter
 */
export function stringify(
  file: GrayMatterFile | string,
  data?: Record<string, unknown> | null,
  options?: GrayMatterOptions,
): string {
  if (data == null && options == null) {
    if (isGrayMatterFile(file)) {
      data = file.data;
      options = {};
    } else if (isString(file)) {
      return file;
    } else {
      throw new TypeError("expected file to be a string or object");
    }
  }
 
  if (!isGrayMatterFile(file)) {
    throw new TypeError("expected file to be a string or object");
  }
 
  const str = file.content;
  const opts = defaults(options);
 
  if (data == null) {
    if (!opts.data) return str;
    data = opts.data;
  }
 
  const language = toBuiltinLanguage(file.language || opts.language);
  const engine = getEngine(language);
 
  data = { ...file.data, ...data };
  const open = opts.delimiters[0];
  const close = opts.delimiters[1];
  const matter = engine.stringify!(data).trim();
  let buf = "";
 
  if (matter !== "{}") {
    buf = newline(open) + newline(matter) + newline(close);
  }
 
  if (isString(file.excerpt) && file.excerpt !== "") {
    Eif (str.indexOf(file.excerpt.trim()) === -1) {
      buf += newline(file.excerpt) + newline(close);
    }
  }
 
  return buf + newline(str);
}
 
if (import.meta.vitest) {
  const { fc, test } = await import("@fast-check/vitest");
 
  describe("stringify", () => {
    it("should stringify file object with data", () => {
      const file = {
        content: "hello world",
        data: { title: "Test" },
        excerpt: "",
        orig: new Uint8Array(),
        language: "yaml",
        matter: "",
        isEmpty: false,
        stringify: () => "",
      };
      const result = stringify(file);
      expect(result).toContain("---");
      expect(result).toContain("title: Test");
      expect(result).toContain("hello world");
    });
 
    it("should return string as-is when only string provided", () => {
      expect(stringify("hello")).toBe("hello");
    });
 
    it("should throw for invalid input", () => {
      expect(() => stringify(123 as unknown as string)).toThrow(TypeError);
    });
 
    it("should throw when file is not GrayMatterFile with data/options", () => {
      expect(() => stringify("not a file" as unknown as GrayMatterFile, { key: "value" })).toThrow(
        TypeError,
      );
    });
 
    it("should use opts.data when data is null", () => {
      const file = {
        content: "content",
        data: {},
        excerpt: "",
        orig: new Uint8Array(),
        language: "yaml",
        matter: "",
        isEmpty: false,
        stringify: () => "",
      };
      const result = stringify(file, null, { data: { fromOpts: true } });
      expect(result).toContain("fromOpts: true");
    });
 
    it("should return content only when data is null and opts.data is falsy", () => {
      const file = {
        content: "just content",
        data: {},
        excerpt: "",
        orig: new Uint8Array(),
        language: "yaml",
        matter: "",
        isEmpty: false,
        stringify: () => "",
      };
      const result = stringify(file, null, {});
      expect(result).toBe("just content");
    });
 
    it("should ensure trailing newline", () => {
      const file = {
        content: "no newline",
        data: { key: "value" },
        excerpt: "",
        orig: new Uint8Array(),
        language: "yaml",
        matter: "",
        isEmpty: false,
        stringify: () => "",
      };
      const result = stringify(file);
      expect(result.endsWith("\n")).toBe(true);
    });
 
    it("should not add front matter for empty data", () => {
      const file = {
        content: "content only",
        data: {},
        excerpt: "",
        orig: new Uint8Array(),
        language: "yaml",
        matter: "",
        isEmpty: false,
        stringify: () => "",
      };
      const result = stringify(file, {});
      expect(result).toBe("content only\n");
    });
 
    it("should include excerpt when present and not in content", () => {
      const file = {
        content: "main content",
        data: { title: "Test" },
        excerpt: "This is excerpt",
        orig: new Uint8Array(),
        language: "yaml",
        matter: "",
        isEmpty: false,
        stringify: () => "",
      };
      const result = stringify(file);
      expect(result).toContain("This is excerpt");
    });
 
    test.prop([
      fc.record({
        title: fc.string({ minLength: 1, maxLength: 50 }),
        count: fc.integer({ min: 0, max: 1000 }),
        enabled: fc.boolean(),
      }),
    ])("should always produce string ending with newline for any data", (data) => {
      const file = {
        content: "test content",
        data,
        excerpt: "",
        orig: new Uint8Array(),
        language: "yaml",
        matter: "",
        isEmpty: false,
        stringify: () => "",
      };
      const result = stringify(file);
      expect(result.endsWith("\n")).toBe(true);
    });
 
    test.prop([fc.string({ minLength: 0, maxLength: 100 })])(
      "should handle any content string",
      (content) => {
        const file = {
          content,
          data: { key: "value" },
          excerpt: "",
          orig: new Uint8Array(),
          language: "yaml",
          matter: "",
          isEmpty: false,
          stringify: () => "",
        };
        const result = stringify(file);
        expect(result).toBeTypeOf("string");
        expect(result.endsWith("\n")).toBe(true);
      },
    );
  });
}