{{ message }}
Repository navigation
Expand file tree
/
Copy pathliquid-tags.ts
More file actions
821 lines (707 loc) · 26.3 KB
/
Copy pathliquid-tags.ts
File metadata and controls
821 lines (707 loc) · 26.3 KB
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
// @purpose Writer tool
// @description Expand and restore Liquid data references in content files
// Usage: npm run liquid-tags -- expand --paths content/pull-requests/about.md
// Usage: npm run liquid-tags -- restore --paths content/pull-requests/about.md
import { Command } from 'commander'
import fs from 'fs'
import path from 'path'
import { load, dump } from 'js-yaml'
import chalk from 'chalk'
interface ExpandOptions {
paths: string[]
verbose?: boolean
markers?: boolean
dryRun?: boolean
reusablesOnly?: boolean
variablesOnly?: boolean
shallow?: boolean
}
interface LiquidReference {
original: string
type: 'reusable' | 'variable'
path: string
startIndex: number
endIndex: number
}
const ROOT = process.env.ROOT || '.'
const DATA_ROOT = path.resolve(path.join(ROOT, 'data'))
const REUSABLES_ROOT = path.join(DATA_ROOT, 'reusables')
const VARIABLES_ROOT = path.join(DATA_ROOT, 'variables')
function getErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
const EXPANDED_PATTERN = /<!-- begin (reusable|variable)s\.([^>]+) -->(.+?)<!-- end \1s\.\2 -->/gs
// Reject absolute, traversal, empty, and unsafe data paths before resolving under data root.
function getDataFilePath(type: 'reusable' | 'variable', dataPath: string): string {
if (path.isAbsolute(dataPath)) {
throw new Error(`Invalid ${type} data path: absolute paths are not allowed: ${dataPath}`)
}
const segments = dataPath.split(/[\\/]/)
if (segments.some((segment) => segment === '..' || segment === '')) {
throw new Error(`Invalid ${type} data path: contains disallowed segments: ${dataPath}`)
}
// Restrict data paths to filename characters used by reusables and variables.
if (!/^[A-Za-z0-9_.\-/]+$/.test(dataPath)) {
throw new Error(`Invalid ${type} data path: contains disallowed characters: ${dataPath}`)
}
if (type === 'reusable') {
const baseRoot = path.resolve(REUSABLES_ROOT)
const relativePath = dataPath.replace(/\./g, '/')
const candidatePath = path.resolve(baseRoot, `${relativePath}.md`)
if (!candidatePath.startsWith(baseRoot + path.sep)) {
throw new Error(`Invalid reusable data path: escapes reusables root: ${dataPath}`)
}
return candidatePath
} else {
const baseRoot = path.resolve(VARIABLES_ROOT)
const fileName = dataPath.split('.')[0]
const candidatePath = path.resolve(baseRoot, `${fileName}.yml`)
if (!candidatePath.startsWith(baseRoot + path.sep)) {
throw new Error(`Invalid variable data path: escapes variables root: ${dataPath}`)
}
return candidatePath
}
}
function convertFilePathToDataPath(filePath: string): string {
const normalizedPath = path.normalize(filePath)
if (normalizedPath.includes('reusables')) {
const relativePath = path.relative(REUSABLES_ROOT, normalizedPath)
return `reusables.${relativePath.replace(/\.md$/, '').replace(/[\\/]/g, '.')}`
} else if (normalizedPath.includes('variables')) {
const relativePath = path.relative(VARIABLES_ROOT, normalizedPath)
return `variables.${relativePath.replace(/\.yml$/, '').replace(/[\\/]/g, '.')}`
}
return filePath
}
const program = new Command()
program
.name('liquid-tags')
.description('Tools to expand and restore Liquid data references in content files')
program
.command('expand')
.description('Expand {% data reusables %} and {% data variables %} statements to their content')
.option('--paths <paths...>', 'Content file paths to process', [])
.option('-v, --verbose', 'Verbose output', false)
.option('--no-markers', 'Skip HTML comment markers (output cannot be restored to Liquid)', true)
.option('--reusables-only', 'Process only reusables (skip variables)', false)
.option('--variables-only', 'Process only variables (skip reusables)', false)
.option('--shallow', 'Expand only one level (do not expand nested references)', false)
.action((options: ExpandOptions) => expandReferences(options))
program
.command('restore')
.description('Restore original Liquid statements from HTML comment markers')
.option('--paths <paths...>', 'Content file paths to process', [])
.option('-v, --verbose', 'Verbose output', false)
.option('--reusables-only', 'Process only reusables (skip variables)', false)
.option('--variables-only', 'Process only variables (skip reusables)', false)
.action((options: ExpandOptions) => restoreReferences(options))
program.parse()
function getAllowedTypes(options: ExpandOptions): Array<'reusable' | 'variable'> {
if (options.reusablesOnly && options.variablesOnly) {
console.log(
chalk.yellow(
'Warning: Both --reusables-only and --variables-only specified. Processing both types.',
),
)
return ['reusable', 'variable']
}
if (options.reusablesOnly) {
return ['reusable']
}
if (options.variablesOnly) {
return ['variable']
}
return ['reusable', 'variable']
}
async function expandReferences(options: ExpandOptions): Promise<void> {
const { paths, verbose, markers, shallow } = options
// --no-markers sets markers to false; missing flag leaves it true.
const withMarkers = markers !== false
const recursive = !shallow // Omitting --shallow enables recursive expansion.
const allowedTypes = getAllowedTypes(options)
const maxIterations = 10 // Stop recursive expansion after 10 passes to avoid circular references.
if (paths.length === 0) {
console.error(chalk.red('Error: No paths provided. Use --paths option.'))
process.exit(1)
}
for (const filePath of paths) {
try {
let iteration = 0
let hasRemainingRefs = true
while (hasRemainingRefs && iteration < maxIterations) {
iteration++
if (verbose && recursive && iteration > 1) {
console.log(chalk.blue(`Processing (iteration ${iteration}): ${filePath}`))
} else if (verbose) {
console.log(chalk.blue(`Processing: ${filePath}`))
if (allowedTypes.length < 2) {
console.log(chalk.dim(` Only processing: ${allowedTypes.join(', ')}`))
}
}
if (!fs.existsSync(filePath)) {
console.error(chalk.red(`Error: File not found: ${filePath}`))
break
}
const content = fs.readFileSync(filePath, 'utf-8')
const expandedContent = await expandFileContent(
content,
filePath,
verbose,
withMarkers,
allowedTypes,
)
if (expandedContent !== content) {
fs.writeFileSync(filePath, expandedContent, 'utf-8')
if (iteration === 1 || !recursive) {
console.log(chalk.green(`✓ Expanded references in: ${filePath}`))
}
} else {
if (verbose && iteration === 1) {
console.log(chalk.gray(` No references found in: ${filePath}`))
}
}
const remainingRefs = findLiquidReferences(expandedContent, allowedTypes)
hasRemainingRefs = remainingRefs.length > 0
if (shallow) {
if (hasRemainingRefs) {
console.log(
chalk.yellow(
`👉 FYI: ${remainingRefs.length} Liquid reference(s) remain in ${filePath}`,
),
)
console.log(
chalk.yellow(
' These come from reusables/variables that contain references to other reusables/variables',
),
)
console.log(
chalk.yellow(
' Run the expand command again to expand them, or omit --shallow for full expansion',
),
)
if (verbose) {
for (const ref of remainingRefs) {
console.log(chalk.dim(` ${ref.original}`))
}
} else {
console.log(chalk.dim(' Use --verbose to see the specific references'))
}
}
break
}
if (hasRemainingRefs && iteration >= maxIterations) {
console.log(
chalk.yellow(`⚠️ Reached maximum iterations (${maxIterations}) for ${filePath}`),
)
console.log(
chalk.yellow(
` ${remainingRefs.length} reference(s) still remain - there may be circular references`,
),
)
if (verbose) {
for (const ref of remainingRefs) {
console.log(chalk.dim(` ${ref.original}`))
}
}
} else if (!hasRemainingRefs && iteration > 1) {
console.log(
chalk.green(
`✓ Fully expanded all references in: ${filePath} (${iteration} iterations)`,
),
)
}
}
} catch (error: unknown) {
console.error(chalk.red(`Error processing ${filePath}: ${getErrorMessage(error)}`))
}
}
}
async function restoreReferences(options: ExpandOptions): Promise<void> {
const { paths, verbose } = options
const allowedTypes = getAllowedTypes(options)
if (paths.length === 0) {
console.error(chalk.red('Error: No paths provided. Use --paths option.'))
process.exit(1)
}
// Compare every file with pre-restore data so a later unedited copy cannot overwrite an edit.
const restorePaths: string[] = []
const updates: ReturnType<typeof extractDataUpdates> = []
let hasAnyEdits = false
for (const filePath of paths) {
try {
if (verbose) {
console.log(chalk.blue(`Restoring: ${filePath}`))
if (allowedTypes.length < 2) {
console.log(chalk.dim(` Only processing: ${allowedTypes.join(', ')}`))
}
}
if (!fs.existsSync(filePath)) {
console.error(chalk.red(`Error: File not found: ${filePath}`))
continue
}
const content = fs.readFileSync(filePath, 'utf-8')
const hasEdits = await detectContentEdits(content, verbose, allowedTypes)
if (hasEdits) {
hasAnyEdits = true
console.log(
chalk.blue(
`${filePath} contains expanded references; any edits made will be preserved in data files`,
),
)
if (!verbose) {
console.log(chalk.dim(' Use --verbose to see details of the edits'))
}
updates.push(...extractDataUpdates(content, allowedTypes))
}
restorePaths.push(filePath)
} catch (error: unknown) {
console.error(chalk.red(`Error restoring ${filePath}: ${getErrorMessage(error)}`))
}
}
if (hasAnyEdits) {
// Write edited expanded blocks back to data files before restoring Liquid tags.
const updatedDataFiles = updateDataFiles(updates, verbose, false)
// Restore updated data files so nested references return to Liquid tags too.
if (updatedDataFiles.length > 0) {
if (verbose) console.log(chalk.blue(' Restoring updated data files back to liquid tags...'))
for (const dataFile of updatedDataFiles) {
try {
const dataContent = fs.readFileSync(dataFile, 'utf-8')
// Data files should never keep markers, whichever types were selected.
const restoredDataContent = restoreFileContent(dataContent, verbose)
if (restoredDataContent !== dataContent) {
fs.writeFileSync(dataFile, restoredDataContent, 'utf-8')
if (verbose) {
const dataPath = convertFilePathToDataPath(dataFile)
console.log(chalk.green(` Restored: ${dataPath}`))
}
}
} catch (error) {
if (verbose) {
const dataPath = convertFilePathToDataPath(dataFile)
console.log(chalk.yellow(` Could not restore ${dataPath}: ${error}`))
}
}
}
}
}
for (const filePath of restorePaths) {
try {
// Re-read so an input that is also an updated data file keeps its saved edit.
const content = fs.readFileSync(filePath, 'utf-8')
// Restore the main file even when no data file changed.
const restoredContent = restoreFileContent(content, verbose, allowedTypes)
if (restoredContent !== content) {
fs.writeFileSync(filePath, restoredContent, 'utf-8')
console.log(chalk.green(`✓ Restored references in: ${filePath}`))
} else {
console.log(chalk.gray(`No expanded references found in: ${filePath}`))
}
} catch (error: unknown) {
console.error(chalk.red(`Error restoring ${filePath}: ${getErrorMessage(error)}`))
}
}
}
async function expandFileContent(
content: string,
filePath: string,
verbose?: boolean,
withMarkers?: boolean,
allowedTypes?: Array<'reusable' | 'variable'>,
): Promise<string> {
const references = findLiquidReferences(content, allowedTypes)
if (references.length === 0) {
return content
}
let expandedContent = content
let offset = 0
for (const ref of references) {
try {
const resolvedValue = await resolveLiquidReference(ref, verbose)
if (resolvedValue !== null) {
const originalText = ref.original
let replacement: string
if (withMarkers) {
const commentStart = `<!-- begin ${ref.type}s.${ref.path} -->`
const commentEnd = `<!-- end ${ref.type}s.${ref.path} -->`
replacement = `${commentStart}${resolvedValue}${commentEnd}`
} else {
replacement = resolvedValue
}
const startPos = ref.startIndex + offset
const endPos = ref.endIndex + offset
expandedContent =
expandedContent.substring(0, startPos) + replacement + expandedContent.substring(endPos)
offset += replacement.length - originalText.length
if (verbose) {
console.log(chalk.green(` Expanded: ${ref.type}s.${ref.path}`))
}
} else {
if (verbose) {
console.log(chalk.yellow(` Warning: Could not expand ${ref.type}s.${ref.path}`))
}
}
} catch (error: unknown) {
if (verbose) {
console.log(
chalk.red(` Error expanding ${ref.type}s.${ref.path}: ${getErrorMessage(error)}`),
)
}
}
}
// expandReferences handles remaining-reference detection in recursive mode.
return expandedContent
}
async function detectContentEdits(
content: string,
verbose?: boolean,
allowedTypes?: Array<'reusable' | 'variable'>,
): Promise<boolean> {
let hasEdits = false
for (const [, type, dataPath, resolvedContent] of content.matchAll(EXPANDED_PATTERN)) {
const refType = type as 'reusable' | 'variable'
const selected = !allowedTypes || allowedTypes.includes(refType)
if (selected) {
try {
const originalContent = loadDataValue(refType, dataPath.trim())
if (originalContent !== null) {
// Nested expanded blocks must become Liquid tags again to match the raw data value.
const currentContent = restoreFileContent(resolvedContent).trim()
if (currentContent !== originalContent.trim()) {
hasEdits = true
if (verbose) {
console.log(chalk.yellow(` Content has been edited: ${type}s.${dataPath}`))
console.log(
chalk.dim(' Original:'),
originalContent.substring(0, 50) + (originalContent.length > 50 ? '...' : ''),
)
console.log(
chalk.dim(' Current: '),
currentContent.substring(0, 50) + (currentContent.length > 50 ? '...' : ''),
)
}
}
}
} catch (error) {
if (verbose) {
console.log(chalk.yellow(` Could not verify content for ${type}s.${dataPath}: ${error}`))
}
}
}
// EXPANDED_PATTERN matches only the outermost block, and a selected block collapses all types.
if (await detectContentEdits(resolvedContent, verbose, selected ? undefined : allowedTypes)) {
hasEdits = true
}
}
return hasEdits
}
function loadDataValue(type: 'reusable' | 'variable', dataPath: string): string | null {
try {
const targetPath = getDataFilePath(type, dataPath)
if (!fs.existsSync(targetPath)) {
return null
}
if (type === 'reusable') {
const content = fs.readFileSync(targetPath, 'utf8')
// Strip reusable frontmatter before comparing content, matching resolveReusable.
const contentWithoutFrontmatter = content.replace(/^---[\s\S]*?---\s*/, '')
return contentWithoutFrontmatter.trim()
} else {
const yamlContent = fs.readFileSync(targetPath, 'utf8')
const data = load(yamlContent) as Record<string, unknown>
const pathParts = dataPath.split('.')
let current: unknown = data
for (let i = 1; i < pathParts.length; i++) {
if (current && typeof current === 'object' && pathParts[i] in current) {
current = (current as Record<string, unknown>)[pathParts[i]]
} else {
return null
}
}
return typeof current === 'string' ? current.trim() : String(current).trim()
}
} catch {
// Unreadable data returns null so callers can treat it as unverifiable.
}
return null
}
function restoreFileContent(
content: string,
verbose?: boolean,
allowedTypes?: Array<'reusable' | 'variable'>,
): string {
return content.replace(EXPANDED_PATTERN, (match, type, dataPath, resolvedContent) => {
const refType = type as 'reusable' | 'variable'
if (!allowedTypes || allowedTypes.includes(refType)) {
const originalLiquid = `{% data ${type}s.${dataPath} %}`
if (verbose) {
console.log(chalk.green(` Restored: ${type}s.${dataPath}`))
}
return originalLiquid
}
// Keep the unselected outer block, but restore selected blocks nested inside it.
const restoredInner = restoreFileContent(resolvedContent, verbose, allowedTypes)
return `<!-- begin ${type}s.${dataPath} -->${restoredInner}<!-- end ${type}s.${dataPath} -->`
})
}
function updateDataFiles(
updates: ReturnType<typeof extractDataUpdates>,
verbose?: boolean,
dryRun?: boolean,
): string[] {
if (updates.length === 0) {
if (verbose) {
console.log(chalk.yellow(' No content changes found'))
}
return []
}
const updatesByFile = new Map<string, string[]>()
for (const update of updates) {
const key = `${update.type}:${update.path}`
if (!updatesByFile.has(key)) {
updatesByFile.set(key, [])
}
updatesByFile.get(key)!.push(update.newContent)
}
const updatedFiles: string[] = []
for (const [key, contents] of updatesByFile) {
const [type, dataPath] = key.split(':')
const targetFilePath = applyDataUpdates(
type as 'reusable' | 'variable',
dataPath,
contents,
verbose,
dryRun,
)
if (targetFilePath) {
updatedFiles.push(targetFilePath)
}
}
return updatedFiles
}
function extractDataUpdates(
content: string,
allowedTypes?: Array<'reusable' | 'variable'>,
): Array<{ type: 'reusable' | 'variable'; path: string; newContent: string }> {
const updates: Array<{ type: 'reusable' | 'variable'; path: string; newContent: string }> = []
for (const [, type, dataPath, resolvedContent] of content.matchAll(EXPANDED_PATTERN)) {
const refType = type as 'reusable' | 'variable'
const selected = !allowedTypes || allowedTypes.includes(refType)
if (selected) {
// Restore nested blocks of every type so data files keep Liquid tags, not markers.
const newContent = restoreFileContent(resolvedContent).trim()
try {
const originalContent = loadDataValue(refType, dataPath.trim())
if (originalContent !== null && newContent !== originalContent.trim()) {
updates.push({ type: refType, path: dataPath.trim(), newContent })
}
} catch {
// Keep blocks on unexpected errors; unreadable files return null from loadDataValue.
updates.push({ type: refType, path: dataPath.trim(), newContent })
}
}
// EXPANDED_PATTERN matches only the outermost block, and a selected block collapses all types.
updates.push(...extractDataUpdates(resolvedContent, selected ? undefined : allowedTypes))
}
return updates
}
function applyDataUpdates(
type: 'reusable' | 'variable',
dataPath: string,
contents: string[],
verbose?: boolean,
dryRun?: boolean,
): string | null {
const targetPath = getDataFilePath(type, dataPath)
if (!fs.existsSync(targetPath)) {
if (verbose) {
console.log(chalk.red(` Error: Data file not found: ${targetPath}`))
}
return null
}
if (dryRun) {
if (verbose) {
console.log(chalk.blue(` Would update: ${targetPath}`))
if (contents.length > 1) {
console.log(
chalk.yellow(
` Warning: Multiple content blocks found for ${dataPath}, would use first one`,
),
)
}
console.log(
chalk.dim(
` New content: ${contents[0].substring(0, 100)}${contents[0].length > 100 ? '...' : ''}`,
),
)
} else {
console.log(chalk.green(` Updated: ${targetPath}`))
}
return targetPath // Dry runs return the target path so callers can report it.
}
try {
if (type === 'reusable') {
if (contents.length > 1) {
console.log(
chalk.yellow(` Warning: Multiple content blocks found for ${dataPath}, using first one`),
)
}
// Preserve a trailing newline from the original reusable file.
const originalContent = fs.readFileSync(targetPath, 'utf8')
const hasTrailingNewline = originalContent.endsWith('\n')
const newContent =
hasTrailingNewline && !contents[0].endsWith('\n') ? `${contents[0]}\n` : contents[0]
fs.writeFileSync(targetPath, newContent)
if (verbose) {
console.log(chalk.green(` Updated: ${type}s.${dataPath}`))
}
} else {
const yamlContent = fs.readFileSync(targetPath, 'utf8')
const data = load(yamlContent) as Record<string, unknown>
const pathParts = dataPath.split('.')
const propertyPath = pathParts.slice(1)
let current: Record<string, unknown> = data
for (let i = 0; i < propertyPath.length - 1; i++) {
if (!current[propertyPath[i]]) {
current[propertyPath[i]] = {}
}
current = current[propertyPath[i]] as Record<string, unknown>
}
const finalKey = propertyPath[propertyPath.length - 1]
if (contents.length > 1) {
console.log(
chalk.yellow(` Warning: Multiple content blocks found for ${dataPath}, using first one`),
)
}
current[finalKey] = contents[0]
// Preserve a trailing newline from the original YAML file.
const hasTrailingNewline = yamlContent.endsWith('\n')
const yamlOutput = dump(data)
const finalYaml =
hasTrailingNewline && !yamlOutput.endsWith('\n') ? `${yamlOutput}\n` : yamlOutput
fs.writeFileSync(targetPath, finalYaml)
if (verbose) {
console.log(chalk.green(` Updated: ${type}s.${dataPath}`))
}
}
return targetPath
} catch (error: unknown) {
if (verbose) {
console.log(chalk.red(` Error updating ${type}s.${dataPath}: ${getErrorMessage(error)}`))
}
return null
}
}
function findLiquidReferences(
content: string,
allowedTypes?: Array<'reusable' | 'variable'>,
): LiquidReference[] {
const references: LiquidReference[] = []
const types = allowedTypes || ['reusable', 'variable']
// Match data references for reusables and variables.
const liquidPattern = /{%\s*data\s+(reusables|variables)\.([^%]+)\s*%}/g
let match
while ((match = liquidPattern.exec(content)) !== null) {
const [original, type, dataPath] = match
const refType = type.slice(0, -1) as 'reusable' | 'variable'
if (types.includes(refType)) {
references.push({
original,
type: refType,
path: dataPath.trim(),
startIndex: match.index,
endIndex: match.index + original.length,
})
}
}
return references
}
async function resolveLiquidReference(
ref: LiquidReference,
verbose?: boolean,
): Promise<string | null> {
try {
if (ref.type === 'reusable') {
return await resolveReusable(ref.path, verbose)
} else if (ref.type === 'variable') {
return await resolveVariable(ref.path, verbose)
}
} catch (error: unknown) {
if (verbose) {
console.log(chalk.red(` Error resolving ${ref.type}: ${getErrorMessage(error)}`))
}
}
return null
}
async function resolveReusable(reusablePath: string, verbose?: boolean): Promise<string | null> {
const filePath = getDataFilePath('reusable', reusablePath)
if (!fs.existsSync(filePath)) {
if (verbose) {
console.log(chalk.yellow(` Reusable not found: ${reusablePath}`))
}
return null
}
try {
const content = fs.readFileSync(filePath, 'utf-8')
// Strip reusable frontmatter before inserting its body.
const contentWithoutFrontmatter = content.replace(/^---[\s\S]*?---\s*/, '')
return contentWithoutFrontmatter.trim()
} catch (error: unknown) {
if (verbose) {
console.log(
chalk.yellow(` Error reading reusable ${reusablePath}: ${getErrorMessage(error)}`),
)
}
return null
}
}
async function resolveVariable(variablePath: string, verbose?: boolean): Promise<string | null> {
const pathParts = variablePath.split('.')
if (pathParts.length < 2) {
if (verbose) {
console.log(chalk.yellow(` Invalid variable path: ${variablePath}`))
}
return null
}
const filePath = getDataFilePath('variable', variablePath)
if (!fs.existsSync(filePath)) {
if (verbose) {
console.log(chalk.yellow(` Variable file not found: ${filePath}`))
}
return null
}
try {
const yamlContent = fs.readFileSync(filePath, 'utf-8')
const data = load(yamlContent) as Record<string, unknown>
// Variable paths start with the file name; remaining segments address YAML keys.
const [, ...keyPath] = pathParts
let value: unknown = data
for (const key of keyPath) {
if (value && typeof value === 'object' && key in value) {
value = (value as Record<string, unknown>)[key]
} else {
if (verbose) {
console.log(chalk.yellow(` Variable key not found: ${variablePath}`))
}
return null
}
}
if (typeof value === 'string') {
return value
} else if (value !== null && value !== undefined) {
return String(value)
} else {
if (verbose) {
console.log(chalk.yellow(` Variable value is null/undefined: ${variablePath}`))
}
return null
}
} catch (error: unknown) {
if (verbose) {
console.log(
chalk.yellow(` Error parsing variable ${variablePath}: ${getErrorMessage(error)}`),
)
}
return null
}
}
You can’t perform that action at this time.
