@imjp/writenex-astro 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +539 -0
  2. package/dist/chunk-5PM6EQE5.js +151 -0
  3. package/dist/chunk-5PM6EQE5.js.map +1 -0
  4. package/dist/chunk-7XU5X6CW.js +1331 -0
  5. package/dist/chunk-7XU5X6CW.js.map +1 -0
  6. package/dist/chunk-AAOQHQPU.js +574 -0
  7. package/dist/chunk-AAOQHQPU.js.map +1 -0
  8. package/dist/chunk-CF2XXJFF.js +1410 -0
  9. package/dist/chunk-CF2XXJFF.js.map +1 -0
  10. package/dist/chunk-CRPZUUDU.js +52 -0
  11. package/dist/chunk-CRPZUUDU.js.map +1 -0
  12. package/dist/chunk-CYLDJ3HZ.js +310 -0
  13. package/dist/chunk-CYLDJ3HZ.js.map +1 -0
  14. package/dist/chunk-KIKIPIFA.js +1 -0
  15. package/dist/chunk-KIKIPIFA.js.map +1 -0
  16. package/dist/chunk-XNTQTTJU.js +145 -0
  17. package/dist/chunk-XNTQTTJU.js.map +1 -0
  18. package/dist/client/index.css +2 -0
  19. package/dist/client/index.css.map +1 -0
  20. package/dist/client/index.js +375 -0
  21. package/dist/client/index.js.map +1 -0
  22. package/dist/client/styles.css +584 -0
  23. package/dist/client/variables.css +304 -0
  24. package/dist/config/index.d.ts +54 -0
  25. package/dist/config/index.js +38 -0
  26. package/dist/config/index.js.map +1 -0
  27. package/dist/config-BmEdBDo_.d.ts +220 -0
  28. package/dist/content-BWR52vD-.d.ts +64 -0
  29. package/dist/discovery/index.d.ts +310 -0
  30. package/dist/discovery/index.js +38 -0
  31. package/dist/discovery/index.js.map +1 -0
  32. package/dist/errors-C0iYiDTv.d.ts +107 -0
  33. package/dist/filesystem/index.d.ts +1292 -0
  34. package/dist/filesystem/index.js +203 -0
  35. package/dist/filesystem/index.js.map +1 -0
  36. package/dist/image-FP7w5ZIs.d.ts +47 -0
  37. package/dist/index.d.ts +64 -0
  38. package/dist/index.js +151 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/loader-55LWCXHA.js +12 -0
  41. package/dist/loader-55LWCXHA.js.map +1 -0
  42. package/dist/loader-CrdnaAWR.d.ts +327 -0
  43. package/dist/server/index.d.ts +357 -0
  44. package/dist/server/index.js +37 -0
  45. package/dist/server/index.js.map +1 -0
  46. package/package.json +94 -0
  47. package/src/client/App.tsx +900 -0
  48. package/src/client/components/ConfigPanel/ConfigPanel.css +553 -0
  49. package/src/client/components/ConfigPanel/ConfigPanel.tsx +396 -0
  50. package/src/client/components/ConfigPanel/index.ts +6 -0
  51. package/src/client/components/CreateContentModal/CreateContentModal.css +327 -0
  52. package/src/client/components/CreateContentModal/CreateContentModal.tsx +216 -0
  53. package/src/client/components/CreateContentModal/index.ts +7 -0
  54. package/src/client/components/Editor/Editor.css +885 -0
  55. package/src/client/components/Editor/Editor.tsx +484 -0
  56. package/src/client/components/Editor/ImageDialog.css +344 -0
  57. package/src/client/components/Editor/ImageDialog.tsx +367 -0
  58. package/src/client/components/Editor/LinkDialog.css +326 -0
  59. package/src/client/components/Editor/LinkDialog.tsx +332 -0
  60. package/src/client/components/Editor/index.ts +6 -0
  61. package/src/client/components/FrontmatterForm/FrontmatterForm.css +468 -0
  62. package/src/client/components/FrontmatterForm/FrontmatterForm.tsx +914 -0
  63. package/src/client/components/FrontmatterForm/index.ts +7 -0
  64. package/src/client/components/Header/Header.css +300 -0
  65. package/src/client/components/Header/Header.tsx +300 -0
  66. package/src/client/components/Header/index.ts +7 -0
  67. package/src/client/components/KeyboardShortcuts/KeyboardShortcuts.css +239 -0
  68. package/src/client/components/KeyboardShortcuts/KeyboardShortcuts.tsx +151 -0
  69. package/src/client/components/KeyboardShortcuts/index.ts +6 -0
  70. package/src/client/components/LazyEditor.tsx +75 -0
  71. package/src/client/components/LiveRegion/LiveRegion.css +19 -0
  72. package/src/client/components/LiveRegion/LiveRegion.tsx +60 -0
  73. package/src/client/components/LiveRegion/index.ts +7 -0
  74. package/src/client/components/SearchReplace/SearchReplacePanel.css +300 -0
  75. package/src/client/components/SearchReplace/SearchReplacePanel.tsx +332 -0
  76. package/src/client/components/SearchReplace/index.ts +7 -0
  77. package/src/client/components/SelectCollectionModal/SelectCollectionModal.css +308 -0
  78. package/src/client/components/SelectCollectionModal/SelectCollectionModal.tsx +223 -0
  79. package/src/client/components/SelectCollectionModal/index.ts +7 -0
  80. package/src/client/components/Sidebar/Sidebar.css +570 -0
  81. package/src/client/components/Sidebar/Sidebar.tsx +617 -0
  82. package/src/client/components/Sidebar/index.ts +7 -0
  83. package/src/client/components/SkipLink/SkipLink.css +51 -0
  84. package/src/client/components/SkipLink/SkipLink.tsx +67 -0
  85. package/src/client/components/SkipLink/index.ts +7 -0
  86. package/src/client/components/UnsavedChangesModal/UnsavedChangesModal.css +233 -0
  87. package/src/client/components/UnsavedChangesModal/UnsavedChangesModal.tsx +160 -0
  88. package/src/client/components/UnsavedChangesModal/index.ts +1 -0
  89. package/src/client/components/VersionHistory/DiffViewer.css +430 -0
  90. package/src/client/components/VersionHistory/DiffViewer.tsx +383 -0
  91. package/src/client/components/VersionHistory/VersionActions.css +318 -0
  92. package/src/client/components/VersionHistory/VersionActions.tsx +277 -0
  93. package/src/client/components/VersionHistory/VersionHistoryPanel.css +369 -0
  94. package/src/client/components/VersionHistory/VersionHistoryPanel.tsx +469 -0
  95. package/src/client/components/VersionHistory/index.ts +9 -0
  96. package/src/client/context/ApiContext.tsx +154 -0
  97. package/src/client/context/ThemeContext.tsx +172 -0
  98. package/src/client/hooks/useAnnounce.ts +201 -0
  99. package/src/client/hooks/useApi.ts +374 -0
  100. package/src/client/hooks/useArrowNavigation.ts +286 -0
  101. package/src/client/hooks/useAutosave.ts +241 -0
  102. package/src/client/hooks/useFocusTrap.ts +178 -0
  103. package/src/client/hooks/useKeyboardShortcuts.ts +203 -0
  104. package/src/client/hooks/useSearch.ts +206 -0
  105. package/src/client/hooks/useVersionHistory.ts +451 -0
  106. package/src/client/index.tsx +70 -0
  107. package/src/client/styles.css +584 -0
  108. package/src/client/utils/focus.ts +57 -0
  109. package/src/client/utils/openInEditor.ts +130 -0
  110. package/src/client/variables.css +304 -0
  111. package/src/config/defaults.ts +109 -0
  112. package/src/config/index.ts +32 -0
  113. package/src/config/loader.ts +174 -0
  114. package/src/config/schema.ts +161 -0
  115. package/src/core/constants.ts +39 -0
  116. package/src/core/errors.ts +739 -0
  117. package/src/core/index.ts +11 -0
  118. package/src/discovery/collections.ts +216 -0
  119. package/src/discovery/index.ts +33 -0
  120. package/src/discovery/patterns.ts +702 -0
  121. package/src/discovery/schema.ts +453 -0
  122. package/src/filesystem/images.ts +798 -0
  123. package/src/filesystem/index.ts +107 -0
  124. package/src/filesystem/reader.ts +452 -0
  125. package/src/filesystem/version-config.ts +390 -0
  126. package/src/filesystem/versions.ts +1339 -0
  127. package/src/filesystem/watcher.ts +226 -0
  128. package/src/filesystem/writer.ts +540 -0
  129. package/src/index.ts +61 -0
  130. package/src/integration.ts +228 -0
  131. package/src/server/assets.ts +254 -0
  132. package/src/server/cache.ts +355 -0
  133. package/src/server/index.ts +33 -0
  134. package/src/server/middleware.ts +209 -0
  135. package/src/server/routes.ts +1428 -0
  136. package/src/types/api.ts +61 -0
  137. package/src/types/config.ts +134 -0
  138. package/src/types/content.ts +64 -0
  139. package/src/types/image.ts +48 -0
  140. package/src/types/index.ts +58 -0
  141. package/src/types/version.ts +117 -0
@@ -0,0 +1,310 @@
1
+ import {
2
+ detectFilePattern,
3
+ getCollectionCount,
4
+ readCollection
5
+ } from "./chunk-AAOQHQPU.js";
6
+ import {
7
+ DEFAULT_FILE_PATTERN
8
+ } from "./chunk-CRPZUUDU.js";
9
+
10
+ // src/discovery/schema.ts
11
+ var MAX_SAMPLE_FILES = 20;
12
+ var REQUIRED_THRESHOLD = 0.9;
13
+ var ENUM_MAX_VALUES = 10;
14
+ var ENUM_RATIO_THRESHOLD = 0.3;
15
+ var IMAGE_EXTENSIONS = [
16
+ ".jpg",
17
+ ".jpeg",
18
+ ".png",
19
+ ".gif",
20
+ ".webp",
21
+ ".avif",
22
+ ".svg"
23
+ ];
24
+ function isImagePath(value) {
25
+ if (typeof value !== "string") return false;
26
+ const lowered = value.toLowerCase();
27
+ return IMAGE_EXTENSIONS.some((ext) => lowered.endsWith(ext));
28
+ }
29
+ function isDateValue(value) {
30
+ if (value instanceof Date) return true;
31
+ if (typeof value === "string") {
32
+ if (/^\d{4}-\d{2}-\d{2}(T|\s)/.test(value)) return true;
33
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return true;
34
+ }
35
+ return false;
36
+ }
37
+ function detectValueType(value) {
38
+ if (value === null || value === void 0) return "null";
39
+ if (typeof value === "boolean") return "boolean";
40
+ if (typeof value === "number") return "number";
41
+ if (typeof value === "string") return "string";
42
+ if (Array.isArray(value)) return "array";
43
+ if (value instanceof Date) return "date";
44
+ if (typeof value === "object") return "object";
45
+ return "unknown";
46
+ }
47
+ function inferFieldType(analysis) {
48
+ if (analysis.hasImagePaths) return "image";
49
+ if (analysis.hasDateValues) return "date";
50
+ const nonNullTypes = new Set([...analysis.types].filter((t) => t !== "null"));
51
+ if (nonNullTypes.size === 1) {
52
+ const type = [...nonNullTypes][0];
53
+ switch (type) {
54
+ case "boolean":
55
+ return "boolean";
56
+ case "number":
57
+ return "number";
58
+ case "array":
59
+ return "array";
60
+ case "object":
61
+ return "object";
62
+ case "date":
63
+ return "date";
64
+ default:
65
+ return "string";
66
+ }
67
+ }
68
+ return "string";
69
+ }
70
+ function detectEnum(values, totalSamples) {
71
+ const stringValues = values.filter(
72
+ (v) => typeof v === "string" && v.length > 0
73
+ );
74
+ if (stringValues.length === 0) return void 0;
75
+ const uniqueValues = [...new Set(stringValues)];
76
+ if (uniqueValues.length > ENUM_MAX_VALUES) return void 0;
77
+ const ratio = uniqueValues.length / totalSamples;
78
+ if (ratio > ENUM_RATIO_THRESHOLD) return void 0;
79
+ if (uniqueValues.length < 2) return void 0;
80
+ if (stringValues.length < totalSamples * 0.5) return void 0;
81
+ return uniqueValues.sort();
82
+ }
83
+ function detectArrayItemType(analysis) {
84
+ if (analysis.arrayItemTypes.size === 0) return void 0;
85
+ const types = [...analysis.arrayItemTypes].filter((t) => t !== "null");
86
+ if (types.length === 0) return void 0;
87
+ if (types.length === 1) return types[0];
88
+ return "string";
89
+ }
90
+ async function detectSchema(collectionPath) {
91
+ const warnings = [];
92
+ const items = await readCollection(collectionPath, {
93
+ includeDrafts: true
94
+ });
95
+ const samples = items.slice(0, MAX_SAMPLE_FILES);
96
+ if (samples.length === 0) {
97
+ return {
98
+ schema: {},
99
+ samplesAnalyzed: 0,
100
+ confidence: 0,
101
+ warnings: ["No content files found in collection"]
102
+ };
103
+ }
104
+ const fieldAnalyses = /* @__PURE__ */ new Map();
105
+ for (const item of samples) {
106
+ for (const [fieldName, value] of Object.entries(item.frontmatter)) {
107
+ let analysis = fieldAnalyses.get(fieldName);
108
+ if (!analysis) {
109
+ analysis = {
110
+ presentCount: 0,
111
+ types: /* @__PURE__ */ new Set(),
112
+ values: [],
113
+ hasImagePaths: false,
114
+ hasDateValues: false,
115
+ arrayItemTypes: /* @__PURE__ */ new Set()
116
+ };
117
+ fieldAnalyses.set(fieldName, analysis);
118
+ }
119
+ analysis.presentCount++;
120
+ analysis.types.add(detectValueType(value));
121
+ analysis.values.push(value);
122
+ if (isImagePath(value)) {
123
+ analysis.hasImagePaths = true;
124
+ }
125
+ if (isDateValue(value)) {
126
+ analysis.hasDateValues = true;
127
+ }
128
+ if (Array.isArray(value)) {
129
+ for (const item2 of value) {
130
+ analysis.arrayItemTypes.add(detectValueType(item2));
131
+ }
132
+ }
133
+ }
134
+ }
135
+ const schema = {};
136
+ const totalSamples = samples.length;
137
+ for (const [fieldName, analysis] of fieldAnalyses) {
138
+ const fieldType = inferFieldType(analysis);
139
+ const isRequired = analysis.presentCount / totalSamples >= REQUIRED_THRESHOLD;
140
+ const field = {
141
+ type: fieldType,
142
+ required: isRequired
143
+ };
144
+ if (fieldType === "array") {
145
+ const itemType = detectArrayItemType(analysis);
146
+ if (itemType) {
147
+ field.items = itemType;
148
+ }
149
+ }
150
+ if (fieldType === "string") {
151
+ const enumValues = detectEnum(analysis.values, totalSamples);
152
+ if (enumValues) {
153
+ field.description = `Options: ${enumValues.join(", ")}`;
154
+ }
155
+ }
156
+ if (fieldType === "boolean") {
157
+ const boolValues = analysis.values.filter(
158
+ (v) => typeof v === "boolean"
159
+ );
160
+ if (boolValues.length > 0) {
161
+ const trueCount = boolValues.filter((v) => v === true).length;
162
+ const falseCount = boolValues.filter((v) => v === false).length;
163
+ field.default = trueCount > falseCount ? true : false;
164
+ }
165
+ }
166
+ const nonNullTypes = [...analysis.types].filter((t) => t !== "null");
167
+ if (nonNullTypes.length > 1) {
168
+ warnings.push(
169
+ `Field "${fieldName}" has inconsistent types: ${nonNullTypes.join(", ")}`
170
+ );
171
+ }
172
+ schema[fieldName] = field;
173
+ }
174
+ const inconsistentFields = warnings.filter(
175
+ (w) => w.includes("inconsistent")
176
+ ).length;
177
+ const confidence = Math.max(
178
+ 0,
179
+ 1 - inconsistentFields / Math.max(1, fieldAnalyses.size)
180
+ );
181
+ return {
182
+ schema,
183
+ samplesAnalyzed: totalSamples,
184
+ confidence,
185
+ warnings
186
+ };
187
+ }
188
+ function mergeSchema(detected, userSchema) {
189
+ if (!userSchema) return detected;
190
+ const merged = { ...detected };
191
+ for (const [fieldName, userField] of Object.entries(userSchema)) {
192
+ merged[fieldName] = {
193
+ ...detected[fieldName],
194
+ ...userField
195
+ };
196
+ }
197
+ return merged;
198
+ }
199
+ function describeSchema(schema) {
200
+ const lines = [];
201
+ for (const [fieldName, field] of Object.entries(schema)) {
202
+ let desc = `- ${fieldName}: ${field.type}`;
203
+ if (field.required) {
204
+ desc += " (required)";
205
+ }
206
+ if (field.items) {
207
+ desc += ` of ${field.items}`;
208
+ }
209
+ if (field.default !== void 0) {
210
+ desc += ` [default: ${JSON.stringify(field.default)}]`;
211
+ }
212
+ if (field.description) {
213
+ desc += ` - ${field.description}`;
214
+ }
215
+ lines.push(desc);
216
+ }
217
+ return lines.join("\n");
218
+ }
219
+
220
+ // src/discovery/collections.ts
221
+ import { readdir, stat } from "fs/promises";
222
+ import { existsSync } from "fs";
223
+ import { join } from "path";
224
+ var DEFAULT_CONTENT_DIR = "src/content";
225
+ var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set(["node_modules", ".git", "_", "."]);
226
+ function shouldIgnore(name) {
227
+ return IGNORED_DIRECTORIES.has(name) || name.startsWith("_") || name.startsWith(".");
228
+ }
229
+ async function discoverCollections(projectRoot, contentDir = DEFAULT_CONTENT_DIR) {
230
+ const contentPath = join(projectRoot, contentDir);
231
+ if (!existsSync(contentPath)) {
232
+ return [];
233
+ }
234
+ const collections = [];
235
+ try {
236
+ const entries = await readdir(contentPath, { withFileTypes: true });
237
+ for (const entry of entries) {
238
+ if (!entry.isDirectory() || shouldIgnore(entry.name)) {
239
+ continue;
240
+ }
241
+ const collectionPath = join(contentPath, entry.name);
242
+ const relativePath = join(contentDir, entry.name);
243
+ const count = await getCollectionCount(collectionPath);
244
+ const patternResult = await detectFilePattern(collectionPath);
245
+ const filePattern = patternResult.pattern;
246
+ const schemaResult = await detectSchema(collectionPath);
247
+ const schema = Object.keys(schemaResult.schema).length > 0 ? schemaResult.schema : void 0;
248
+ const previewUrl = `/${entry.name}/{slug}`;
249
+ collections.push({
250
+ name: entry.name,
251
+ path: relativePath,
252
+ filePattern,
253
+ count,
254
+ schema,
255
+ previewUrl
256
+ });
257
+ }
258
+ } catch (error) {
259
+ console.error(`[writenex] Failed to discover collections: ${error}`);
260
+ }
261
+ return collections;
262
+ }
263
+ function mergeCollections(discovered, configured) {
264
+ const configuredNames = new Set(configured.map((c) => c.name));
265
+ const result = [];
266
+ for (const config of configured) {
267
+ const discoveredMatch = discovered.find((d) => d.name === config.name);
268
+ result.push({
269
+ name: config.name,
270
+ path: config.path,
271
+ filePattern: config.filePattern ?? discoveredMatch?.filePattern ?? DEFAULT_FILE_PATTERN,
272
+ count: discoveredMatch?.count ?? 0,
273
+ schema: config.schema ?? discoveredMatch?.schema,
274
+ previewUrl: config.previewUrl ?? discoveredMatch?.previewUrl ?? `/${config.name}/{slug}`
275
+ });
276
+ }
277
+ for (const disc of discovered) {
278
+ if (!configuredNames.has(disc.name)) {
279
+ result.push(disc);
280
+ }
281
+ }
282
+ return result;
283
+ }
284
+ async function getCollection(projectRoot, collectionName, contentDir = DEFAULT_CONTENT_DIR) {
285
+ const collections = await discoverCollections(projectRoot, contentDir);
286
+ return collections.find((c) => c.name === collectionName);
287
+ }
288
+ async function collectionExists(projectRoot, collectionName, contentDir = DEFAULT_CONTENT_DIR) {
289
+ const collectionPath = join(projectRoot, contentDir, collectionName);
290
+ if (!existsSync(collectionPath)) {
291
+ return false;
292
+ }
293
+ try {
294
+ const stats = await stat(collectionPath);
295
+ return stats.isDirectory();
296
+ } catch {
297
+ return false;
298
+ }
299
+ }
300
+
301
+ export {
302
+ detectSchema,
303
+ mergeSchema,
304
+ describeSchema,
305
+ discoverCollections,
306
+ mergeCollections,
307
+ getCollection,
308
+ collectionExists
309
+ };
310
+ //# sourceMappingURL=chunk-CYLDJ3HZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/discovery/schema.ts","../src/discovery/collections.ts"],"sourcesContent":["/**\n * @fileoverview Schema auto-detection for content collections\n *\n * This module analyzes frontmatter from sample content files to automatically\n * infer the schema (field types, required status, enums, etc.).\n *\n * ## Detection Process:\n * 1. Read sample files from the collection (up to 20)\n * 2. Parse frontmatter from each file\n * 3. Analyze field patterns across all samples\n * 4. Infer field types and constraints\n * 5. Generate schema definition\n *\n * ## Detected Types:\n * - string: Plain text values\n * - number: Numeric values\n * - boolean: True/false values\n * - date: ISO date strings or Date objects\n * - array: Arrays (with item type detection)\n * - image: Paths ending with image extensions\n *\n * @module @writenex/astro/discovery/schema\n */\n\nimport type { CollectionSchema, FieldType, SchemaField } from \"@/types\";\nimport { readCollection } from \"@/filesystem/reader\";\n\n/**\n * Maximum number of files to sample for schema detection\n */\nconst MAX_SAMPLE_FILES = 20;\n\n/**\n * Minimum presence ratio to consider a field required\n * (field must appear in at least 90% of files)\n */\nconst REQUIRED_THRESHOLD = 0.9;\n\n/**\n * Maximum unique values to consider a field as enum\n */\nconst ENUM_MAX_VALUES = 10;\n\n/**\n * Minimum ratio of unique values to total to NOT be an enum\n * (if uniqueValues / total < 0.3, it's likely an enum)\n */\nconst ENUM_RATIO_THRESHOLD = 0.3;\n\n/**\n * Image file extensions for detection\n */\nconst IMAGE_EXTENSIONS = [\n \".jpg\",\n \".jpeg\",\n \".png\",\n \".gif\",\n \".webp\",\n \".avif\",\n \".svg\",\n];\n\n/**\n * Field analysis data collected from samples\n */\ninterface FieldAnalysis {\n /** Number of files where this field appears */\n presentCount: number;\n /** Detected types for this field across samples */\n types: Set<string>;\n /** Sample values for enum detection */\n values: unknown[];\n /** Whether values look like image paths */\n hasImagePaths: boolean;\n /** Whether values look like dates */\n hasDateValues: boolean;\n /** For arrays, analysis of item types */\n arrayItemTypes: Set<string>;\n}\n\n/**\n * Result of schema detection\n */\nexport interface SchemaDetectionResult {\n /** The detected schema */\n schema: CollectionSchema;\n /** Number of files analyzed */\n samplesAnalyzed: number;\n /** Confidence score (0-1) based on sample consistency */\n confidence: number;\n /** Fields that had inconsistent types across samples */\n warnings: string[];\n}\n\n/**\n * Check if a string looks like an image path\n *\n * @param value - Value to check\n * @returns True if it looks like an image path\n */\nfunction isImagePath(value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n\n const lowered = value.toLowerCase();\n return IMAGE_EXTENSIONS.some((ext) => lowered.endsWith(ext));\n}\n\n/**\n * Check if a value looks like a date\n *\n * @param value - Value to check\n * @returns True if it looks like a date\n */\nfunction isDateValue(value: unknown): boolean {\n // Already a Date object\n if (value instanceof Date) return true;\n\n // ISO date string (YYYY-MM-DD or full ISO)\n if (typeof value === \"string\") {\n // Full ISO format\n if (/^\\d{4}-\\d{2}-\\d{2}(T|\\s)/.test(value)) return true;\n // Simple date format\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return true;\n }\n\n return false;\n}\n\n/**\n * Detect the JavaScript type of a value\n *\n * @param value - Value to analyze\n * @returns Detected type string\n */\nfunction detectValueType(value: unknown): string {\n if (value === null || value === undefined) return \"null\";\n if (typeof value === \"boolean\") return \"boolean\";\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"string\") return \"string\";\n if (Array.isArray(value)) return \"array\";\n if (value instanceof Date) return \"date\";\n if (typeof value === \"object\") return \"object\";\n return \"unknown\";\n}\n\n/**\n * Convert detected type to schema field type\n *\n * @param analysis - Field analysis data\n * @returns The appropriate FieldType\n */\nfunction inferFieldType(analysis: FieldAnalysis): FieldType {\n // If it has image paths, it's an image field\n if (analysis.hasImagePaths) return \"image\";\n\n // If it has date values, it's a date field\n if (analysis.hasDateValues) return \"date\";\n\n // Check detected types (excluding null)\n const nonNullTypes = new Set([...analysis.types].filter((t) => t !== \"null\"));\n\n // Single type is easy\n if (nonNullTypes.size === 1) {\n const type = [...nonNullTypes][0];\n switch (type) {\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"array\":\n return \"array\";\n case \"object\":\n return \"object\";\n case \"date\":\n return \"date\";\n default:\n return \"string\";\n }\n }\n\n // Mixed types - default to string (most flexible)\n return \"string\";\n}\n\n/**\n * Detect if a field should be treated as an enum\n *\n * @param values - All values seen for this field\n * @param totalSamples - Total number of samples\n * @returns Array of enum values, or undefined if not an enum\n */\nfunction detectEnum(\n values: unknown[],\n totalSamples: number\n): string[] | undefined {\n // Filter to string values only\n const stringValues = values.filter(\n (v): v is string => typeof v === \"string\" && v.length > 0\n );\n\n if (stringValues.length === 0) return undefined;\n\n // Get unique values\n const uniqueValues = [...new Set(stringValues)];\n\n // Check if it's a good candidate for enum\n if (uniqueValues.length > ENUM_MAX_VALUES) return undefined;\n\n // Check ratio of unique to total\n const ratio = uniqueValues.length / totalSamples;\n if (ratio > ENUM_RATIO_THRESHOLD) return undefined;\n\n // Must have at least 2 unique values and appear multiple times\n if (uniqueValues.length < 2) return undefined;\n if (stringValues.length < totalSamples * 0.5) return undefined;\n\n return uniqueValues.sort();\n}\n\n/**\n * Detect item type for array fields\n *\n * @param analysis - Field analysis data\n * @returns The detected item type, or undefined\n */\nfunction detectArrayItemType(analysis: FieldAnalysis): string | undefined {\n if (analysis.arrayItemTypes.size === 0) return undefined;\n\n // Filter out null\n const types = [...analysis.arrayItemTypes].filter((t) => t !== \"null\");\n\n if (types.length === 0) return undefined;\n if (types.length === 1) return types[0];\n\n // Mixed types - default to string\n return \"string\";\n}\n\n/**\n * Analyze frontmatter from content items to detect schema\n *\n * @param collectionPath - Absolute path to the collection directory\n * @returns Schema detection result\n *\n * @example\n * ```typescript\n * const result = await detectSchema('/project/src/content/blog');\n * console.log(result.schema);\n * // {\n * // title: { type: 'string', required: true },\n * // pubDate: { type: 'date', required: true },\n * // draft: { type: 'boolean', required: false, default: false },\n * // tags: { type: 'array', required: false, items: 'string' },\n * // }\n * ```\n */\nexport async function detectSchema(\n collectionPath: string\n): Promise<SchemaDetectionResult> {\n const warnings: string[] = [];\n\n // Read sample content files\n const items = await readCollection(collectionPath, {\n includeDrafts: true,\n });\n\n // Limit to max samples\n const samples = items.slice(0, MAX_SAMPLE_FILES);\n\n if (samples.length === 0) {\n return {\n schema: {},\n samplesAnalyzed: 0,\n confidence: 0,\n warnings: [\"No content files found in collection\"],\n };\n }\n\n // Analyze each field across all samples\n const fieldAnalyses = new Map<string, FieldAnalysis>();\n\n for (const item of samples) {\n for (const [fieldName, value] of Object.entries(item.frontmatter)) {\n // Get or create field analysis\n let analysis = fieldAnalyses.get(fieldName);\n if (!analysis) {\n analysis = {\n presentCount: 0,\n types: new Set(),\n values: [],\n hasImagePaths: false,\n hasDateValues: false,\n arrayItemTypes: new Set(),\n };\n fieldAnalyses.set(fieldName, analysis);\n }\n\n // Update analysis\n analysis.presentCount++;\n analysis.types.add(detectValueType(value));\n analysis.values.push(value);\n\n // Check for special types\n if (isImagePath(value)) {\n analysis.hasImagePaths = true;\n }\n if (isDateValue(value)) {\n analysis.hasDateValues = true;\n }\n\n // Analyze array items\n if (Array.isArray(value)) {\n for (const item of value) {\n analysis.arrayItemTypes.add(detectValueType(item));\n }\n }\n }\n }\n\n // Generate schema from analysis\n const schema: CollectionSchema = {};\n const totalSamples = samples.length;\n\n for (const [fieldName, analysis] of fieldAnalyses) {\n const fieldType = inferFieldType(analysis);\n const isRequired =\n analysis.presentCount / totalSamples >= REQUIRED_THRESHOLD;\n\n const field: SchemaField = {\n type: fieldType,\n required: isRequired,\n };\n\n // Add array item type if applicable\n if (fieldType === \"array\") {\n const itemType = detectArrayItemType(analysis);\n if (itemType) {\n field.items = itemType;\n }\n }\n\n // Detect enum for string fields\n if (fieldType === \"string\") {\n const enumValues = detectEnum(analysis.values, totalSamples);\n if (enumValues) {\n // Store enum values in the field\n // Note: We use 'default' to store enum options since SchemaField\n // doesn't have an 'enum' property - this can be enhanced later\n field.description = `Options: ${enumValues.join(\", \")}`;\n }\n }\n\n // Detect default value for boolean fields\n if (fieldType === \"boolean\") {\n const boolValues = analysis.values.filter(\n (v): v is boolean => typeof v === \"boolean\"\n );\n if (boolValues.length > 0) {\n // Use most common value as default\n const trueCount = boolValues.filter((v) => v === true).length;\n const falseCount = boolValues.filter((v) => v === false).length;\n field.default = trueCount > falseCount ? true : false;\n }\n }\n\n // Check for type inconsistencies\n const nonNullTypes = [...analysis.types].filter((t) => t !== \"null\");\n if (nonNullTypes.length > 1) {\n warnings.push(\n `Field \"${fieldName}\" has inconsistent types: ${nonNullTypes.join(\", \")}`\n );\n }\n\n schema[fieldName] = field;\n }\n\n // Calculate confidence based on consistency\n const inconsistentFields = warnings.filter((w) =>\n w.includes(\"inconsistent\")\n ).length;\n const confidence = Math.max(\n 0,\n 1 - inconsistentFields / Math.max(1, fieldAnalyses.size)\n );\n\n return {\n schema,\n samplesAnalyzed: totalSamples,\n confidence,\n warnings,\n };\n}\n\n/**\n * Merge detected schema with user-provided schema\n *\n * User schema takes precedence over detected schema.\n *\n * @param detected - Auto-detected schema\n * @param userSchema - User-provided schema overrides\n * @returns Merged schema\n */\nexport function mergeSchema(\n detected: CollectionSchema,\n userSchema?: CollectionSchema\n): CollectionSchema {\n if (!userSchema) return detected;\n\n const merged: CollectionSchema = { ...detected };\n\n for (const [fieldName, userField] of Object.entries(userSchema)) {\n merged[fieldName] = {\n ...detected[fieldName],\n ...userField,\n };\n }\n\n return merged;\n}\n\n/**\n * Convert schema to a human-readable description\n *\n * @param schema - The schema to describe\n * @returns Human-readable description\n */\nexport function describeSchema(schema: CollectionSchema): string {\n const lines: string[] = [];\n\n for (const [fieldName, field] of Object.entries(schema)) {\n let desc = `- ${fieldName}: ${field.type}`;\n\n if (field.required) {\n desc += \" (required)\";\n }\n\n if (field.items) {\n desc += ` of ${field.items}`;\n }\n\n if (field.default !== undefined) {\n desc += ` [default: ${JSON.stringify(field.default)}]`;\n }\n\n if (field.description) {\n desc += ` - ${field.description}`;\n }\n\n lines.push(desc);\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * @fileoverview Collection discovery for Astro content collections\n *\n * This module provides functions to auto-discover content collections\n * from an Astro project's src/content directory.\n *\n * ## Discovery Process:\n * 1. Scan src/content/ for subdirectories\n * 2. Each subdirectory is treated as a collection\n * 3. Count content files in each collection\n * 4. Detect file patterns from existing files\n * 5. Auto-detect frontmatter schema from sample files\n *\n * @module @writenex/astro/discovery/collections\n */\n\nimport { readdir, stat } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { DiscoveredCollection, CollectionConfig } from \"@/types\";\nimport { getCollectionCount } from \"@/filesystem/reader\";\nimport { DEFAULT_FILE_PATTERN } from \"@/config/defaults\";\nimport { detectFilePattern as detectPattern } from \"./patterns\";\nimport { detectSchema } from \"./schema\";\n\n/**\n * Default content directory path relative to project root\n */\nconst DEFAULT_CONTENT_DIR = \"src/content\";\n\n/**\n * Directories to ignore during discovery\n */\nconst IGNORED_DIRECTORIES = new Set([\"node_modules\", \".git\", \"_\", \".\"]);\n\n/**\n * Check if a directory should be ignored\n *\n * @param name - Directory name\n * @returns True if should be ignored\n */\nfunction shouldIgnore(name: string): boolean {\n return (\n IGNORED_DIRECTORIES.has(name) ||\n name.startsWith(\"_\") ||\n name.startsWith(\".\")\n );\n}\n\n/**\n * Discover all content collections in a project\n *\n * Scans the src/content directory for subdirectories and treats\n * each as a content collection.\n *\n * @param projectRoot - Absolute path to the project root\n * @param contentDir - Relative path to content directory (default: src/content)\n * @returns Array of discovered collections\n *\n * @example\n * ```typescript\n * const collections = await discoverCollections('/path/to/project');\n * // Returns: [\n * // { name: 'blog', path: 'src/content/blog', count: 10, ... },\n * // { name: 'docs', path: 'src/content/docs', count: 5, ... },\n * // ]\n * ```\n */\nexport async function discoverCollections(\n projectRoot: string,\n contentDir: string = DEFAULT_CONTENT_DIR\n): Promise<DiscoveredCollection[]> {\n const contentPath = join(projectRoot, contentDir);\n\n // Check if content directory exists\n if (!existsSync(contentPath)) {\n return [];\n }\n\n const collections: DiscoveredCollection[] = [];\n\n try {\n const entries = await readdir(contentPath, { withFileTypes: true });\n\n for (const entry of entries) {\n // Skip non-directories and ignored directories\n if (!entry.isDirectory() || shouldIgnore(entry.name)) {\n continue;\n }\n\n const collectionPath = join(contentPath, entry.name);\n const relativePath = join(contentDir, entry.name);\n\n // Count content files in this collection\n const count = await getCollectionCount(collectionPath);\n\n // Detect file pattern using pattern detection module\n const patternResult = await detectPattern(collectionPath);\n const filePattern = patternResult.pattern;\n\n // Auto-detect schema from sample files\n const schemaResult = await detectSchema(collectionPath);\n const schema =\n Object.keys(schemaResult.schema).length > 0\n ? schemaResult.schema\n : undefined;\n\n // Generate default preview URL pattern\n const previewUrl = `/${entry.name}/{slug}`;\n\n collections.push({\n name: entry.name,\n path: relativePath,\n filePattern,\n count,\n schema,\n previewUrl,\n });\n }\n } catch (error) {\n console.error(`[writenex] Failed to discover collections: ${error}`);\n }\n\n return collections;\n}\n\n/**\n * Merge discovered collections with configured collections\n *\n * Configured collections take precedence over discovered ones.\n * This allows users to override auto-discovered settings.\n *\n * @param discovered - Auto-discovered collections\n * @param configured - User-configured collections\n * @returns Merged collection list\n */\nexport function mergeCollections(\n discovered: DiscoveredCollection[],\n configured: CollectionConfig[]\n): DiscoveredCollection[] {\n const configuredNames = new Set(configured.map((c) => c.name));\n const result: DiscoveredCollection[] = [];\n\n // Add configured collections first (they take precedence)\n for (const config of configured) {\n const discoveredMatch = discovered.find((d) => d.name === config.name);\n\n result.push({\n name: config.name,\n path: config.path,\n filePattern:\n config.filePattern ??\n discoveredMatch?.filePattern ??\n DEFAULT_FILE_PATTERN,\n count: discoveredMatch?.count ?? 0,\n schema: config.schema ?? discoveredMatch?.schema,\n previewUrl:\n config.previewUrl ??\n discoveredMatch?.previewUrl ??\n `/${config.name}/{slug}`,\n });\n }\n\n // Add discovered collections that weren't configured\n for (const disc of discovered) {\n if (!configuredNames.has(disc.name)) {\n result.push(disc);\n }\n }\n\n return result;\n}\n\n/**\n * Get a single collection by name\n *\n * @param projectRoot - Absolute path to the project root\n * @param collectionName - Name of the collection\n * @param contentDir - Relative path to content directory\n * @returns The collection if found, undefined otherwise\n */\nexport async function getCollection(\n projectRoot: string,\n collectionName: string,\n contentDir: string = DEFAULT_CONTENT_DIR\n): Promise<DiscoveredCollection | undefined> {\n const collections = await discoverCollections(projectRoot, contentDir);\n return collections.find((c) => c.name === collectionName);\n}\n\n/**\n * Check if a collection exists\n *\n * @param projectRoot - Absolute path to the project root\n * @param collectionName - Name of the collection\n * @param contentDir - Relative path to content directory\n * @returns True if the collection exists\n */\nexport async function collectionExists(\n projectRoot: string,\n collectionName: string,\n contentDir: string = DEFAULT_CONTENT_DIR\n): Promise<boolean> {\n const collectionPath = join(projectRoot, contentDir, collectionName);\n\n if (!existsSync(collectionPath)) {\n return false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,YAAY,cAAc;AAEnE,MAAI,CAAC,WAAW,cAAc,GAAG;AAC/B,WAAO;AAAA,EACT;AAEA,MAAI;AACF,UAAM,QAAQ,MAAM,KAAK,cAAc;AACvC,WAAO,MAAM,YAAY;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["item"]}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-KIKIPIFA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,145 @@
1
+ // src/filesystem/watcher.ts
2
+ import { watch } from "chokidar";
3
+ import { stat } from "fs/promises";
4
+ import { join } from "path";
5
+ var ContentWatcher = class {
6
+ watcher = null;
7
+ projectRoot;
8
+ contentDir;
9
+ options;
10
+ debounceTimers = /* @__PURE__ */ new Map();
11
+ constructor(projectRoot, contentDir = "src/content", options = {}) {
12
+ this.projectRoot = projectRoot;
13
+ this.contentDir = contentDir;
14
+ this.options = {
15
+ debounceMs: 100,
16
+ ignored: ["**/node_modules/**", "**/.git/**"],
17
+ ...options
18
+ };
19
+ }
20
+ /**
21
+ * Start watching for file changes
22
+ */
23
+ start() {
24
+ if (this.watcher) {
25
+ return;
26
+ }
27
+ const watchPath = join(this.projectRoot, this.contentDir);
28
+ this.watcher = watch(watchPath, {
29
+ ignored: this.options.ignored,
30
+ persistent: true,
31
+ ignoreInitial: true,
32
+ awaitWriteFinish: {
33
+ stabilityThreshold: 100,
34
+ pollInterval: 50
35
+ }
36
+ });
37
+ this.watcher.on("add", (path) => this.handleChange("add", path)).on("change", (path) => this.handleChange("change", path)).on("unlink", (path) => this.handleChange("unlink", path)).on("error", (error) => {
38
+ console.error("[writenex] Watcher error:", error);
39
+ });
40
+ }
41
+ /**
42
+ * Stop watching for file changes
43
+ */
44
+ async stop() {
45
+ if (this.watcher) {
46
+ await this.watcher.close();
47
+ this.watcher = null;
48
+ }
49
+ for (const timer of this.debounceTimers.values()) {
50
+ clearTimeout(timer);
51
+ }
52
+ this.debounceTimers.clear();
53
+ }
54
+ /**
55
+ * Handle a file change event
56
+ */
57
+ handleChange(type, filePath) {
58
+ if (!filePath.endsWith(".md") && !filePath.endsWith(".mdx")) {
59
+ return;
60
+ }
61
+ const existingTimer = this.debounceTimers.get(filePath);
62
+ if (existingTimer) {
63
+ clearTimeout(existingTimer);
64
+ }
65
+ const timer = setTimeout(() => {
66
+ this.debounceTimers.delete(filePath);
67
+ this.emitChange(type, filePath);
68
+ }, this.options.debounceMs);
69
+ this.debounceTimers.set(filePath, timer);
70
+ }
71
+ /**
72
+ * Emit a file change event
73
+ */
74
+ emitChange(type, filePath) {
75
+ if (!this.options.onChange) {
76
+ return;
77
+ }
78
+ const contentPath = join(this.projectRoot, this.contentDir);
79
+ const relativePath = filePath.replace(contentPath, "").replace(/^[/\\]/, "");
80
+ const parts = relativePath.split(/[/\\]/);
81
+ const collection = parts[0] ?? "";
82
+ this.options.onChange({
83
+ type,
84
+ path: filePath,
85
+ collection
86
+ });
87
+ }
88
+ /**
89
+ * Check if the watcher is running
90
+ */
91
+ isWatching() {
92
+ return this.watcher !== null;
93
+ }
94
+ };
95
+ var FileModificationTracker = class {
96
+ mtimes = /* @__PURE__ */ new Map();
97
+ /**
98
+ * Record the current modification time of a file
99
+ */
100
+ async track(filePath) {
101
+ try {
102
+ const stats = await stat(filePath);
103
+ this.mtimes.set(filePath, stats.mtimeMs);
104
+ } catch {
105
+ this.mtimes.delete(filePath);
106
+ }
107
+ }
108
+ /**
109
+ * Check if a file has been modified externally
110
+ */
111
+ async hasExternalChanges(filePath) {
112
+ const lastKnown = this.mtimes.get(filePath);
113
+ if (lastKnown === void 0) {
114
+ return false;
115
+ }
116
+ try {
117
+ const stats = await stat(filePath);
118
+ return stats.mtimeMs > lastKnown;
119
+ } catch {
120
+ return true;
121
+ }
122
+ }
123
+ /**
124
+ * Clear tracking for a file
125
+ */
126
+ untrack(filePath) {
127
+ this.mtimes.delete(filePath);
128
+ }
129
+ /**
130
+ * Clear all tracking
131
+ */
132
+ clear() {
133
+ this.mtimes.clear();
134
+ }
135
+ };
136
+ function createContentWatcher(projectRoot, options) {
137
+ return new ContentWatcher(projectRoot, "src/content", options);
138
+ }
139
+
140
+ export {
141
+ ContentWatcher,
142
+ FileModificationTracker,
143
+ createContentWatcher
144
+ };
145
+ //# sourceMappingURL=chunk-XNTQTTJU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/filesystem/watcher.ts"],"sourcesContent":["/**\n * @fileoverview File watcher for detecting external changes\n *\n * This module provides file watching capabilities to detect when\n * content files are modified outside of the Writenex editor\n * (e.g., in VS Code or another editor).\n *\n * @module @writenex/astro/filesystem/watcher\n */\n\nimport { watch, type FSWatcher } from \"chokidar\";\nimport { stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/**\n * File change event types\n */\nexport type FileChangeType = \"add\" | \"change\" | \"unlink\";\n\n/**\n * File change event\n */\nexport interface FileChangeEvent {\n type: FileChangeType;\n path: string;\n collection: string;\n}\n\n/**\n * Watcher options\n */\nexport interface WatcherOptions {\n /** Callback when a file changes */\n onChange?: (event: FileChangeEvent) => void;\n /** Debounce delay in milliseconds */\n debounceMs?: number;\n /** Patterns to ignore */\n ignored?: string[];\n}\n\n/**\n * Content file watcher\n *\n * Watches the src/content directory for changes and emits events\n * when files are added, modified, or deleted.\n */\nexport class ContentWatcher {\n private watcher: FSWatcher | null = null;\n private projectRoot: string;\n private contentDir: string;\n private options: WatcherOptions;\n private debounceTimers: Map<string, NodeJS.Timeout> = new Map();\n\n constructor(\n projectRoot: string,\n contentDir: string = \"src/content\",\n options: WatcherOptions = {}\n ) {\n this.projectRoot = projectRoot;\n this.contentDir = contentDir;\n this.options = {\n debounceMs: 100,\n ignored: [\"**/node_modules/**\", \"**/.git/**\"],\n ...options,\n };\n }\n\n /**\n * Start watching for file changes\n */\n start(): void {\n if (this.watcher) {\n return; // Already watching\n }\n\n const watchPath = join(this.projectRoot, this.contentDir);\n\n this.watcher = watch(watchPath, {\n ignored: this.options.ignored,\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 100,\n pollInterval: 50,\n },\n });\n\n this.watcher\n .on(\"add\", (path) => this.handleChange(\"add\", path))\n .on(\"change\", (path) => this.handleChange(\"change\", path))\n .on(\"unlink\", (path) => this.handleChange(\"unlink\", path))\n .on(\"error\", (error) => {\n console.error(\"[writenex] Watcher error:\", error);\n });\n }\n\n /**\n * Stop watching for file changes\n */\n async stop(): Promise<void> {\n if (this.watcher) {\n await this.watcher.close();\n this.watcher = null;\n }\n\n // Clear all debounce timers\n for (const timer of this.debounceTimers.values()) {\n clearTimeout(timer);\n }\n this.debounceTimers.clear();\n }\n\n /**\n * Handle a file change event\n */\n private handleChange(type: FileChangeType, filePath: string): void {\n // Only handle markdown files\n if (!filePath.endsWith(\".md\") && !filePath.endsWith(\".mdx\")) {\n return;\n }\n\n // Debounce rapid changes\n const existingTimer = this.debounceTimers.get(filePath);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n const timer = setTimeout(() => {\n this.debounceTimers.delete(filePath);\n this.emitChange(type, filePath);\n }, this.options.debounceMs);\n\n this.debounceTimers.set(filePath, timer);\n }\n\n /**\n * Emit a file change event\n */\n private emitChange(type: FileChangeType, filePath: string): void {\n if (!this.options.onChange) {\n return;\n }\n\n // Extract collection name from path\n const contentPath = join(this.projectRoot, this.contentDir);\n const relativePath = filePath\n .replace(contentPath, \"\")\n .replace(/^[/\\\\]/, \"\");\n const parts = relativePath.split(/[/\\\\]/);\n const collection = parts[0] ?? \"\";\n\n this.options.onChange({\n type,\n path: filePath,\n collection,\n });\n }\n\n /**\n * Check if the watcher is running\n */\n isWatching(): boolean {\n return this.watcher !== null;\n }\n}\n\n/**\n * Track file modification times for conflict detection\n */\nexport class FileModificationTracker {\n private mtimes: Map<string, number> = new Map();\n\n /**\n * Record the current modification time of a file\n */\n async track(filePath: string): Promise<void> {\n try {\n const stats = await stat(filePath);\n this.mtimes.set(filePath, stats.mtimeMs);\n } catch {\n // File might not exist yet\n this.mtimes.delete(filePath);\n }\n }\n\n /**\n * Check if a file has been modified externally\n */\n async hasExternalChanges(filePath: string): Promise<boolean> {\n const lastKnown = this.mtimes.get(filePath);\n if (lastKnown === undefined) {\n return false; // Not tracked, assume no changes\n }\n\n try {\n const stats = await stat(filePath);\n return stats.mtimeMs > lastKnown;\n } catch {\n return true; // File might have been deleted\n }\n }\n\n /**\n * Clear tracking for a file\n */\n untrack(filePath: string): void {\n this.mtimes.delete(filePath);\n }\n\n /**\n * Clear all tracking\n */\n clear(): void {\n this.mtimes.clear();\n }\n}\n\n/**\n * Create a content watcher instance\n */\nexport function createContentWatcher(\n projectRoot: string,\n options?: WatcherOptions\n): ContentWatcher {\n return new ContentWatcher(projectRoot, \"src/content\", options);\n}\n"],"mappings":";AAUA,SAAS,aAA6B;AACtC,SAAS,YAAY;AACrB,SAAS,YAAY;AAkCd,IAAM,iBAAN,MAAqB;AAAA,EAClB,UAA4B;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA,iBAA8C,oBAAI,IAAI;AAAA,EAE9D,YACE,aACA,aAAqB,eACrB,UAA0B,CAAC,GAC3B;AACA,SAAK,cAAc;AACnB,SAAK,aAAa;AAClB,SAAK,UAAU;AAAA,MACb,YAAY;AAAA,MACZ,SAAS,CAAC,sBAAsB,YAAY;AAAA,MAC5C,GAAG;AAAA,IACL;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,QAAI,KAAK,SAAS;AAChB;AAAA,IACF;AAEA,UAAM,YAAY,KAAK,KAAK,aAAa,KAAK,UAAU;AAExD,SAAK,UAAU,MAAM,WAAW;AAAA,MAC9B,SAAS,KAAK,QAAQ;AAAA,MACtB,YAAY;AAAA,MACZ,eAAe;AAAA,MACf,kBAAkB;AAAA,QAChB,oBAAoB;AAAA,QACpB,cAAc;AAAA,MAChB;AAAA,IACF,CAAC;AAED,SAAK,QACF,GAAG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