mnfst-types 0.1.12 → 0.1.14

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.
package/README.md CHANGED
@@ -20,7 +20,7 @@ This writes `manifest.d.ts` in the current directory. Re-run it whenever you add
20
20
  --init Also write a baseline jsconfig.json (only if missing)
21
21
  --ci Also write .github/workflows/types.yml (only if missing)
22
22
  --check Exit 1 if the output is out of date; write nothing
23
- --tsc Type-check app/ and shared/ (paths from the import map)
23
+ --tsc Type-check the scripts the page loads (paths from the import map)
24
24
  -h, --help Show usage
25
25
  ```
26
26
 
@@ -30,9 +30,10 @@ This writes `manifest.d.ts` in the current directory. Re-run it whenever you add
30
30
  npx mnfst-types --tsc
31
31
  ```
32
32
 
33
- Type-checks `app/` and `shared/` with TypeScript. The config is built on every
34
- run: paths come from the page's import map, so adding an alias like `@shared/`
35
- never needs a config change. A project `jsconfig.json` or `tsconfig.json` is
33
+ Type-checks the scripts `index.html` and the manifest's component files load
34
+ (and everything they import), plus the project's `.d.ts` files. The config is
35
+ built on every run: paths come from the page's import map, so adding an alias
36
+ never needs a config change. No folder layout is assumed. A project `jsconfig.json` or `tsconfig.json` is
36
37
  extended — its own options and paths win.
37
38
 
38
39
  `--init` writes a `jsconfig.json` so editors show the same errors as you type;
@@ -44,7 +45,7 @@ https://manifestx.dev/docs/framework/getting-started/type-checks.
44
45
 
45
46
  1. Reads `manifest.json` and walks each entry under `data`.
46
47
  2. For local CSV / JSON / YAML sources, samples the first ~50 rows to infer field types.
47
- 3. For Appwrite-table sources, types rows from the column names in the project's shared contract (manifest.json `contract`); `ManifestRows` overrides them with precise types.
48
+ 3. For Appwrite-table sources, rows accept any field until the project declares their type in `ManifestRows`.
48
49
  4. For Appwrite-bucket sources, types the source as `ManifestBucketSource`.
49
50
  5. Combines the inferred row types with the static ambient declarations and writes a single `manifest.d.ts`.
50
51
 
@@ -8,11 +8,11 @@
8
8
  // Re-running the CLI overwrites the augmentation block (between the
9
9
  // AUGMENTATION:start / AUGMENTATION:end markers in the template).
10
10
 
11
- import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync, mkdtempSync, rmSync, realpathSync } from 'node:fs';
11
+ import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync, mkdtempSync, rmSync, realpathSync, readdirSync } from 'node:fs';
12
12
  import { tmpdir } from 'node:os';
13
13
  import { spawnSync } from 'node:child_process';
14
14
  import { dirname, join, resolve, isAbsolute, relative } from 'node:path';
15
- import { fileURLToPath, pathToFileURL } from 'node:url';
15
+ import { fileURLToPath } from 'node:url';
16
16
  import { createRequire } from 'node:module';
17
17
 
18
18
  const require = createRequire(import.meta.url);
@@ -57,6 +57,7 @@ export async function main(argv) {
57
57
  console.log(`mnfst-types: ${opts.out} is up to date`);
58
58
  }
59
59
  } else if (!opts.tsc) {
60
+ mkdirSync(dirname(outPath), { recursive: true });
60
61
  writeFileSync(outPath, output);
61
62
  console.log(`mnfst-types: wrote ${outPath}`);
62
63
  }
@@ -70,7 +71,7 @@ export async function main(argv) {
70
71
  writeOnce(join(projectRoot, '.github', 'workflows', 'types.yml'), defaultWorkflow(typesPath));
71
72
  }
72
73
  if (opts.tsc) {
73
- const status = runTsc(projectRoot, typesPath);
74
+ const status = runTsc(projectRoot, typesPath, manifest);
74
75
  if (status) process.exitCode = process.exitCode || status;
75
76
  }
76
77
  }
@@ -125,13 +126,14 @@ Options:
125
126
  --init Also write a baseline jsconfig.json (only if missing)
126
127
  --ci Also write .github/workflows/types.yml (only if missing)
127
128
  --check Exit 1 if the output file is out of date; write nothing
128
- --tsc Type-check app/ and shared/ with tsc; paths come from the
129
- import map on every run (extends your jsconfig/tsconfig if any)
129
+ --tsc Type-check the scripts the page loads (and what they import)
130
+ plus the project's .d.ts files; import-map paths are read on
131
+ every run; extends your jsconfig/tsconfig if any
130
132
  -h, --help Show this message
131
133
  `);
132
134
  }
133
135
 
134
- // index.html's import map as jsconfig paths: "@app/": "/app/" → "@app/*": ["./app/*"]
136
+ // index.html's import map as jsconfig paths: "@x/": "/x/" → "@x/*": ["./x/*"]
135
137
  function importMapPaths(projectRoot) {
136
138
  const paths = {};
137
139
  let html = '';
@@ -160,7 +162,84 @@ const COMPILER_DEFAULTS = {
160
162
  skipLibCheck: true,
161
163
  lib: ['es2022', 'dom', 'dom.iterable']
162
164
  };
163
- const DEFAULT_INCLUDE = (types) => ['app/**/*', 'shared/**/*', types, '*.d.ts'];
165
+ const SCRIPT_TAG = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
166
+ const SRC_ATTR = /(?:^|\s)src\s*=\s*["']([^"']+)["']/i;
167
+ const MODULE_TYPE = /(?:^|\s)type\s*=\s*["']?module["']?/i;
168
+
169
+ const inside = (root, file) => { const r = relative(root, file); return !!r && !r.startsWith('..') && !isAbsolute(r); };
170
+
171
+ // The page and manifest.json's component files (their markup lands in the page)
172
+ function pageSources(projectRoot, manifest) {
173
+ const pages = ['index.html', ...stringList(manifest.preloadedComponents), ...stringList(manifest.components)];
174
+ const out = [];
175
+ for (const page of pages) {
176
+ try { out.push({ page, html: readFileSync(resolve(projectRoot, page.replace(/^\/+/, '')), 'utf8').replace(/<!--[\s\S]*?-->/g, '') }); } catch { /* missing */ }
177
+ }
178
+ return out;
179
+ }
180
+
181
+ // A src as the browser resolves it: against the page document at the project root
182
+ function localScript(projectRoot, src) {
183
+ const clean = src.split(/[?#]/)[0];
184
+ if (!clean || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(clean) || !/\.m?js$/i.test(clean) || /\.min\.m?js$/i.test(clean)) return null;
185
+ let pathname;
186
+ try { pathname = decodeURIComponent(new URL(clean, 'http://page/').pathname); } catch { return null; }
187
+ const file = resolve(projectRoot, pathname.replace(/^\/+/, ''));
188
+ return inside(projectRoot, file) && existsSync(file) ? file : null;
189
+ }
190
+
191
+ // Local scripts the page loads (tsc follows their imports), and inline module bodies
192
+ function scriptEntries(projectRoot, manifest) {
193
+ const files = new Set();
194
+ const inline = [];
195
+ for (const { page, html } of pageSources(projectRoot, manifest)) {
196
+ for (const [, attrs, body] of html.matchAll(SCRIPT_TAG)) {
197
+ const src = attrs.match(SRC_ATTR);
198
+ if (src) {
199
+ const file = localScript(projectRoot, src[1]);
200
+ if (file) files.add(file);
201
+ } else if (MODULE_TYPE.test(attrs) && body.trim()) {
202
+ inline.push({ page, body });
203
+ }
204
+ }
205
+ }
206
+ return { files: [...files], inline };
207
+ }
208
+
209
+ // Inline module copies for tsc: relative and root specifiers point at the files the page would load
210
+ function writeInlineModules(dir, projectRoot, inline) {
211
+ return inline.map(({ page, body }, i) => {
212
+ const fixed = body.replace(/(\bfrom\s*|\bimport\s*\(?\s*)(["'])(\.{1,2}\/|\/)([^"']*)\2/g,
213
+ (m, lead, q, start, rest) => lead + q + resolve(projectRoot, (start === '/' ? '' : start) + rest).split('\\').join('/') + q);
214
+ const file = join(dir, `inline-${i + 1}-${page.replace(/[^a-z0-9]+/gi, '-')}.mjs`);
215
+ writeFileSync(file, fixed);
216
+ return file;
217
+ });
218
+ }
219
+
220
+ // Every .d.ts in the project except dependencies, dot-folders and render output
221
+ function declarationFiles(projectRoot, manifest) {
222
+ const pre = manifest.render || manifest.prerender || {};
223
+ const output = resolve(projectRoot, typeof pre.output === 'string' ? pre.output : 'website');
224
+ const out = [];
225
+ const walk = (dir, depth) => {
226
+ if (depth > 8) return;
227
+ let entries;
228
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
229
+ for (const e of entries) {
230
+ if (e.name.startsWith('.') || e.name === 'node_modules') continue;
231
+ const full = join(dir, e.name);
232
+ if (e.isDirectory()) { if (full !== output) walk(full, depth + 1); }
233
+ else if (e.name.endsWith('.d.ts')) out.push(full);
234
+ }
235
+ };
236
+ walk(projectRoot, 0);
237
+ return out;
238
+ }
239
+
240
+ function stringList(v) {
241
+ return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [];
242
+ }
164
243
 
165
244
  // JSON with comments and trailing commas, as tsconfig allows; null when unreadable
166
245
  function readJsonc(path) {
@@ -243,10 +322,19 @@ function findTsc(projectRoot) {
243
322
 
244
323
  // Type-check with a config built now: import-map paths can't drift. A project
245
324
  // jsconfig/tsconfig is extended, and its own paths win over the import map.
246
- function runTsc(projectRoot, types) {
325
+ function runTsc(projectRoot, types, manifest = {}) {
247
326
  const abs = (p) => resolve(projectRoot, p);
248
327
  const own = ['tsconfig.json', 'jsconfig.json'].map((f) => join(projectRoot, f)).find((f) => existsSync(f));
249
328
  const config = { compilerOptions: {} };
329
+ const entries = scriptEntries(projectRoot, manifest);
330
+ const typesFile = abs(types);
331
+ const dir = mkdtempSync(join(tmpdir(), 'mnfst-tsc-'));
332
+ const inputs = [...new Set([
333
+ ...entries.files,
334
+ ...writeInlineModules(dir, projectRoot, entries.inline),
335
+ ...declarationFiles(projectRoot, manifest),
336
+ ...(existsSync(typesFile) ? [typesFile] : [])
337
+ ])];
250
338
  let paths = { mnfst: [abs(types)] };
251
339
  for (const [k, v] of Object.entries(importMapPaths(projectRoot))) paths[k] = v.map(abs);
252
340
  if (own) {
@@ -254,15 +342,18 @@ function runTsc(projectRoot, types) {
254
342
  const chain = configChain(own);
255
343
  if (!chain[0].config) console.warn(`mnfst-types: couldn't read ${own}; extending it with import-map paths only`);
256
344
  paths = { ...paths, ...chainPaths(chain) };
257
- if (!chain.some(({ config: c }) => c && (c.include || c.files))) config.include = DEFAULT_INCLUDE(types).map(abs);
345
+ if (!chain.some(({ config: c }) => c && (c.include || c.files))) config.files = inputs;
258
346
  } else {
259
347
  Object.assign(config.compilerOptions, COMPILER_DEFAULTS);
260
- config.include = DEFAULT_INCLUDE(types).map(abs);
261
- config.exclude = ['node_modules', 'website'].map(abs);
348
+ config.files = inputs;
349
+ }
350
+ if (config.files && !config.files.length) {
351
+ rmSync(dir, { recursive: true, force: true });
352
+ console.log('mnfst-types: no local scripts or .d.ts files to check');
353
+ return 0;
262
354
  }
263
355
  config.compilerOptions.paths = paths;
264
356
  config.compilerOptions.noEmit = true;
265
- const dir = mkdtempSync(join(tmpdir(), 'mnfst-tsc-'));
266
357
  const file = join(dir, 'tsconfig.json');
267
358
  try {
268
359
  writeFileSync(file, JSON.stringify(config, null, 2));
@@ -276,10 +367,10 @@ function runTsc(projectRoot, types) {
276
367
  }
277
368
  }
278
369
 
370
+ // No include: editors check whatever is open; --tsc supplies its own inputs
279
371
  function defaultJsconfig(types, aliases = {}) {
280
372
  return JSON.stringify({
281
373
  compilerOptions: { ...COMPILER_DEFAULTS, paths: { mnfst: [`./${types}`], ...aliases } },
282
- include: DEFAULT_INCLUDE(types),
283
374
  exclude: ['node_modules', 'website']
284
375
  }, null, 4) + '\n';
285
376
  }
@@ -343,12 +434,11 @@ async function buildAugmentation(manifest, projectRoot) {
343
434
  return '// No data sources declared in manifest.json.\nexport interface ManifestSources { [sourceName: string]: any }';
344
435
  }
345
436
 
346
- const contract = await loadContract(manifest, projectRoot);
347
437
  const sourceTypes = [];
348
438
  const augmentations = [];
349
439
 
350
440
  for (const [name, config] of Object.entries(data)) {
351
- const inferred = await inferSourceType(name, config, projectRoot, manifest, contract);
441
+ const inferred = await inferSourceType(name, config, projectRoot);
352
442
  if (!inferred) continue;
353
443
  sourceTypes.push(inferred.typeBlock);
354
444
  augmentations.push(` ${jsonKey(name)}: ${inferred.augmentationType};`);
@@ -371,38 +461,7 @@ async function buildAugmentation(manifest, projectRoot) {
371
461
  return lines.join('\n');
372
462
  }
373
463
 
374
- // The project's shared contract (manifest.json `contract`), for Appwrite column names
375
- async function loadContract(manifest, projectRoot) {
376
- const c = manifest.contract;
377
- const ref = c && typeof c === 'object' ? c.module : c;
378
- if (typeof ref !== 'string' || !ref) return null;
379
- const file = resolve(projectRoot, ref.replace(/^\/+/, ''));
380
- if (!existsSync(file)) {
381
- console.warn(`mnfst-types: contract ${ref} not found; Appwrite rows stay loose`);
382
- return null;
383
- }
384
- try {
385
- const mod = await import(`${pathToFileURL(file).href}?mtime=${statSync(file).mtimeMs}`);
386
- return mod && mod.tables && typeof mod.tables === 'object' ? mod.tables : null;
387
- } catch (e) {
388
- console.warn(`mnfst-types: contract ${ref} failed to load (${e.message}); Appwrite rows stay loose`);
389
- return null;
390
- }
391
- }
392
-
393
- function contractColumns(tables, manifest, config) {
394
- if (!tables) return null;
395
- const defaultDb = manifest.appwrite && (manifest.appwrite.databaseId || manifest.appwrite.database);
396
- const db = config.appwriteDatabaseId || defaultDb;
397
- const hit = Object.entries(tables).find(([key, t]) => t && (t.id || key) === config.appwriteTableId && (!t.database || !db || t.database === db));
398
- return hit && Array.isArray(hit[1].columns) ? { key: hit[0], columns: hit[1].columns.filter((c) => typeof c === 'string') } : null;
399
- }
400
-
401
- // ---------------------------------------------------------------------------
402
- // Source-shape inference
403
- // ---------------------------------------------------------------------------
404
-
405
- async function inferSourceType(name, config, projectRoot, manifest = {}, contract = null) {
464
+ async function inferSourceType(name, config, projectRoot) {
406
465
  const safeName = toTypeName(name);
407
466
 
408
467
  // Appwrite bucket (storage).
@@ -413,21 +472,13 @@ async function inferSourceType(name, config, projectRoot, manifest = {}, contrac
413
472
  };
414
473
  }
415
474
 
416
- // Appwrite table: column names from the contract when it declares the table.
475
+ // Appwrite table: any field until the project declares ManifestRows.<name>
417
476
  if (config && typeof config === 'object' && config.appwriteTableId) {
418
477
  const rowType = `Row_${safeName}`;
419
- const declared = contractColumns(contract, manifest, config);
420
- const typeBlock = declared
421
- ? [
422
- `/** Row shape for $x.${name}: columns of "${declared.key}" in the contract (declare ManifestRows.${name} for precise types). */`,
423
- `export type ${rowType} = ManifestRowSystem & {`,
424
- ...declared.columns.map((c) => ` ${jsonKey(c)}: any;`),
425
- `};`
426
- ].join('\n')
427
- : [
428
- `/** Row shape for $x.${name} (Appwrite table; add it to the contract, or declare ManifestRows.${name}, for checked columns). */`,
429
- `export type ${rowType} = ManifestRowSystem & { [field: string]: any };`
430
- ].join('\n');
478
+ const typeBlock = [
479
+ `/** Row shape for $x.${name} (Appwrite table; declare ManifestRows.${name} for checked fields). */`,
480
+ `export type ${rowType} = ManifestRowSystem & { [field: string]: any };`
481
+ ].join('\n');
431
482
  return {
432
483
  typeBlock,
433
484
  augmentationType: `ManifestTableSource<ManifestRowFor<${JSON.stringify(name)}, ${rowType}>>`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mnfst-types",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "Generate TypeScript types for a Manifest project from manifest.json and sample data",
5
5
  "type": "module",
6
6
  "bin": {
@@ -194,13 +194,13 @@ export interface ManifestAppwriteBucketOps {
194
194
  $remove(fileId: string): Promise<void>;
195
195
  $delete(fileId: string | string[]): Promise<unknown>;
196
196
  $duplicate(fileId: string, options?: { newName?: string; newFileId?: string }): Promise<ManifestFile>;
197
- $filesFor(parentId: string, fieldName?: string): ManifestFile[];
197
+ $filesFor(tableName: string, entryId: string, fileIdsColumn?: string): Promise<ManifestFile[]>;
198
198
  $first(limit?: number): Promise<ManifestCursorPage<ManifestFile>>;
199
199
  $next(cursor: string, limit?: number): Promise<ManifestCursorPage<ManifestFile>>;
200
200
  $prev(cursor: string, limit?: number): Promise<ManifestCursorPage<ManifestFile>>;
201
201
  $page(page: number, limit?: number): Promise<ManifestOffsetPage<ManifestFile>>;
202
- $unlinkFrom(parentId: string, fileId: string): Promise<void>;
203
- $removeFrom(parentId: string, fileId: string): Promise<void>;
202
+ $unlinkFrom(tableName: string, entryId: string, file: string | { $id: string }, fileIdsColumn?: string): Promise<void>;
203
+ $removeFrom(tableName: string, entryId: string, file: string | { $id: string }, fileIdsColumn?: string): Promise<ManifestFile[] | null>;
204
204
  }
205
205
 
206
206
  /**
@@ -226,8 +226,8 @@ export type ManifestObjectSource<T> = T & ManifestSourceState;
226
226
  export type ManifestBucketSource = ReadonlyArray<ManifestFile> & ManifestSourceState & ManifestAppwriteBucketOps;
227
227
 
228
228
  /**
229
- * Precise row types, keyed by data source name. Declare them to override the
230
- * column names `npx mnfst-types` reads from the contract:
229
+ * Precise row types, keyed by data source name. Appwrite rows accept any
230
+ * field until declared here:
231
231
  *
232
232
  * declare module 'mnfst' { interface ManifestRows { tasks: Task } }
233
233
  */
@@ -387,6 +387,33 @@ export interface ManifestPresence {
387
387
  /** `$date(id?)` from the datepicker plugin — the picker API for the nearest (or given) instance. */
388
388
  export type ManifestDate = (id?: string) => Record<string, unknown>;
389
389
 
390
+ /** `x-chart` config object (standalone; annotate config objects with it). */
391
+ export interface ManifestChartConfig {
392
+ type?: 'line' | 'area' | 'bar' | 'combo' | 'scatter' | 'candlestick' | 'ohlc' | 'pie' | 'donut' | 'gauge' | 'heatmap' | 'gantt' | 'map' | (string & {});
393
+ labels?: unknown[];
394
+ series?: Array<{ name?: string; data?: unknown[]; color?: string; type?: string }>;
395
+ data?: unknown;
396
+ height?: number;
397
+ stacked?: boolean;
398
+ legend?: boolean;
399
+ axis?: boolean;
400
+ grid?: boolean;
401
+ tooltip?: boolean;
402
+ dataLabels?: boolean;
403
+ curve?: 'monotone' | 'linear' | 'step' | 'step-after' | 'step-before' | 'natural' | (string & {});
404
+ ticks?: Array<number | { at: number; label?: string }>;
405
+ tickAnchor?: 'start' | 'end';
406
+ /** Line/area/combo: `false` drops per-point dots; hover columns show every series at that label. Map: marker list. */
407
+ points?: boolean | Array<Record<string, unknown>>;
408
+ /** Cartesian (incl. candlestick): widens the y-axis to include it. Gauge: range start. Gantt: axis start (number or date). */
409
+ min?: number | string | Date;
410
+ /** Cartesian (incl. candlestick): widens the y-axis to include it. Gauge: range end. Gantt: axis end (number or date). */
411
+ max?: number | string | Date;
412
+ /** Intl.NumberFormat options for tooltip and data-label values; axis ticks add compact notation. */
413
+ format?: Intl.NumberFormatOptions;
414
+ [key: string]: unknown;
415
+ }
416
+
390
417
  /** `$chart(id?)` from the charts plugin — the chart API for the nearest (or given) instance. */
391
418
  export type ManifestChart = (id?: string) => Record<string, unknown>;
392
419