summaryrefslogtreecommitdiff
path: root/src/flatmatter.ts
blob: 84c8b7b657a27d1ec31b46016641b92151ec3e33 (plain)
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import { trimChar } from "./utils.ts";

export type Matter = {
  [key: string]: Matter | unknown;
};

export type ConformanceResult = {
  passed: boolean;
  error?: string;
};

export type ParsedValue = {
  value: unknown;
  computeActions: ComputeAction[];
};

export type ComputeAction = {
  identifier: string;
  args: Array<unknown>;
};

export interface Serializer {
  serialize(parsedConfig: Matter): unknown;
}

export interface FlatMatterFn {
  name: string;

  compute(args: unknown[]): unknown;
}

export default class FlatMatter {
  private content: string;
  private parsedConfig: Matter = {};
  private functions: FlatMatterFn[];

  constructor(content: string, functions: FlatMatterFn[] = []) {
    this.content = content;
    this.functions = functions;
    this.parse();

    console.log("done");
  }

  private parse(): void {
    for (const line of this.content.split(/\r?\n/)) {
      this.parseLine(line);
    }
  }

  /**
   * Parses a given line of FlatMatter.
   *
   * @param {string} line
   * @returns {void}
   */
  private parseLine(line: string): void {
    this.validateLineConformance(line);

    const keys = line.split(":")[0].trim().split(".");
    const value = line.split(":").slice(1).join(":").trim();
    const parsedValue = this.parseValue(value);

    if (!parsedValue) return;

    const config = keys.reduceRight((acc, key) => {
      return { [key]: acc };
    }, this.computeValue(parsedValue)) as Matter;

    this.parsedConfig = { ...this.parsedConfig, ...config };
  }

  private validateLineConformance(line: string): void {
  }

  private validateLineHasKeyVal(line: string): ConformanceResult {
    return {
      passed: true,
    };
  }

  private validateLineHasOnlyOneColonChar(line: string): ConformanceResult {
    return {
      passed: true,
    };
  }

  /**
   * Detects if the value is a simple value. A simple value is any
   * of the following: `"a string"`, boolean `true` or `false`, or
   * anything numeric like `12345` or `123.45`.
   *
   * @param {string} value
   * @returns {boolean}
   */
  private isSimpleValue(value: string): boolean {
    const isString = value.startsWith('"') && value.endsWith('"');
    const isBoolean = value === "true" || value === "false";
    const isNumber = !Number.isNaN(value);

    return isString || isBoolean || isNumber;
  }

  /**
   * Detects if the value is a function value. A function value is any
   * of the following:
   *
   * - A function call with arguments: `(function-name *args)`
   * - A function call by reference: `function-name`
   *
   * @param {string} value
   * @returns {boolean}
   */
  private isFunctionValue(value: string): boolean {
    const isFnCall = value.startsWith("(") && value.endsWith(")");
    const isFnReference = !!value.match(/^([a-zA-Z0-9_-]+)$/);

    return isFnCall || isFnReference;
  }

  /**
   * Detects if the value is a piped value. A piped value is a mix of
   * simple and function value parts, piped together with the forward
   * slash `/` character. For example:
   *
   * ```yaml
   * posts: (get-content "posts") / (limit 10) / only-published
   * ```
   *
   * or:
   *
   *  ```yaml
   * posts: "posts" / get-content / (limit 10) / only-published
   * ```
   *
   * The result of the previous pipe gets passed to the next as a first
   * argument.
   *
   * @param {string} value
   * @returns {boolean}
   */
  private isPipedValue(value: string): boolean {
    for (const part of this.composePipedValueParts(value)) {
      if (!this.isSimpleValue(part) && !this.isFunctionValue(part)) {
        return false;
      }
    }

    return true;
  }

  /**
   * Parses a value to a `ParsedValue` object, or `null`
   * in case it could not for whatever reason.
   *
   * @param {string} value
   * @returns {ParsedValue | null}
   */
  private parseValue(value: string): ParsedValue | null {
    if (this.isSimpleValue(value)) {
      return {
        value: this.parseSimpleValue(value),
        computeActions: [],
      };
    }

    if (this.isFunctionValue(value)) {
      return {
        value: null,
        computeActions: [
          this.parseFunctionValue(value),
        ],
      };
    }

    if (this.isPipedValue(value)) {
      return this.parsePipedValue(value);
    }

    return null;
  }

  /**
   * Parses the value part of a line into a simple value, like for example
   * a `string`, `number` or `boolean`.
   *
   * @param {string} value
   * @returns {string | number | boolean}
   */
  private parseSimpleValue(value: string): string | number | boolean {
    if (value === "true" || value === "false") {
      return value === "true";
    }

    if (!Number.isNaN(parseFloat(value))) {
      return parseFloat(value);
    }

    if (!Number.isNaN(parseInt(value))) {
      return parseInt(value);
    }

    return value.substring(1, value.length - 1);
  }

  /**
   * Parses the value part of a line into a Compute Action, which is
   * later executed to run the function described in FlatMatter.
   *
   * @param {string} value
   * @returns {ComputeAction}
   */
  private parseFunctionValue(value: string): ComputeAction {
    const isFn = value.startsWith("(") && value.endsWith(")");

    if (!isFn) {
      return {
        identifier: value,
        args: [],
      };
    }

    const fnName = trimChar(value, ["(", ")"]).split(" ")[0]
      .trim();
    const fnArgs = this.parseFunctionValueArgs(value);

    return {
      identifier: fnName,
      args: fnArgs,
    };
  }

  /**
   * Parses the value part of a line into a ParsedValue, which is
   * composed out of piped parts separated by the forward slash `/` character.
   *
   * The ParsedValue will include the default value, if any, and a list of compute
   * actions which will later be executed.
   *
   * @param {string} value
   * @returns {ParsedValue}
   */
  private parsePipedValue(value: string): ParsedValue {
    const parts = this.composePipedValueParts(value);

    if (this.isSimpleValue(parts[0])) {
      return {
        value: this.parseSimpleValue(parts[0]),
        computeActions: parts.slice(1).map((p) => this.parseFunctionValue(p)),
      };
    }

    return {
      value: null,
      computeActions: parts.map((p) => this.parseFunctionValue(p)),
    };
  }

  /**
   * Takes the entire value part of a line and, assuming it is a function value,
   * parses it into a list of arguments to be passed down to the function.
   *
   * @param {string} value
   * @returns {unknown[]}
   */
  private parseFunctionValueArgs(value: string): unknown[] {
    const parts = value.substring(1, value.length - 1).split(" ").slice(1);

    if (!parts.length) {
      return [];
    }

    const normalizedParts = [parts[0]];

    for (let i = 1; i < parts.length; i++) {
      const untilCurrent = normalizedParts.join(" ");
      const quoteCount = untilCurrent.split('"').length - 1;

      if (quoteCount % 2 === 0) {
        normalizedParts.push(parts[i]);
        continue;
      }

      const lastIndex = normalizedParts.length - 1;
      const lastPart = normalizedParts[lastIndex];

      normalizedParts[lastIndex] = `${lastPart} ${parts[i]}`;
    }

    return normalizedParts.map((part) => this.parseSimpleValue(part));
  }

  /**
   * Takes an entire value of a line and composes it into a list
   * of piped parts.
   *
   * @param {string} value
   * @returns {string[]}
   */
  private composePipedValueParts(value: string): string[] {
    const parts = value.split(" / ");
    const normalizedParts = [parts[0]];

    for (let i = 1; i < parts.length; i++) {
      const untilCurrent = normalizedParts.join(" / ");
      const quoteCount = untilCurrent.split('"').length - 1;

      if (quoteCount % 2 === 0) {
        normalizedParts.push(parts[i]);
        continue;
      }

      const lastIndex = normalizedParts.length - 1;
      const lastPart = normalizedParts[lastIndex];

      normalizedParts[lastIndex] = `${lastPart} / ${parts[i]}`;
    }

    return normalizedParts;
  }

  /**
   * Takes ParsedValue and, optionally an initial value, and runs
   * compute actions over it to return the final computed value.
   *
   * @param {ParsedValue} parsedValue
   * @returns {unknown}
   */
  private computeValue(parsedValue: ParsedValue): unknown {
    let value = parsedValue.value;

    for (const ca of parsedValue.computeActions) {
      const fnInstance = this.functions.find((f) => f.name === ca.identifier);

      if (!fnInstance) {
        continue;
      }

      if (value !== null) {
        ca.args = [value, ...ca.args];
      }

      value = fnInstance.compute(ca.args);
    }

    return value;
  }

  /**
   * Takes a Serializer and uses it to transform internal data
   * object to a desired output.
   *
   * @param {Serializer} serializer
   * @returns {unknown}
   */
  public serialize(serializer: Serializer): unknown {
    return serializer.serialize(this.parsedConfig);
  }
}