@open-artifact/data-core 0.11.0 → 0.12.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-artifact/data-core",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "The Data type's model, free of DOM and React: dataset and dashboard documents, filters and their rules, SQL filling, tables and data files, connector answer readers, dash/look colors, drafts, the view context and the project check.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -16,8 +16,8 @@
16
16
  "NOTICE"
17
17
  ],
18
18
  "dependencies": {
19
- "@open-artifact/live-store": "0.11.0",
20
- "@open-artifact/wasm-data-rules": "0.11.0"
19
+ "@open-artifact/live-store": "0.12.1",
20
+ "@open-artifact/wasm-data-rules": "0.12.1"
21
21
  },
22
22
  "license": "Apache-2.0",
23
23
  "author": {
package/src/check-page.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { cellToString } from "./tables.js";
2
2
  import { DASH_PAGE_TOKENS, dashChartToken, MAX_LOOK_CHARTS } from "./look.js";
3
3
  const VOID_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
4
- const DROPPED_TAGS = new Set(['meta', 'base', 'form', 'iframe', 'frame', 'frameset', 'object', 'embed', 'portal', 'fencedframe']);
4
+ const DROPPED_TAGS = new Set(['meta', 'base', 'iframe', 'frame', 'frameset', 'object', 'embed', 'portal', 'fencedframe']);
5
5
  const SCRIPT_TYPES = new Set(['', 'text/javascript', 'application/javascript']);
6
6
  const FIGURE_PATTERN = /(?<![\w.#-])(?:[$€£¥]\s?\d[\d,.]*|\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?\s?%|\d+\.\d+|\d{3,})(?![\w.-])/;
7
7
  const YEAR_OR_DATE_PATTERN = /^(?:19|20)\d{2}$|\d{4}-\d{2}/;
@@ -157,7 +157,7 @@ export function checkDashboardPage(files, datasets, report) {
157
157
  const oneWriter = page.elements.some(isOneWriterMeta);
158
158
  for (const element of page.elements) {
159
159
  if (DROPPED_TAGS.has(element.tag) && !isOneWriterMeta(element))
160
- report(PAGE_DOC, 'warning', `<${element.tag}> is dropped${element.tag === 'form' ? ' with everything in it' : ''}.`, element.line);
160
+ report(PAGE_DOC, 'warning', `<${element.tag}> is dropped.`, element.line);
161
161
  const priority = element.attrs['data-fetchpriority'];
162
162
  if (priority !== undefined && !['high', 'low'].includes(priority.trim().toLowerCase()))
163
163
  report(PAGE_DOC, 'warning', `data-fetchpriority="${priority}" reads as auto; it is high or low.`, element.line);
package/src/check.d.ts CHANGED
@@ -35,7 +35,10 @@ export declare const LOOK_TWEAK_SIZES: readonly string[];
35
35
  export declare const LOCAL_OWNER_ID = "owner";
36
36
  /** The file a finding names for a store path. */
37
37
  export declare function dataDocumentFile(path: string): string;
38
- /** Store paths the history leaves out: each person's own documents and drafts. */
38
+ /**
39
+ * Store paths the history leaves out: what the page saves under `data/` (each person's own documents too), drafts,
40
+ * and `dash/settings` (how often the sources update).
41
+ */
39
42
  export declare function dataHistoryIgnores(path: string): boolean;
40
43
  /** A new, empty dashboard's documents by store path (without `.json`), as JSON text. */
41
44
  export declare function scaffoldDataProject(title: string): Record<string, string>;
package/src/check.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { isPlainObject } from "./text.js";
2
- import { DASHBOARD_ENTRY_PATH, DASH_LOOK_PATH, DASH_META_PATH, DASH_PARAMS_PATH, DASH_SETTINGS_PATH, DRAFTS_COLLECTION, USER_DATA_COLLECTION, isValidDashboardFilename, isValidDatasetId, parseDataPath, userCheckPath, userRunsPath, } from "./paths.js";
2
+ import { DASHBOARD_ENTRY_PATH, DASH_LOOK_PATH, DASH_META_PATH, DASH_PARAMS_PATH, DASH_SETTINGS_PATH, DRAFTS_COLLECTION, isValidDashboardFilename, isValidDatasetId, parseDataPath, userCheckPath, userRunsPath, } from "./paths.js";
3
3
  import { MAX_DATA_BYTES, PAGE_LANGUAGE_PATTERN, STORED_BLOB_PATH_PATTERN, isValidParameterName, parseDashboardUpdates, parseDataset, parseParameterValue, } from "./model.js";
4
- import { DATA_FILE_FORMATS, inferDataFileFormat, parseDataFileTable } from "./tables.js";
4
+ import { DATA_FILE_FORMATS, inferDataFileFormat, parseDataFileTable, parseFileJson } from "./tables.js";
5
+ import { MAX_SAVED_ROWS_PATH_SEGMENTS, SAVED_ROWS_ROOT, savedRowsPathProblem } from "./saved-rows.js";
5
6
  import { getDatasetParameterNames, getSourceRuleProblems } from "./fill.js";
6
7
  import { CARD_LUMINANCE, CHART_CONTRAST, DEFAULT_LOOK_TEXT, GROUND_LUMINANCE, LOOK_SIZE_RANGES, LOOK_STATUSES, MAX_LOOK_CHARTS, MAX_LOOK_CORNERS, MIN_BORDER_DISTANCE, MIN_CHART_DISTANCE, TEXT_CONTRAST, UI_CONTRAST, colorDistance, contrastRatio, isDarkColor, mixHex, parseFontStack, parseLookColor, relativeLuminance, } from "./look.js";
7
8
  import { parseDraftHead } from "./drafts.js";
@@ -47,10 +48,15 @@ const CHECK_DRAWING_WORDS = {
47
48
  export function dataDocumentFile(path) {
48
49
  return `db/${path}.json`;
49
50
  }
50
- /** Store paths the history leaves out: each person's own documents and drafts. */
51
+ /**
52
+ * Store paths the history leaves out: what the page saves under `data/` (each person's own documents too), drafts,
53
+ * and `dash/settings` (how often the sources update).
54
+ */
51
55
  export function dataHistoryIgnores(path) {
52
56
  const clean = path.replace(/^\/+/, '').replace(/\.json$/, '');
53
- return [USER_DATA_COLLECTION, DRAFTS_COLLECTION].some((collection) => clean === collection || clean.startsWith(`${collection}/`));
57
+ if (clean === DASH_SETTINGS_PATH)
58
+ return true;
59
+ return [SAVED_ROWS_ROOT, DRAFTS_COLLECTION].some((collection) => clean === collection || clean.startsWith(`${collection}/`));
54
60
  }
55
61
  /** A new, empty dashboard's documents by store path (without `.json`), as JSON text. */
56
62
  export function scaffoldDataProject(title) {
@@ -58,15 +64,34 @@ export function scaffoldDataProject(title) {
58
64
  }
59
65
  const kb = (bytes) => (bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.ceil(bytes / 1024)} KB`);
60
66
  const utf8Bytes = (text) => new TextEncoder().encode(text).length;
61
- /** What the page reads as a document's `edit` stamp: the agent's `{via, at}` or a person's `{by, byAt}`. */
67
+ /**
68
+ * The `edit` stamp is the page's own: `{by, byAt}`, the person who last changed the document on the page. History
69
+ * names the agent by itself, so a stamp the agent wrote (`{via, at}`) is only noted.
70
+ */
62
71
  function editStampProblem(edit) {
63
- const message = 'edit must be {via: "agent", at: <UTC ISO>} (the page ignores anything else).';
72
+ const leaveOut = 'leave edit out of what you write: the page stamps the person who changes it there, and History names you by itself.';
64
73
  if (!isPlainObject(edit))
65
- return message;
74
+ return `edit is the page’s {by, byAt}; ${leaveOut}`;
66
75
  const time = (value) => typeof value === 'number' ? Number.isFinite(value) : typeof value === 'string' && !Number.isNaN(Date.parse(value));
67
- const writer = typeof edit.via === 'string' && time(edit.at);
68
- const person = typeof edit.by === 'string' && time(edit.byAt);
69
- return writer || person ? null : message;
76
+ if (typeof edit.by === 'string' && time(edit.byAt))
77
+ return null;
78
+ return edit.via !== undefined ? `edit holds {via, at}, which the page ignores; ${leaveOut}` : `edit is the page’s {by, byAt}; ${leaveOut}`;
79
+ }
80
+ const SAVED_ROWS_PATH_HINT = 'a collection such as data/team/notes, or one document such as data/team/notes/today';
81
+ function savedRowsPathMessage(problem, path) {
82
+ const shown = JSON.stringify(path);
83
+ switch (problem) {
84
+ case 'not_text':
85
+ return `source.path is missing: where the page saves the rows, ${SAVED_ROWS_PATH_HINT} (data/users/me/… for each reader’s own).`;
86
+ case 'outside_data':
87
+ return `source.path ${shown} isn’t under data/: saved rows are kept in ${SAVED_ROWS_PATH_HINT}.`;
88
+ case 'too_deep':
89
+ return `source.path ${shown} has more than ${MAX_SAVED_ROWS_PATH_SEGMENTS} parts.`;
90
+ case 'bad_segment':
91
+ return `source.path ${shown}: each part is 1–200 of A–Z a–z 0–9 _ - . ~ : @ + (and not . or ..).`;
92
+ case 'own_report':
93
+ return `source.path ${shown} is one of the page’s own reports (a person’s folder, check, runs, page, history-…), not saved rows.`;
94
+ }
70
95
  }
71
96
  function checkMeta(meta, report) {
72
97
  const doc = DASH_META_PATH;
@@ -268,12 +293,12 @@ function checkDataset(id, data, params, loaders, context, report) {
268
293
  }
269
294
  const rawSource = isPlainObject(data.source) ? data.source : null;
270
295
  if (rawSource === null) {
271
- issue('needs source: {kind: "call", connector, tool, args} (a live query) or {kind: "file", url, name, format} (an upload).');
296
+ issue('needs source: {kind: "call", connector, tool, args} (a live query), {kind: "file", url, name, format} (an upload) or {kind: "store", path} (rows saved from the page).');
272
297
  return info;
273
298
  }
274
299
  const dataset = parseDataset(id, data);
275
300
  if (dataset === null) {
276
- issue('source has no kind the page reads: give it a "kind" of "call" (a live query) or "file" (an upload).');
301
+ issue('source has no kind the page reads: give it a "kind" of "call" (a live query), "file" (an upload) or "store" (saved rows).');
277
302
  return info;
278
303
  }
279
304
  const { source } = dataset;
@@ -281,7 +306,13 @@ function checkDataset(id, data, params, loaders, context, report) {
281
306
  if (source.rawKind === 'rows')
282
307
  issue('is an old rows dataset (it shows "Didn’t load"): make its rows a JSON file, upload it, then set the document with a file source and updated.');
283
308
  else
284
- issue(`source.kind ${JSON.stringify(source.rawKind)} isn’t one the page loads; use "call" or "file".`);
309
+ issue(`source.kind ${JSON.stringify(source.rawKind)} isn’t one the page loads; use "call", "file" or "store".`);
310
+ return info;
311
+ }
312
+ if (source.kind === 'store') {
313
+ const problem = savedRowsPathProblem(rawSource.path);
314
+ if (problem !== null)
315
+ issue(savedRowsPathMessage(problem, rawSource.path));
285
316
  return info;
286
317
  }
287
318
  if (source.kind === 'query') {
@@ -341,19 +372,24 @@ function checkDataset(id, data, params, loaders, context, report) {
341
372
  if (loaders.has(id)) {
342
373
  // Its loader makes the rows when the page runs; runs says what it gave.
343
374
  }
344
- else if (format === 'text') {
345
- issue(`format "text" has no rows of its own: add dash.loader("${id}", {description, fn}) that makes them from the file’s text.`);
346
- return info;
347
- }
348
- else {
375
+ else if (format !== 'text') {
376
+ // A "text" file is its text: a calc that takes it gets [], dash.data gives the text as its data.
349
377
  const text = context.readBlob?.(blob);
350
378
  if (text !== undefined && text !== null) {
351
379
  const table = parseDataFileTable(text, format);
352
- if (table === null) {
353
- issue(`the file has no rows the page can read as ${format}${format === 'json' ? ' (an array of row objects, or one under rows/data/results)' : ''}; or add dash.loader("${id}", …) that makes rows of its text.`);
380
+ if (table !== null)
381
+ info.table = table;
382
+ else if (format === 'json') {
383
+ // Other valid JSON is the source's value, for a calc or the page's own code.
384
+ if (parseFileJson(text) === undefined) {
385
+ issue(`the file isn’t valid JSON; upload it again as JSON, or as "text" with dash.loader("${id}", …) to read it.`);
386
+ return info;
387
+ }
388
+ }
389
+ else {
390
+ issue(`the file has no rows the page can read as ${format}; or add dash.loader("${id}", …) that makes rows of its text.`);
354
391
  return info;
355
392
  }
356
- info.table = table;
357
393
  }
358
394
  }
359
395
  const updated = isPlainObject(data.updated) ? data.updated : null;
@@ -423,7 +459,7 @@ function checkPageReports(docs, context, report) {
423
459
  report(checkPath, level, `the open page found ${CHECK_DRAWING_WORDS[String(entry.what)] ?? String(entry.what)}${times}${note}.`);
424
460
  else {
425
461
  const did = entry.kind === 'stopped' ? 'stopped' : entry.kind === 'rejection' ? 'left a promise rejected' : 'threw';
426
- report(checkPath, level, `the page's code ${did}: ${String(entry.name)}${typeof entry.file === 'string' ? ` in ${entry.file}` : ''}${times}; errors in ${runsPath} hold its words${note}.`);
462
+ report(checkPath, level, `the page's code ${did}: ${String(entry.name)}${typeof entry.file === 'string' ? ` in ${entry.file}` : ''}${typeof entry.where === 'string' && entry.where !== '' ? `, where ${entry.where.slice(0, 80)}` : ''}${times}; errors in ${runsPath} hold its words${note}.`);
427
463
  }
428
464
  }
429
465
  for (const entry of Array.isArray(check.sources) ? check.sources.filter(isPlainObject) : []) {
@@ -310,6 +310,8 @@ export interface CalculationContext {
310
310
  input(id: string): {
311
311
  status: 'ok' | 'loading' | 'missing' | 'error' | 'connect' | 'declined';
312
312
  rows: unknown[];
313
+ /** What a source holds when it isn't rows. */
314
+ value?: unknown;
313
315
  };
314
316
  stateOf(id: string): unknown[];
315
317
  post(report: CalculationReport): void;
@@ -0,0 +1,34 @@
1
+ /** Files a person imports on an empty dashboard, and the request that hands them to the agent. */
2
+ import type { DataFileFormat } from './types.ts';
3
+ /** What an imported file holds: a data file a source reads as it is, or a workbook the agent turns into CSV. */
4
+ export type ImportedFileKind = DataFileFormat | 'workbook';
5
+ /** An imported file once stored. */
6
+ export interface ImportedFile {
7
+ name: string;
8
+ /** Its stored url (`/_blob/<id>`). */
9
+ url: string;
10
+ kind: ImportedFileKind;
11
+ }
12
+ /** What the import button's file picker offers. */
13
+ export declare const IMPORT_FILE_ACCEPT: string;
14
+ /** Largest file the import takes, in bytes. */
15
+ export declare const MAX_IMPORT_FILE_BYTES: number;
16
+ /** The kind of a picked file from its name, then its media type; `null` when it is none the import takes. */
17
+ export declare function importedFileKind(name: string, type?: string): ImportedFileKind | null;
18
+ /** The request sent to the agent: build the empty dashboard in the picked format from the imported files. */
19
+ export declare function importPrompt(form: string, files: readonly ImportedFile[]): string;
20
+ /** Where an import request came from, for the agent to read as data. */
21
+ export interface ImportSelection {
22
+ label: string;
23
+ chip: {
24
+ about: 'import';
25
+ form: string;
26
+ files: {
27
+ name: string;
28
+ url: string;
29
+ kind: ImportedFileKind;
30
+ }[];
31
+ };
32
+ text: string;
33
+ }
34
+ export declare function importSelection(form: string, files: readonly ImportedFile[]): ImportSelection;
package/src/imports.js ADDED
@@ -0,0 +1,76 @@
1
+ /** Files a person imports on an empty dashboard, and the request that hands them to the agent. */
2
+ import { DEFAULT_DASHBOARD_FORM, findDashboardFormKey } from "./forms.js";
3
+ import { remixFormName } from "./drafts.js";
4
+ import { inferDataFileFormat } from "./tables.js";
5
+ const WORKBOOK_TYPES = [
6
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
7
+ 'application/vnd.ms-excel',
8
+ ];
9
+ /** What the import button's file picker offers. */
10
+ export const IMPORT_FILE_ACCEPT = [
11
+ '.csv',
12
+ '.tsv',
13
+ '.tab',
14
+ '.json',
15
+ '.geojson',
16
+ '.xlsx',
17
+ '.xls',
18
+ 'text/csv',
19
+ 'text/tab-separated-values',
20
+ 'application/json',
21
+ 'application/geo+json',
22
+ ...WORKBOOK_TYPES,
23
+ ].join(',');
24
+ /** Largest file the import takes, in bytes. */
25
+ export const MAX_IMPORT_FILE_BYTES = 25 * 1024 * 1024;
26
+ /** The kind of a picked file from its name, then its media type; `null` when it is none the import takes. */
27
+ export function importedFileKind(name, type = '') {
28
+ const lower = name.toLowerCase();
29
+ if (lower.endsWith('.xlsx') || lower.endsWith('.xls'))
30
+ return 'workbook';
31
+ const byName = inferDataFileFormat(name);
32
+ if (byName !== null)
33
+ return byName;
34
+ const media = type.split(';')[0]?.trim().toLowerCase() ?? '';
35
+ if (WORKBOOK_TYPES.includes(media))
36
+ return 'workbook';
37
+ if (media === 'text/csv')
38
+ return 'csv';
39
+ if (media === 'text/tab-separated-values')
40
+ return 'tsv';
41
+ if (media === 'application/json' || media === 'application/geo+json')
42
+ return 'json';
43
+ return null;
44
+ }
45
+ const KIND_NAMES = {
46
+ csv: 'CSV',
47
+ tsv: 'TSV',
48
+ json: 'JSON',
49
+ text: 'text',
50
+ workbook: 'Excel workbook',
51
+ };
52
+ /** The format the request names: a known one, else the default. */
53
+ function knownForm(form) {
54
+ return findDashboardFormKey(form) ?? DEFAULT_DASHBOARD_FORM;
55
+ }
56
+ function fileLine({ name, url, kind }) {
57
+ return `${JSON.stringify(name)} at ${url} (${KIND_NAMES[kind]})`;
58
+ }
59
+ /** The request sent to the agent: build the empty dashboard in the picked format from the imported files. */
60
+ export function importPrompt(form, files) {
61
+ const workbook = files.some((file) => file.kind === 'workbook');
62
+ return (`Build this dashboard as a ${remixFormName(knownForm(form))} from the ${files.length === 1 ? 'file' : 'files'} I imported: ` +
63
+ files.map(fileLine).join('; ') +
64
+ '. Attach each as a file source' +
65
+ (workbook ? ', with each sheet you use from a workbook uploaded as its own CSV' : '') +
66
+ '. See "Imported files" in SKILL.md.');
67
+ }
68
+ export function importSelection(form, files) {
69
+ const known = knownForm(form);
70
+ const name = remixFormName(known);
71
+ return {
72
+ label: `Import ${files.length === 1 ? (files[0]?.name ?? 'a file') : `${files.length} files`}`,
73
+ chip: { about: 'import', form: known, files: files.map(({ name: file, url, kind }) => ({ name: file, url, kind })) },
74
+ text: `From the empty dashboard's Import a file button, with ${name} (${known}) picked as the format.`,
75
+ };
76
+ }
package/src/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export * from './connector-types.ts';
3
3
  export * from './text.ts';
4
4
  export * from './paths.ts';
5
5
  export * from './tables.ts';
6
+ export * from './saved-rows.ts';
6
7
  export * from './rule-pattern.ts';
7
8
  export * from './model.ts';
8
9
  export * from './addresses.ts';
@@ -18,6 +19,7 @@ export * from './forms.ts';
18
19
  export * from './records.ts';
19
20
  export * from './versions.ts';
20
21
  export * from './drafts.ts';
22
+ export * from './imports.ts';
21
23
  export * from './view-context.ts';
22
24
  export * from './check.ts';
23
25
  export * from './check-page.ts';
package/src/index.js CHANGED
@@ -3,6 +3,7 @@ export * from "./connector-types.js";
3
3
  export * from "./text.js";
4
4
  export * from "./paths.js";
5
5
  export * from "./tables.js";
6
+ export * from "./saved-rows.js";
6
7
  export * from "./rule-pattern.js";
7
8
  export * from "./model.js";
8
9
  export * from "./addresses.js";
@@ -18,6 +19,7 @@ export * from "./forms.js";
18
19
  export * from "./records.js";
19
20
  export * from "./versions.js";
20
21
  export * from "./drafts.js";
22
+ export * from "./imports.js";
21
23
  export * from "./view-context.js";
22
24
  export * from "./check.js";
23
25
  export * from "./check-page.js";
package/src/model.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { RESERVED_OBJECT_KEYS, asRecord, getOwnProperty, isPlainObject, isSafeCount, normalizeCodeLanguage, normalizeDescription, parseBoundedInteger, parseEnumValue, parseTimestamp, sanitizeSingleLine, sanitizeText, } from "./text.js";
2
2
  import { isValidDashboardFilename, isValidDatasetId } from "./paths.js";
3
+ import { isSavedRowsPath } from "./saved-rows.js";
3
4
  import { DATA_FILE_FORMATS, inferDataFileFormatOrCsv } from "./tables.js";
4
5
  export const MAX_ERROR_MESSAGE_CHARACTERS = 400;
5
6
  /** The largest data file the file editor stores. */
@@ -215,6 +216,10 @@ export function parseDatasetSource(record) {
215
216
  format: parseEnumValue(getOwnProperty(record, 'format'), DATA_FILE_FORMATS, inferDataFileFormatOrCsv(fileName)),
216
217
  };
217
218
  }
219
+ if (name === 'store') {
220
+ const path = getOwnProperty(record, 'path');
221
+ return { kind: 'store', path: isSavedRowsPath(path) ? path : '' };
222
+ }
218
223
  return { kind: 'unsupported', rawKind: sanitizeSingleLine(name) };
219
224
  }
220
225
  /** A query's `langs`: each argument name to its code language, lower-cased; `undefined` when none. */
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Saved rows: what people enter on the page (ticks, notes, targets), kept in the artifact's own store under `data/`
3
+ * and read back as a source, `{kind: "store", path}`. A path with an odd number of segments names a collection (one
4
+ * row per document, by document ID); an even number names one document (one row while it exists).
5
+ */
6
+ import type { Table } from './types.ts';
7
+ /** Where saved rows live: `data/…`. */
8
+ export declare const SAVED_ROWS_ROOT = "data";
9
+ /** `data/users/me/…` stands for the person looking at the page. */
10
+ export declare const CURRENT_VIEWER_ALIAS = "me";
11
+ /** A collection gives at most this many rows, the first by document ID. */
12
+ export declare const MAX_SAVED_ROWS = 1000;
13
+ export declare const MAX_SAVED_ROWS_PATH_SEGMENTS = 16;
14
+ /** How long the first answer for saved rows may take before the source counts as failed. */
15
+ export declare const SAVED_ROWS_FIRST_ANSWER_MS = 10000;
16
+ /** Why a path can't hold saved rows. */
17
+ export type SavedRowsPathProblem = 'not_text' | 'outside_data' | 'bad_segment' | 'too_deep' | 'own_report';
18
+ export type SavedRowsShape = 'collection' | 'document';
19
+ /** One stored document of saved rows: its ID (the last path segment) and its fields. */
20
+ export interface SavedRowsDocument {
21
+ id: string;
22
+ data: Record<string, unknown>;
23
+ }
24
+ /** What keeps `path` from naming saved rows, or `null` when it does. */
25
+ export declare function savedRowsPathProblem(path: unknown): SavedRowsPathProblem | null;
26
+ export declare function isSavedRowsPath(path: unknown): path is string;
27
+ /** A collection (odd number of segments) or one document (even). */
28
+ export declare function getSavedRowsShape(path: string): SavedRowsShape;
29
+ /** The path with `data/users/me` read as this viewer's own folder. */
30
+ export declare function resolveSavedRowsPath(path: string, viewerId: string): string;
31
+ /**
32
+ * Whether a stored path (with `me` already read as an id) is inside `data/users/<viewerId>/`, the folder that is that
33
+ * person's own: what a commenter may write. The folder itself is no document, so it doesn't count.
34
+ */
35
+ export declare function isInViewerFolder(path: string, viewerId: string): boolean;
36
+ /** Orders document IDs as the store does: by UTF-16 code unit, so the same rows come first everywhere. */
37
+ export declare const compareSavedRowIds: (a: string, b: string) => number;
38
+ /**
39
+ * The rows a source of saved rows gives: one per document (all its fields, with its ID in `id`), sorted by ID and
40
+ * cut to {@link MAX_SAVED_ROWS} (the table is then marked as cut). No documents give no rows, only the `id` column.
41
+ */
42
+ export declare function savedRowsTable(documents: readonly SavedRowsDocument[]): Table;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Saved rows: what people enter on the page (ticks, notes, targets), kept in the artifact's own store under `data/`
3
+ * and read back as a source, `{kind: "store", path}`. A path with an odd number of segments names a collection (one
4
+ * row per document, by document ID); an even number names one document (one row while it exists).
5
+ */
6
+ import { USER_CHECK_DOCUMENT, USER_DATA_COLLECTION, USER_HISTORY_PREFIX, USER_PAGE_DOCUMENT, USER_RUNS_DOCUMENT, } from "./paths.js";
7
+ import { normalizeTable } from "./tables.js";
8
+ /** Where saved rows live: `data/…`. */
9
+ export const SAVED_ROWS_ROOT = 'data';
10
+ /** `data/users/me/…` stands for the person looking at the page. */
11
+ export const CURRENT_VIEWER_ALIAS = 'me';
12
+ /** A collection gives at most this many rows, the first by document ID. */
13
+ export const MAX_SAVED_ROWS = 1000;
14
+ export const MAX_SAVED_ROWS_PATH_SEGMENTS = 16;
15
+ /** How long the first answer for saved rows may take before the source counts as failed. */
16
+ export const SAVED_ROWS_FIRST_ANSWER_MS = 10_000;
17
+ const SAVED_ROWS_SEGMENT = /^[A-Za-z0-9_\-.~:@+]{1,200}$/;
18
+ const OWN_REPORT_NAMES = new Set([USER_CHECK_DOCUMENT, USER_RUNS_DOCUMENT, USER_PAGE_DOCUMENT]);
19
+ const segmentsOf = (path) => path.split('/');
20
+ /** `data/users/<someone>` itself, or one of the type's own documents in it (`check`, `runs`, `page`, `history-…`). */
21
+ function isOwnReport(segments) {
22
+ const [root, users, , name] = segments;
23
+ if (`${root}/${users}` !== USER_DATA_COLLECTION)
24
+ return false;
25
+ if (segments.length === 3)
26
+ return true;
27
+ return segments.length === 4 && name !== undefined && (OWN_REPORT_NAMES.has(name) || name.startsWith(USER_HISTORY_PREFIX));
28
+ }
29
+ /** What keeps `path` from naming saved rows, or `null` when it does. */
30
+ export function savedRowsPathProblem(path) {
31
+ if (typeof path !== 'string' || path === '')
32
+ return 'not_text';
33
+ const segments = segmentsOf(path);
34
+ if (segments[0] !== SAVED_ROWS_ROOT || segments.length < 2)
35
+ return 'outside_data';
36
+ if (segments.length > MAX_SAVED_ROWS_PATH_SEGMENTS)
37
+ return 'too_deep';
38
+ if (segments.some((segment) => segment === '.' || segment === '..' || !SAVED_ROWS_SEGMENT.test(segment)))
39
+ return 'bad_segment';
40
+ return isOwnReport(segments) ? 'own_report' : null;
41
+ }
42
+ export function isSavedRowsPath(path) {
43
+ return savedRowsPathProblem(path) === null;
44
+ }
45
+ /** A collection (odd number of segments) or one document (even). */
46
+ export function getSavedRowsShape(path) {
47
+ return segmentsOf(path).length % 2 === 1 ? 'collection' : 'document';
48
+ }
49
+ /** The path with `data/users/me` read as this viewer's own folder. */
50
+ export function resolveSavedRowsPath(path, viewerId) {
51
+ const prefix = `${USER_DATA_COLLECTION}/${CURRENT_VIEWER_ALIAS}`;
52
+ return path === prefix || path.startsWith(`${prefix}/`) ? `${USER_DATA_COLLECTION}/${viewerId}${path.slice(prefix.length)}` : path;
53
+ }
54
+ /**
55
+ * Whether a stored path (with `me` already read as an id) is inside `data/users/<viewerId>/`, the folder that is that
56
+ * person's own: what a commenter may write. The folder itself is no document, so it doesn't count.
57
+ */
58
+ export function isInViewerFolder(path, viewerId) {
59
+ if (viewerId === '' || viewerId === CURRENT_VIEWER_ALIAS)
60
+ return false;
61
+ const segments = segmentsOf(path);
62
+ return segments.length > 3 && `${segments[0]}/${segments[1]}` === USER_DATA_COLLECTION && segments[2] === viewerId && !segments.includes('..');
63
+ }
64
+ /** Orders document IDs as the store does: by UTF-16 code unit, so the same rows come first everywhere. */
65
+ export const compareSavedRowIds = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
66
+ /**
67
+ * The rows a source of saved rows gives: one per document (all its fields, with its ID in `id`), sorted by ID and
68
+ * cut to {@link MAX_SAVED_ROWS} (the table is then marked as cut). No documents give no rows, only the `id` column.
69
+ */
70
+ export function savedRowsTable(documents) {
71
+ const sorted = [...documents].sort((a, b) => compareSavedRowIds(a.id, b.id));
72
+ const kept = sorted.slice(0, MAX_SAVED_ROWS);
73
+ const table = normalizeTable({ columns: ['id'], rows: kept.map((document) => ({ ...document.data, id: document.id })) });
74
+ const rows = table ?? { columns: [], rows: [] };
75
+ const columns = rows.columns.length === 0 ? ['id'] : rows.columns;
76
+ return sorted.length > MAX_SAVED_ROWS ? { columns, rows: rows.rows, cut: 'rows' } : { columns, rows: rows.rows };
77
+ }
package/src/types.d.ts CHANGED
@@ -79,11 +79,17 @@ export interface CalculationSource {
79
79
  cantRun?: LoadWording;
80
80
  withheld?: string;
81
81
  }
82
+ /** Saved rows: a collection or a document under `data/` that the page writes (see `saved-rows.ts`). */
83
+ export interface StoreSource {
84
+ kind: 'store';
85
+ /** As written; `data/users/me/…` is read as the viewer's own. Empty when the path can't hold saved rows. */
86
+ path: string;
87
+ }
82
88
  export interface UnsupportedSource {
83
89
  kind: 'unsupported';
84
90
  rawKind: string;
85
91
  }
86
- export type DatasetSource = QuerySource | FileSource | CalculationSource | UnsupportedSource;
92
+ export type DatasetSource = QuerySource | FileSource | StoreSource | CalculationSource | UnsupportedSource;
87
93
  export interface ViewerIdentity {
88
94
  id: string;
89
95
  name: string;
@@ -160,7 +166,7 @@ export type LoadWording = {
160
166
  code: 'unasked' | 'heldBack' | 'couldnt' | 'unchosen' | 'stillUnchosen' | 'toolUnavailable' | 'turnedOff' | 'notData';
161
167
  connector: string;
162
168
  } | {
163
- code: 'noLiveData' | 'orgApproval' | 'fileNotStored' | 'fileFailed' | 'fileNoRows' | 'noConnector' | 'noTool' | 'noQuery' | 'resultTooBig' | 'tookTooLong' | 'loadThrew' | 'stillRunning' | 'queryFailed' | 'queryCanceled' | 'resultNotKept' | 'didntFinish' | 'notRows' | 'noJob' | 'noStatement' | 'sqlOpenQuote' | 'calcTakesSpec';
169
+ code: 'noLiveData' | 'orgApproval' | 'fileNotStored' | 'fileFailed' | 'fileNoRows' | 'savedRowsUnavailable' | 'savedRowsSilent' | 'savedRowsFailed' | 'noConnector' | 'noTool' | 'noQuery' | 'resultTooBig' | 'tookTooLong' | 'loadThrew' | 'stillRunning' | 'queryFailed' | 'queryCanceled' | 'resultNotKept' | 'didntFinish' | 'notRows' | 'noJob' | 'noStatement' | 'sqlOpenQuote' | 'calcTakesSpec';
164
170
  } | {
165
171
  code: 'fileStatus';
166
172
  status: string;