summaryrefslogtreecommitdiff
path: root/src/flatmatter.ts
blob: e7e5f6ef95d45ddbb3b72b7593cf07e5caaab5f7 (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
import { EOL } from "node:os";
import * as Effect from "effect/Effect";
import * as Context from "effect/Context";
import * as Ref from "effect/Ref";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
import { trimChar } from "./utils.ts";

const ComputeAction = Schema.Struct({
  identifier: Schema.NonEmptyString,
  args: Schema.Array(Schema.Unknown),
});

const ParsedValue = Schema.Struct({
  value: Schema.Unknown,
  computeActions: Schema.Array(ComputeAction),
});

type Function = {
  name: string;
  compute(...args: unknown[]): unknown;
};

class FunctionsState extends Context.Tag("FunctionsState")<
  FunctionsState,
  Ref.Ref<Function[]>
>() {}

/**
 * State for holding the content string.
 */
class ContentState extends Context.Tag("ContentState")<
  ContentState,
  Ref.Ref<string>
>() {}

/**
 * State for holding the parsed configuration.
 */
class ConfigState extends Context.Tag("ConfigState")<
  ConfigState,
  Ref.Ref<Record<string, unknown>>
>() {}

const validateLineHasKeyValEffect = (idx: number, line: string) =>
  Effect.gen(function* () {
    if (!line.includes(":")) {
      yield* Effect.fail(
        Cause.fail(`Line on index ${idx} doesn't have a value separator.`),
      );
    }
  });

/**
 * Validates that the given line has only one value separator.
 */
const validateLineHasOnlyOneColonCharEffect = (idx: number, line: string) =>
  Effect.gen(function* () {
    let separatorCount = 0;
    let parts = line.split(":").slice(1);

    for (let i = 0; i < parts.length; i++) {
      const partsUntilCurrent = parts.slice(0, i).join(":");
      const quoteCount = partsUntilCurrent.split('"').length - 1;

      if (quoteCount % 2 === 0) {
        separatorCount++;
      }
    }

    if (separatorCount > 1) {
      yield* Effect.fail(
        Cause.fail(`Line on index ${idx} has multiple value separators.`),
      );
    }
  });

const validateLineConformanceEffect = (idx: number, line: string) =>
  Effect.gen(function* () {
    const validatorEffects = [
      validateLineHasKeyValEffect,
      validateLineHasOnlyOneColonCharEffect,
    ];

    for (const validatorEffect of validatorEffects) {
      yield* validatorEffect(idx, line);
    }
  });

const isSimpleValue = (value: string): boolean => {
  const isString = value.startsWith('"') && value.endsWith('"');
  const isBoolean = value === "true" || value === "false";
  const isNumber = !isNaN(parseFloat(value));

  return isString || isBoolean || isNumber;
};

const parseSimpleValue = (value: string): string | number | boolean => {
  if (value === "true" || value === "false") {
    return value === "true";
  }

  if (!Number.isNaN(parseInt(value)) && value.indexOf(".") === -1) {
    return parseInt(value);
  }

  if (!Number.isNaN(parseFloat(value)) && value.indexOf(".") !== -1) {
    return parseFloat(value);
  }

  return trimChar(value, '"');
};

const 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) => parseSimpleValue(part));
};

const parseFunctionValue = (
  value: string,
): Schema.Schema.Type<typeof ComputeAction> => {
  const isFn = value.startsWith("(") && value.endsWith(")");

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

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

  return ComputeAction.make({
    identifier: fnName,
    args: fnArgs,
  });
};

const 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;
};

const parseValueEffect = (value: string) =>
  Effect.gen(function* () {
    const parts = composePipedValueParts(value);

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

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

const computeValueEffect = (parsedValue: typeof ParsedValue.Type) =>
  Effect.gen(function* () {
    let value = parsedValue.value;
    const functions = yield* Ref.get(yield* FunctionsState);

    for (const computeAction of parsedValue.computeActions) {
      const fn = functions.find((f) => f.name === computeAction.identifier);

      if (!fn) {
        continue;
      }

      if (value !== null) {
        value = fn.compute(value, ...computeAction.args);
        continue;
      }

      value = fn.compute(...computeAction.args);
    }

    return value;
  });

const parseLineEffect = (idx: number, line: string) =>
  Effect.gen(function* () {
    yield* validateLineConformanceEffect(idx, line);

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

    const updatedConfig = keys.reduceRight(
      (acc, key) => {
        return { [key]: acc };
      },
      yield* computeValueEffect(parsedValue),
    ) as Record<string, unknown>;

    yield* Ref.update(yield* ConfigState, (config) => {
      return { ...config, ...updatedConfig };
    });
  });

const parseContentEffect = Effect.gen(function* () {
  const content = yield* Ref.get(yield* ContentState);
  const lines = content.split(EOL);
  let frontMatterBreakCount = 0;

  for (let i = 0; i < lines.length; i++) {
    if (lines[i].trim() === "---" && frontMatterBreakCount < 2) {
      frontMatterBreakCount++;
      continue;
    }

    if (frontMatterBreakCount < 2) {
      yield* parseLineEffect(i, lines[i]);
      continue;
    }

    // FlatMatter ends, Markdown begins
    yield* Ref.update(yield* ConfigState, (config) => {
      config.content = lines.slice(i).join(EOL).trim();
      return config;
    });

    break;
  }
});

/**
 *
 */
const composeConfigEffect = Effect.gen(function* () {
  yield* parseContentEffect;

  return yield* Ref.get(yield* ConfigState);
});

const config = (
  content: string,
  functions: Function[] = [],
): Record<string, unknown> => {
  return Effect.runSync(
    composeConfigEffect.pipe(
      Effect.provideServiceEffect(ContentState, Ref.make(content)),
      Effect.provideServiceEffect(ConfigState, Ref.make({})),
      Effect.provideServiceEffect(FunctionsState, Ref.make(functions)),
    ),
  );
};

export default {
  config,
};