@opendatacapture/instrument-guidelines 0.0.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/AGENTS.md ADDED
@@ -0,0 +1,935 @@
1
+ You are an expert senior software engineer. Your role is to design and generate data collection instruments for the Open Data Capture platform.
2
+
3
+ Adhere to the following guidelines:
4
+
5
+ 1. You must ask clarifying questions\*whenever any requirement, field meaning, data semantics, scoring, branching/conditional logic, timing, language, or UX behavior is unclear. Do not try to guess the user’s intent.
6
+ 2. Unless the user explicitly says otherwise, your goal must be to create the most accurate and faithful digital implementation of the user’s source material (e.g., a paper form, protocol, or written spec) while conforming to the instrument specification described below.
7
+ 3. Avoid redundant text unless needed to preserve the original structure; do not restate content in multiple places (e.g., instructions vs. field group descriptions) unless that matches the source.
8
+ 4. If a request would misrepresent the source material, explain why and confirm whether the user wants to proceed anyway.
9
+ 5. Place generated forms in lib/forms and interactive tasks in lib/interactive.
10
+ 6. After generating or modifying an instrument, type-check and lint your work by running `pnpm lint`, and fix any errors it reports.
11
+
12
+ # Instrument Specification
13
+
14
+ ## 1. Core Architecture
15
+
16
+ In Open Data Capture (ODC), an instrument is the unit of data collection: it defines what the user sees, what data is produced, and how that data is validated. Instruments are code-based JavaScript objects and written in TypeScript.
17
+
18
+ Every instrument has a `kind` field that acts as a discriminator. The four valid kinds are:
19
+
20
+ - `FORM` (scalar): declarative form fields, produces a single data payload.
21
+ - `INTERACTIVE` (scalar): arbitrary code that runs in an iframe, produces a single data payload.
22
+ - `FILE` (scalar): collects one or more uploaded files; produces no field data of its own.
23
+ - `SERIES` (non-scalar): ordered list of references to scalar instruments; produces no data itself.
24
+
25
+ The `language` field determines how all UI-facing string fields are structured.
26
+
27
+ - **Unilingual**: `language: 'en'` or `language: 'fr'`
28
+ - All UI string fields are plain values: `title: 'My Instrument'`
29
+ - **Multilingual**: `language: ['en', 'fr']`
30
+ - All UI string fields become per-language objects: `title: { en: 'My Instrument', fr: 'Mon instrument' }`
31
+
32
+ The only two supported languages are `'en'` (English) and `'fr'` (French).
33
+
34
+ ```ts
35
+ type Language = 'en' | 'fr';
36
+ type InstrumentKind = 'FILE' | 'FORM' | 'INTERACTIVE' | 'SERIES';
37
+ type InstrumentLanguage = Language | Language[];
38
+ type InstrumentUIOption<TLanguage extends InstrumentLanguage, TValue> = TLanguage extends Language
39
+ ? TValue
40
+ : TLanguage extends Language[]
41
+ ? { [K in TLanguage[number]]: TValue }
42
+ : never;
43
+ ```
44
+
45
+ All instruments share a common base structure:
46
+
47
+ ```ts
48
+ interface InstrumentDetails<TLanguage extends InstrumentLanguage> {
49
+ /** The legal person(s) that created the instrument and hold copyright to the instrument */
50
+ authors?: null | string[];
51
+
52
+ /** A brief description of the instrument, such as the purpose and history of the instrument */
53
+ description: InstrumentUIOption<TLanguage, string>;
54
+
55
+ /**
56
+ * @deprecated use `clientDetails.estimatedDuration`.
57
+ * An integer representing the estimated number of minutes to complete the instrument.
58
+ */
59
+ estimatedDuration?: number;
60
+
61
+ /**
62
+ * @deprecated use `clientDetails.instructions`.
63
+ * Brief sequential instructions for how the subject should complete the instrument.
64
+ */
65
+ instructions?: InstrumentUIOption<TLanguage, string[]>;
66
+
67
+ /**
68
+ * A valid SPDX license identifier (`LicenseIdentifier`), corresponding to the SPDX license list
69
+ * version d2709ad (released on 2024-01-30). When authoring inside the Open Data Capture
70
+ * repository, this is further narrowed to an `ApprovedLicense` (e.g. `'Apache-2.0'`).
71
+ */
72
+ license: LicenseIdentifier;
73
+
74
+ /** An reference link where the user can learn more about the instrument */
75
+ referenceUrl?: null | string;
76
+
77
+ /** A URL where the user can find the source code for the instrument */
78
+ sourceUrl?: null | string;
79
+
80
+ /** The title of the instrument in the language it is written, omitting the definite article. */
81
+ title: InstrumentUIOption<TLanguage, string>;
82
+ }
83
+
84
+ interface ClientInstrumentDetails<TLanguage extends InstrumentLanguage> {
85
+ /** An integer representing the estimated number of minutes for the average target subject to complete the instrument */
86
+ estimatedDuration?: number;
87
+
88
+ /** Brief sequential instructions for how the subject should complete the instrument. */
89
+ instructions?: InstrumentUIOption<TLanguage, string[]>;
90
+
91
+ /** The title of the instrument to show the client. If not specified, defaults to `details.title` */
92
+ title?: InstrumentUIOption<TLanguage, string>;
93
+ }
94
+
95
+ interface BaseInstrument<TLanguage extends InstrumentLanguage> {
96
+ /** The runtime version for this instrument; set automatically by `defineInstrument`. Do not set it yourself. */
97
+ __runtimeVersion: 1;
98
+ /** The content in the instrument to be rendered to the client */
99
+ clientDetails?: ClientInstrumentDetails<TLanguage>;
100
+ /** The content in the instrument to be rendered to the clinician/researcher */
101
+ content?: unknown;
102
+ /** The details of the instrument to be displayed to the user */
103
+ details: InstrumentDetails<TLanguage>;
104
+ /** The database ID for the instrument. For scalar instruments, this is derived from `internal`. */
105
+ id?: string;
106
+ /** The discriminator key for the type of instrument */
107
+ kind: InstrumentKind;
108
+ /** The language(s) in which the instrument is written */
109
+ language: TLanguage;
110
+ /** A list of tags that users can use to filter instruments */
111
+ tags: InstrumentUIOption<TLanguage, string[]>;
112
+ }
113
+ ```
114
+
115
+ > `__runtimeVersion` is injected by `defineInstrument` / `defineSeriesInstrument` — author your
116
+ > definition object without it.
117
+
118
+ ### 1.1 Scalar vs Series Instruments
119
+
120
+ Scalar instruments are those that can be completed. They:
121
+
122
+ - Have a stable `internal` identity (`edition` + `name`)
123
+ - Define a `validationSchema` (Zod v3 or v4)
124
+ - Produce one output payload (`data`) whose static type is derived from the schema output type
125
+ - Can define `measures` derived from that output
126
+
127
+ ```ts
128
+ type InstrumentMeasureVisibility = 'hidden' | 'visible';
129
+
130
+ // The value a measure may resolve to.
131
+ type InstrumentMeasureValue = boolean | Date | number | RecordArrayFieldValue[] | string | undefined;
132
+
133
+ interface ComputedInstrumentMeasure<TData, TLanguage extends InstrumentLanguage> {
134
+ /** @deprecated use `visibility` */
135
+ hidden?: boolean;
136
+ kind: 'computed';
137
+ label: InstrumentUIOption<TLanguage, string>;
138
+ value: (data: TData) => InstrumentMeasureValue;
139
+ visibility?: InstrumentMeasureVisibility;
140
+ }
141
+
142
+ interface ConstantInstrumentMeasure<TData, TLanguage extends InstrumentLanguage> {
143
+ /** @deprecated use `visibility` */
144
+ hidden?: boolean;
145
+ kind: 'const';
146
+ label?: InstrumentUIOption<TLanguage, string>;
147
+ /** The data key whose value is exposed as a measure (must hold an `InstrumentMeasureValue`). */
148
+ ref: Extract<keyof TData, string>;
149
+ visibility?: InstrumentMeasureVisibility;
150
+ }
151
+
152
+ type InstrumentMeasure<TData, TLanguage extends InstrumentLanguage> =
153
+ | ComputedInstrumentMeasure<TData, TLanguage>
154
+ | ConstantInstrumentMeasure<TData, TLanguage>;
155
+
156
+ type InstrumentMeasures<TData, TLanguage extends InstrumentLanguage> = {
157
+ [key: string]: InstrumentMeasure<TData, TLanguage>;
158
+ };
159
+
160
+ interface ScalarInstrumentInternal {
161
+ edition: number;
162
+ name: string;
163
+ }
164
+
165
+ interface ScalarInstrument<TData, TLanguage extends InstrumentLanguage> extends BaseInstrument<TLanguage> {
166
+ defaultMeasureVisibility?: InstrumentMeasureVisibility;
167
+ internal: ScalarInstrumentInternal;
168
+ measures: InstrumentMeasures<TData, TLanguage> | null;
169
+ validationSchema: z.ZodType<TData>;
170
+ }
171
+ ```
172
+
173
+ Series instruments are orchestration containers. They:
174
+
175
+ - Define an ordered list of scalar instrument identities (the same `{ edition, name }` shape used by scalar `internal`)
176
+ - Do not define `validationSchema`, `measures`, or `internal` (they are not directly completed)
177
+
178
+ The `content` may be either a bare ordered array of identities, or an object that wraps the array
179
+ with optional series-level `params`:
180
+
181
+ ```ts
182
+ type SeriesContent =
183
+ | ScalarInstrumentInternal[]
184
+ | { items: ScalarInstrumentInternal[]; params?: { skipProgress?: boolean } };
185
+
186
+ interface SeriesInstrument<TLanguage extends InstrumentLanguage> extends BaseInstrument<TLanguage> {
187
+ content: SeriesContent;
188
+ internal?: never;
189
+ kind: 'SERIES';
190
+ }
191
+ ```
192
+
193
+ ### 1.2 Scalar Instrument Kinds
194
+
195
+ #### 1.3.1 Form Instruments
196
+
197
+ A form instrument (`kind: 'FORM'`) is a **scalar** instrument with declarative, data-driven content. The validation schema defines the output data shape, and the `content` describes corresponding UI fields.
198
+
199
+ There are two authoring styles supported for `content`:
200
+
201
+ 1. Flat: A direct object mapping from every data key to its field definition
202
+ 2. Grouped: An array of objects, each containing a subset of fields
203
+
204
+ Use flat when all fields belong to a single, unsectioned form. Use grouped when fields should be visually organized into named sections.
205
+
206
+ Every key present in the `validationSchema` object must have a corresponding entry in content object (in the case of a flat structure), or should appear in exactly one group across the full array (in the case of a grouped structure).
207
+
208
+ ##### Data Value Types
209
+
210
+ The `Data` type is a flat record whose values are drawn from a two-level hierarchy of field value types:
211
+
212
+ ```ts
213
+ // Scalar values
214
+ type ScalarFieldValue = boolean | Date | number | Set<string> | string | undefined;
215
+
216
+ // Composite values (contain nested scalar values)
217
+ type FieldsetValue = { [key: string]: ScalarFieldValue }; // one row
218
+ type RecordArrayFieldValue = FieldsetValue[] | undefined; // array of rows
219
+ type NumberRecordFieldValue = Partial<{ [key: string]: number }> | undefined; // keyed numeric scores
220
+
221
+ type CompositeFieldValue = NumberRecordFieldValue | RecordArrayFieldValue;
222
+ type FieldValue = CompositeFieldValue | ScalarFieldValue;
223
+
224
+ // The top-level data record
225
+ type Data = { [key: string]: FieldValue };
226
+ ```
227
+
228
+ The `validationSchema` must produce an object whose keys map to these value types. The TypeScript type of the instrument's `TData` generic is inferred from the schema's output type.
229
+
230
+ ##### Static Scalar Fields
231
+
232
+ Every scalar field extends `BaseField`:
233
+
234
+ ```ts
235
+ interface BaseField<TLanguage extends InstrumentLanguage> {
236
+ description?: InstrumentUIOption<TLanguage, string>;
237
+ disabled?: boolean;
238
+ kind: StaticFieldKind;
239
+ label: InstrumentUIOption<TLanguage, string>;
240
+ }
241
+ ```
242
+
243
+ The five static scalar field types are:
244
+
245
+ **`string`** - corresponds to type `string`
246
+
247
+ ```ts
248
+ // With a fixed set of options (radio buttons or a dropdown)
249
+ interface StringFieldWithOptions<TLanguage, TValue extends string> extends BaseField<TLanguage> {
250
+ kind: 'string';
251
+ options: { [K in TValue]: InstrumentUIOption<TLanguage, { [K in TValue]: string }> }; // maps each valid value to its display label
252
+ variant: 'radio' | 'select';
253
+ }
254
+
255
+ // Free-text input
256
+ interface StringFieldWithoutOptions<TLanguage> extends BaseField<TLanguage> {
257
+ kind: 'string';
258
+ placeholder?: string; // placeholder is plain text, not multilingual
259
+ variant: 'input' | 'textarea';
260
+ }
261
+
262
+ // Masked password input, with an optional strength meter
263
+ interface StringFieldPassword<TLanguage> extends BaseField<TLanguage> {
264
+ kind: 'string';
265
+ // returns a strength score from 0 (weakest) to 4 (strongest)
266
+ calculateStrength?: (this: void, password: string) => 0 | 1 | 2 | 3 | 4;
267
+ variant: 'password';
268
+ }
269
+ ```
270
+
271
+ **`number`** - corresponds to type `number`
272
+
273
+ ```ts
274
+ // With a fixed set of options (radio buttons or a dropdown)
275
+ interface NumberFieldWithOptions<TLanguage, TValue extends number> extends BaseField<TLanguage> {
276
+ disableAutoPrefix?: boolean;
277
+ kind: 'number';
278
+ options: { [K in TValue]: string };
279
+ variant: 'radio' | 'select';
280
+ }
281
+
282
+ // Plain numeric input
283
+ interface NumberFieldInput<TLanguage> extends BaseField<TLanguage> {
284
+ kind: 'number';
285
+ /** @deprecated define the bound in the `validationSchema` instead, for better user feedback */
286
+ max?: number;
287
+ /** @deprecated define the bound in the `validationSchema` instead, for better user feedback */
288
+ min?: number;
289
+ variant: 'input';
290
+ }
291
+
292
+ // Range slider
293
+ interface NumberFieldSlider<TLanguage> extends BaseField<TLanguage> {
294
+ kind: 'number';
295
+ max: number;
296
+ min: number;
297
+ variant: 'slider';
298
+ }
299
+ ```
300
+
301
+ **`date`** - corresponds to type `Date`
302
+
303
+ ```ts
304
+ interface DateField<TLanguage> extends BaseField<TLanguage> {
305
+ kind: 'date';
306
+ }
307
+ ```
308
+
309
+ **`boolean`** - corresponds to type `boolean`
310
+
311
+ ```ts
312
+ interface BooleanFieldCheckbox<TLanguage> extends BaseField<TLanguage> {
313
+ kind: 'boolean';
314
+ variant: 'checkbox';
315
+ }
316
+
317
+ interface BooleanFieldRadio<TLanguage> extends BaseField<TLanguage> {
318
+ kind: 'boolean';
319
+ // define custom display labels for true or false
320
+ options?: InstrumentUIOption<TLanguage, { false: string; true: string }>;
321
+ variant: 'radio';
322
+ }
323
+ ```
324
+
325
+ **`set`** — Represents a multi-select value stored as `Set<string>`:
326
+
327
+ ```ts
328
+ interface SetField<TLanguage, TValue extends Set<string>> extends BaseField<TLanguage> {
329
+ kind: 'set';
330
+ options: InstrumentUIOption<TLanguage, { [K in TItem]: string }>; // TItem = string members of TValue
331
+ variant: 'listbox' | 'select';
332
+ }
333
+ ```
334
+
335
+ ##### Static Composite Fields
336
+
337
+ Composite fields hold structured sub-values rather than a single value.
338
+
339
+ **`record-array`** — An array of uniform rows, each row defined by a `Fieldset`. A `Fieldset` is an object that maps each key in the row to either a static scalar field or a `DynamicFieldsetField` (a field whose presence or definition depends on the current row's partial values):
340
+
341
+ ```ts
342
+ type DynamicFieldsetField<TLanguage, TFieldsetValue, TValue> = {
343
+ kind: 'dynamic';
344
+ render: (this: void, fieldset: Partial<TFieldsetValue>) => null | ScalarField<TLanguage, TValue>;
345
+ };
346
+
347
+ type Fieldset<TLanguage, TFieldset> = {
348
+ [K in keyof TFieldset]:
349
+ | DynamicFieldsetField<TLanguage, TFieldset, TFieldset[K]>
350
+ | ScalarField<TLanguage, TFieldset[K]>;
351
+ };
352
+
353
+ interface RecordArrayField<TLanguage, TValue> extends BaseField<TLanguage> {
354
+ /** When true, suppress the automatic numeric suffix appended to each row's heading */
355
+ disableAutoSuffix?: boolean;
356
+ fieldset: Fieldset<TLanguage, TValue[number]>;
357
+ kind: 'record-array';
358
+ }
359
+ ```
360
+
361
+ **`number-record`** — A fixed set of labeled rows each producing a numeric score, rendered as a Likert-style grid. The `items` object defines the label and optional description for each row key; the `options` object defines the shared column headers (numeric value → display string):
362
+
363
+ ```ts
364
+ interface NumberRecordField<TLanguage, TValue> extends BaseField<TLanguage> {
365
+ /** When true, suppress the automatic numeric prefix shown before each option label */
366
+ disableAutoPrefix?: boolean;
367
+ items: {
368
+ [K in keyof TValue]: {
369
+ description?: InstrumentUIOption<TLanguage, string>;
370
+ label: InstrumentUIOption<TLanguage, string>;
371
+ };
372
+ };
373
+ kind: 'number-record';
374
+ options: InstrumentUIOption<TLanguage, { [key: number]: string }>;
375
+ variant: 'likert';
376
+ }
377
+ ```
378
+
379
+ ##### Dynamic Fields
380
+
381
+ A top-level dynamic field conditionally renders a static field based on the form's current (possibly partial) data. It is used for cross-field conditional logic (e.g., show field B only when field A has a specific value):
382
+
383
+ ```ts
384
+ type DynamicField<TData, TValue, TLanguage> = {
385
+ deps: readonly Extract<keyof TData, string>[]; // keys this field depends on
386
+ kind: 'dynamic';
387
+ render: (this: void, data: PartialData<TData>) => null | StaticField<TLanguage, TValue>;
388
+ };
389
+ ```
390
+
391
+ - `deps` lists the data keys the render function reads. The field is re-evaluated whenever any listed dependency changes.
392
+ - `render` receives the current partial form data and must return either a `StaticField` definition (to show the field) or `null` (to hide it and clear its value).
393
+
394
+ ##### Content Structure
395
+
396
+ ```ts
397
+ type Fields<TData, TLanguage> = {
398
+ [K in keyof TData]-?: UnknownField<TData, K, TLanguage>;
399
+ };
400
+
401
+ type FieldsGroup<TData, TLanguage> = {
402
+ description?: InstrumentUIOption<TLanguage, string>;
403
+ fields: { [K in keyof TData]?: UnknownField<TData, K, TLanguage> };
404
+ title?: InstrumentUIOption<TLanguage, string>;
405
+ };
406
+
407
+ type Content<TData, TLanguage> = Fields<TData, TLanguage> | FieldsGroup<TData, TLanguage>[];
408
+ ```
409
+
410
+ ##### Full Type
411
+
412
+ ```ts
413
+ type FormInstrument<TData extends FormInstrument.Data, TLanguage extends InstrumentLanguage> = ScalarInstrument<
414
+ TData,
415
+ TLanguage
416
+ > & {
417
+ content: FormInstrument.Content<TData, TLanguage>;
418
+ initialValues?: PartialDeep<TData>;
419
+ kind: 'FORM';
420
+ measures: InstrumentMeasures<TData, TLanguage> | null;
421
+ };
422
+ ```
423
+
424
+ - `initialValues` — optional pre-populated values, applied when the form is first rendered. This is a _deep_ partial (`PartialDeep<TData>`), so nested composite values (e.g. individual fields within `record-array` rows) may be partially specified.
425
+
426
+ #### 1.3.2 Interactive Instruments
427
+
428
+ An interactive instrument (`kind: 'INTERACTIVE'`) is a **scalar** instrument that executes arbitrary code inside a sandboxed iframe.
429
+
430
+ ##### Data Type
431
+
432
+ The output data type is not constrained to a schema-derived shape. Instead, `TData` must be assignable to the recursive `Json` type:
433
+
434
+ ```ts
435
+ type JsonLiteral = boolean | null | number | string;
436
+ type Json = Json[] | JsonLiteral | { [key: string]: Json };
437
+
438
+ type Data = Json;
439
+ ```
440
+
441
+ The `validationSchema` must still be provided (as on all scalar instruments) and must produce a type that satisfies `Json`.
442
+
443
+ ##### Content Object
444
+
445
+ The `content` property is a plain object with the following fields:
446
+
447
+ ```ts
448
+ content: {
449
+ /** The entry point for the task. Must call `done` exactly once when the task is complete. */
450
+ render: (done: (data: TData) => void) => PromiseLike<void> | void;
451
+
452
+ /** Raw HTML string to inject into the iframe <body> */
453
+ html?: string;
454
+
455
+ /** <meta> tags for the iframe <head>; each key is the meta name, each value is the content */
456
+ meta?: { [name: string]: string };
457
+
458
+ /** Static asset paths (e.g., '/image.png') mapped to base64 data URLs for use by legacy scripts */
459
+ staticAssets?: { [key: string]: string };
460
+
461
+ /** Enter fullscreen automatically when the instrument content is shown */
462
+ defaultFullscreen?: boolean;
463
+
464
+ /** Show an initial screen to select a language before the instrument begins */
465
+ enableLanguageSelect?: boolean;
466
+
467
+ /** Show a button above the instrument to change languages */
468
+ enableLanguageToggle?: boolean;
469
+
470
+ /** Block the user from changing languages during the instrument */
471
+ enableLanguageLock?: boolean;
472
+
473
+ /** Inject pre-compiled legacy assets into the iframe <head> (for bundles that cannot use the runtime module system) */
474
+ readonly __injectHead?: {
475
+ /** base64-encoded legacy scripts */
476
+ readonly scripts?: readonly string[];
477
+ /** base64-encoded css */
478
+ readonly style?: string;
479
+ };
480
+ }
481
+ ```
482
+
483
+ - `render` is the only required field in `content`. It receives a `done` callback and must call it exactly once with the collected data to end the task and submit the result.
484
+ - `staticAssets` maps virtual paths to base64 data URLs so that legacy scripts referencing asset paths (e.g., image `src` attributes) continue to work inside the iframe sandbox.
485
+ - `__injectHead` is intended for instruments that wrap pre-compiled legacy JavaScript bundles that cannot be refactored to use the runtime module system; in most cases prefer the import forms in §4.2 (`import './legacy.js?legacy'`, `import './styles.css'`) over hand-encoding base64.
486
+ - The `enableLanguage*` options only apply to multilingual instruments (`language: ['en', 'fr']`).
487
+
488
+ ##### Full Type
489
+
490
+ ```ts
491
+ type InteractiveInstrument<
492
+ TData extends InteractiveInstrument.Data,
493
+ TLanguage extends InstrumentLanguage
494
+ > = ScalarInstrument<TData, TLanguage> & {
495
+ content: {
496
+ render: (done: (data: TData) => void) => PromiseLike<void> | void;
497
+ html?: string;
498
+ meta?: { [name: string]: string };
499
+ staticAssets?: { [key: string]: string };
500
+ defaultFullscreen?: boolean;
501
+ enableLanguageSelect?: boolean;
502
+ enableLanguageToggle?: boolean;
503
+ enableLanguageLock?: boolean;
504
+ readonly __injectHead?: {
505
+ readonly scripts?: readonly string[];
506
+ readonly style?: string;
507
+ };
508
+ };
509
+ kind: 'INTERACTIVE';
510
+ };
511
+ ```
512
+
513
+ #### 1.3.3 File Instruments
514
+
515
+ A file instrument (`kind: 'FILE'`) is a **scalar** instrument that collects one or more uploaded files from the subject rather than declarative field data. It still requires a `validationSchema`, but its own `Data` type is empty (`{ [key: string]: never }`) — the files themselves are the payload, not field values.
516
+
517
+ The `content` describes the file slots the subject must fill, grouped into one or more `fileGroups`:
518
+
519
+ ```ts
520
+ namespace FileInstrument {
521
+ type Data = { [key: string]: never };
522
+
523
+ type FileGroup<TLanguage extends InstrumentLanguage> = {
524
+ /** The base filename the uploaded file(s) will be stored under */
525
+ basename: string;
526
+ /** The minimum and maximum number of files accepted for this group */
527
+ count: { max: number; min: number };
528
+ /** The label shown to the user for this group */
529
+ label: InstrumentUIOption<TLanguage, string>;
530
+ /** The single accepted MIME type, or `null` to accept any type */
531
+ type: FileType | null;
532
+ };
533
+
534
+ type Content<TLanguage extends InstrumentLanguage> = {
535
+ fileGroups: FileGroup<TLanguage>[];
536
+ };
537
+ }
538
+
539
+ type FileInstrument<TLanguage extends InstrumentLanguage> = ScalarInstrument<FileInstrument.Data, TLanguage> & {
540
+ content: FileInstrument.Content<TLanguage>;
541
+ kind: 'FILE';
542
+ };
543
+ ```
544
+
545
+ `FileType` is a single MIME string drawn from the predefined `FILE_TYPES` groups:
546
+
547
+ - **binary**: `application/octet-stream`
548
+ - **documents**: `application/pdf`, `text/plain`, `text/markdown`, `text/html`, `application/msword`, `application/vnd.openxmlformats-officedocument.wordprocessingml.document`, `application/rtf`
549
+ - **images**: `image/png`, `image/jpeg`, `image/tiff`, `image/gif`, `image/svg+xml`, `image/bmp`
550
+ - **spreadsheets**: `text/csv`, `text/tsv`, `application/vnd.ms-excel`, `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`, `application/vnd.oasis.opendocument.spreadsheet`
551
+ - **structured**: `application/json`, `application/xml`
552
+
553
+ Because `FileInstrument.Data` is empty, the `validationSchema` should validate to an empty object (e.g. `z.object({})`) and `measures` is typically `null`.
554
+
555
+ ## 3. Runtime API and Imports
556
+
557
+ ### 3.1 Available Runtime Modules
558
+
559
+ All imports must use the runtime URL format: `/runtime/v1/<package>@<version>`.
560
+
561
+ The `validationSchema` may be authored with **either Zod v3 or Zod v4** (`InstrumentValidationSchema` accepts `z.ZodType` from either). Choose the import path accordingly:
562
+
563
+ ```ts
564
+ import { z } from '/runtime/v1/zod@3.x'; // Zod v3 API
565
+ import { z } from '/runtime/v1/zod@3.x/v4'; // Zod v4 API
566
+ ```
567
+
568
+ Prefer one consistently within a single instrument. New instruments should use the v4 API.
569
+
570
+ ### 3.2 The Define Instrument API
571
+
572
+ The `defineInstrument` function must always be used to create scalar (`FORM`, `INTERACTIVE`, and `FILE`) instruments. It accepts a definition object containing all required fields for the chosen `kind`, and returns a fully typed instrument object — including the `__runtimeVersion` field, which it sets automatically. The output data type is derived automatically from the `validationSchema`.
573
+
574
+ ```ts
575
+ import { defineInstrument } from '/runtime/v1/@opendatacapture/runtime-core';
576
+ import { z } from '/runtime/v1/zod@3.x/v4';
577
+ ```
578
+
579
+ The `defineSeriesInstrument` function must always be used to create `SERIES` instruments.
580
+
581
+ ```ts
582
+ import { defineSeriesInstrument } from '/runtime/v1/@opendatacapture/runtime-core';
583
+ ```
584
+
585
+ ### 3.3 Runtime Helpers
586
+
587
+ `@opendatacapture/runtime-core` also exports helpers usable from within an instrument's `render`:
588
+
589
+ - **`addNotification(notification)`** — display a notification in the ODC UI during an **interactive** instrument (does not work in forms):
590
+
591
+ ```ts
592
+ import { addNotification } from '/runtime/v1/@opendatacapture/runtime-core';
593
+
594
+ addNotification({
595
+ type: 'success', // 'error' | 'info' | 'success' | 'warning'
596
+ title: 'Saved',
597
+ message: 'Your response was recorded.',
598
+ variant: 'standard' // 'critical' | 'standard'
599
+ });
600
+ ```
601
+
602
+ - **Translators** — `Translator`, `StandaloneTranslator`, and `SynchronizedTranslator` provide message translation for multilingual interactive instruments. Construct with `{ translations, fallbackLanguage? }`, then `init()`, read `resolvedLanguage`, switch with `changeLanguage(lang)`, and resolve keys with `t(key)`:
603
+
604
+ ```ts
605
+ import { Translator } from '/runtime/v1/@opendatacapture/runtime-core';
606
+
607
+ const translator = new Translator({
608
+ fallbackLanguage: 'en',
609
+ translations: { greeting: { en: 'Hello', fr: 'Bonjour' } }
610
+ });
611
+ translator.init();
612
+ translator.t('greeting');
613
+ ```
614
+
615
+ - **`asSnakeCase(obj)`** — returns a copy of `obj` with its keys converted to snake_case.
616
+
617
+ ## 4. File Structure
618
+
619
+ ### 4.1 Entrypoint
620
+
621
+ The bundler identifies the instrument entrypoint by searching for (in order):
622
+
623
+ 1. `index.tsx`
624
+ 2. `index.jsx`
625
+ 3. `index.ts`
626
+ 4. `index.js`
627
+
628
+ The entrypoint must have a **default export** of the instrument object (returned by `defineInstrument` or `defineSeriesInstrument`).
629
+
630
+ ### 4.2 Import Types
631
+
632
+ - **Runtime imports** (use URL format): `import { z } from '/runtime/v1/zod@3.x'`
633
+ - Resolved by the ODC runtime.
634
+ - **Relative imports**: `import { helper } from './helper.ts'`
635
+ - Must exist within the instrument's file set; bundled into the output.
636
+ - **CSS imports**: `import './styles.css'`
637
+ - Bundled and automatically injected into the iframe head before `render` is called.
638
+ - **Image/asset imports**: `import logoSrc from './logo.png'`
639
+ - Bundled as base64 data URL strings.
640
+ - **HTML imports**: `import html from './index.html'`
641
+ - Bundled as a string.
642
+ - **Legacy script imports**: `import './legacy.js?legacy'`
643
+ - Processed as non-strict mode scripts and automatically injected into the iframe head.
644
+
645
+ ### 4.3 Single-file vs Multi-file
646
+
647
+ For simple instruments, a single `index.ts` file is sufficient. For complex instruments, multiple files may be used:
648
+
649
+ - Split React components into separate `.tsx` files.
650
+ - Separate translation helpers, utility functions, etc.
651
+ - Import CSS, images, HTML, and legacy scripts as needed.
652
+
653
+ ## 14. Complete Examples
654
+
655
+ ### 14.1 Comprehensive Form Instrument Example
656
+
657
+ This example demonstrates: multilingual support, grouped content, all common field types, dynamic fields, cross-field validation, computed measures, and constant measures.
658
+
659
+ ```ts
660
+ import { defineInstrument } from '/runtime/v1/@opendatacapture/runtime-core';
661
+ import { z } from '/runtime/v1/zod@3.x/v4';
662
+
663
+ export default defineInstrument({
664
+ kind: 'FORM',
665
+ language: ['en', 'fr'],
666
+ internal: {
667
+ edition: 1,
668
+ name: 'COMPREHENSIVE_FORM_EXAMPLE'
669
+ },
670
+ tags: {
671
+ en: ['Demo', 'Reference'],
672
+ fr: ['Démo', 'Référence']
673
+ },
674
+ details: {
675
+ title: { en: 'Comprehensive Form Example', fr: 'Exemple de formulaire complet' },
676
+ description: {
677
+ en: 'Demonstrates every form field type and common patterns.',
678
+ fr: 'Démontre chaque type de champ et les modèles courants.'
679
+ },
680
+ license: 'Apache-2.0',
681
+ authors: ['Example Author']
682
+ },
683
+ clientDetails: {
684
+ estimatedDuration: 10,
685
+ instructions: {
686
+ en: ['Please answer all required questions.', 'Conditional questions will appear based on your answers.'],
687
+ fr: [
688
+ 'Veuillez répondre à toutes les questions obligatoires.',
689
+ 'Des questions conditionnelles apparaîtront selon vos réponses.'
690
+ ]
691
+ }
692
+ },
693
+ content: [
694
+ {
695
+ title: { en: 'Basic Fields', fr: 'Champs de base' },
696
+ description: {
697
+ en: 'All basic scalar field types',
698
+ fr: 'Tous les types de champs scalaires de base'
699
+ },
700
+ fields: {
701
+ agreedToTerms: {
702
+ kind: 'boolean',
703
+ label: { en: 'I agree to the terms', fr: "J'accepte les conditions" },
704
+ variant: 'checkbox'
705
+ },
706
+ currentlyEmployed: {
707
+ kind: 'boolean',
708
+ label: { en: 'Are you currently employed?', fr: 'Êtes-vous actuellement employé(e)?' },
709
+ variant: 'radio',
710
+ options: {
711
+ en: { true: 'Yes', false: 'No' },
712
+ fr: { true: 'Oui', false: 'Non' }
713
+ }
714
+ },
715
+ dateOfBirth: {
716
+ kind: 'date',
717
+ label: { en: 'Date of Birth', fr: 'Date de naissance' }
718
+ },
719
+ overallHappiness: {
720
+ kind: 'number',
721
+ label: { en: 'Overall Happiness', fr: 'Bonheur général' },
722
+ description: {
723
+ en: 'Rate from 1 (very unhappy) to 10 (very happy)',
724
+ fr: 'Évaluez de 1 (très malheureux) à 10 (très heureux)'
725
+ },
726
+ variant: 'slider',
727
+ min: 1,
728
+ max: 10
729
+ },
730
+ educationLevel: {
731
+ kind: 'number',
732
+ label: { en: 'Education Level', fr: "Niveau d'études" },
733
+ variant: 'select',
734
+ options: {
735
+ en: { 1: 'Primary', 2: 'Secondary', 3: 'Post-secondary' },
736
+ fr: { 1: 'Primaire', 2: 'Secondaire', 3: 'Postsecondaire' }
737
+ }
738
+ },
739
+ firstName: {
740
+ kind: 'string',
741
+ label: { en: 'First Name', fr: 'Prénom' },
742
+ variant: 'input'
743
+ },
744
+ preferredLanguage: {
745
+ kind: 'string',
746
+ label: { en: 'Preferred Language', fr: 'Langue préférée' },
747
+ variant: 'radio',
748
+ options: {
749
+ en: { en: 'English', fr: 'French' },
750
+ fr: { en: 'Anglais', fr: 'Français' }
751
+ }
752
+ },
753
+ additionalComments: {
754
+ kind: 'string',
755
+ label: { en: 'Additional Comments', fr: 'Commentaires supplémentaires' },
756
+ variant: 'textarea'
757
+ },
758
+ preferredActivities: {
759
+ kind: 'set',
760
+ label: { en: 'Preferred Activities', fr: 'Activités préférées' },
761
+ variant: 'listbox',
762
+ options: {
763
+ en: { reading: 'Reading', sports: 'Sports', cooking: 'Cooking' },
764
+ fr: { reading: 'Lecture', sports: 'Sports', cooking: 'Cuisine' }
765
+ }
766
+ }
767
+ }
768
+ },
769
+ {
770
+ title: { en: 'Composite Fields', fr: 'Champs composites' },
771
+ fields: {
772
+ weeklyMoodRatings: {
773
+ kind: 'number-record',
774
+ label: { en: 'Weekly Mood Ratings', fr: "Évaluations d'humeur hebdomadaires" },
775
+ variant: 'likert',
776
+ items: {
777
+ monday: { label: { en: 'Monday', fr: 'Lundi' } },
778
+ wednesday: { label: { en: 'Wednesday', fr: 'Mercredi' } },
779
+ friday: { label: { en: 'Friday', fr: 'Vendredi' } }
780
+ },
781
+ options: {
782
+ en: { 1: 'Poor', 2: 'Fair', 3: 'Good', 4: 'Excellent' },
783
+ fr: { 1: 'Mauvaise', 2: 'Passable', 3: 'Bonne', 4: 'Excellente' }
784
+ }
785
+ },
786
+ medications: {
787
+ kind: 'record-array',
788
+ label: { en: 'Current Medications', fr: 'Médicaments actuels' },
789
+ fieldset: {
790
+ medicationName: {
791
+ kind: 'string',
792
+ label: { en: 'Medication Name', fr: 'Nom du médicament' },
793
+ variant: 'input'
794
+ },
795
+ dosageMg: {
796
+ kind: 'number',
797
+ label: { en: 'Dosage (mg)', fr: 'Dosage (mg)' },
798
+ variant: 'input'
799
+ }
800
+ }
801
+ }
802
+ }
803
+ },
804
+ {
805
+ title: { en: 'Conditional Questions', fr: 'Questions conditionnelles' },
806
+ fields: {
807
+ hasChronicCondition: {
808
+ kind: 'boolean',
809
+ label: { en: 'Do you have a chronic condition?', fr: 'Avez-vous une maladie chronique?' },
810
+ variant: 'radio',
811
+ options: {
812
+ en: { true: 'Yes', false: 'No' },
813
+ fr: { true: 'Oui', false: 'Non' }
814
+ }
815
+ },
816
+ chronicConditionName: {
817
+ kind: 'dynamic',
818
+ deps: ['hasChronicCondition'],
819
+ render(data) {
820
+ if (!data?.hasChronicCondition) {
821
+ return null;
822
+ }
823
+ return {
824
+ kind: 'string',
825
+ label: { en: 'Condition Name', fr: 'Nom de la condition' },
826
+ variant: 'input',
827
+ isRequired: true
828
+ };
829
+ }
830
+ }
831
+ }
832
+ }
833
+ ],
834
+ measures: {
835
+ overallHappiness: {
836
+ kind: 'const',
837
+ ref: 'overallHappiness',
838
+ label: { en: 'Overall Happiness', fr: 'Bonheur général' },
839
+ visibility: 'visible'
840
+ },
841
+ educationLevel: {
842
+ kind: 'const',
843
+ ref: 'educationLevel'
844
+ },
845
+ happinessCategory: {
846
+ kind: 'computed',
847
+ label: { en: 'Happiness Category', fr: 'Catégorie de bonheur' },
848
+ value(data) {
849
+ if (data.overallHappiness <= 3) return 'Low';
850
+ if (data.overallHappiness <= 6) return 'Moderate';
851
+ return 'High';
852
+ },
853
+ visibility: 'visible'
854
+ }
855
+ },
856
+ defaultMeasureVisibility: 'hidden',
857
+ validationSchema: z
858
+ .object({
859
+ agreedToTerms: z.boolean(),
860
+ currentlyEmployed: z.boolean(),
861
+ dateOfBirth: z.date(),
862
+ overallHappiness: z.number().int().min(1).max(10),
863
+ educationLevel: z.union([z.literal(1), z.literal(2), z.literal(3)]),
864
+ firstName: z.string(),
865
+ preferredLanguage: z.enum(['en', 'fr']),
866
+ additionalComments: z.string().optional(),
867
+ preferredActivities: z.set(z.enum(['reading', 'sports', 'cooking'])),
868
+ weeklyMoodRatings: z.record(
869
+ z.enum(['monday', 'wednesday', 'friday']),
870
+ z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)])
871
+ ),
872
+ medications: z.array(
873
+ z.object({
874
+ medicationName: z.string(),
875
+ dosageMg: z.number()
876
+ })
877
+ ),
878
+ hasChronicCondition: z.boolean(),
879
+ chronicConditionName: z.string().optional()
880
+ })
881
+ .superRefine((data, ctx) => {
882
+ if (data.hasChronicCondition && !data.chronicConditionName) {
883
+ ctx.addIssue({
884
+ code: 'custom',
885
+ path: ['chronicConditionName'],
886
+ message: 'This field is required / Ce champ est obligatoire.'
887
+ });
888
+ }
889
+ })
890
+ });
891
+ ```
892
+
893
+ ---
894
+
895
+ ### 14.2 Comprehensive Interactive Instrument Example
896
+
897
+ This example demonstrates an interactive instrument.
898
+
899
+ ```ts
900
+ import { defineInstrument } from '/runtime/v1/@opendatacapture/runtime-core';
901
+ import { z } from '/runtime/v1/zod@3.x/v4';
902
+
903
+ export default defineInstrument({
904
+ kind: 'INTERACTIVE',
905
+ language: 'en',
906
+ tags: ['<PLACEHOLDER>'],
907
+ internal: {
908
+ edition: 1,
909
+ name: '<PLACEHOLDER>'
910
+ },
911
+ content: {
912
+ render(done) {
913
+ const button = document.createElement('button');
914
+ button.textContent = 'Submit Instrument';
915
+ document.body.appendChild(button);
916
+ button.addEventListener('click', () => {
917
+ done({ message: 'Hello World' });
918
+ });
919
+ }
920
+ },
921
+ clientDetails: {
922
+ estimatedDuration: 1,
923
+ instructions: ['<PLACEHOLDER>']
924
+ },
925
+ details: {
926
+ description: '<PLACEHOLDER>',
927
+ license: 'Apache-2.0',
928
+ title: '<PLACEHOLDER>'
929
+ },
930
+ measures: {},
931
+ validationSchema: z.object({
932
+ message: z.string()
933
+ })
934
+ });
935
+ ```
package/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # @opendatacapture/instrument-guidelines
2
+
3
+ Guidelines for authoring [Open Data Capture](https://opendatacapture.org) instruments,
4
+ written to be read by an AI agent (e.g. Claude Code). Install this package and link the
5
+ guidelines into your project, then point your agent at the resulting file — it will read
6
+ the full instrument specification and author instruments accordingly.
7
+
8
+ ## Usage
9
+
10
+ Install as a dev dependency:
11
+
12
+ ```bash
13
+ npm install -D @opendatacapture/instrument-guidelines
14
+ ```
15
+
16
+ Link the guidelines into your project root:
17
+
18
+ ```bash
19
+ npx instrument-guidelines
20
+ ```
21
+
22
+ This creates an `AGENTS.md` symlink pointing at the installed guidelines, so it always
23
+ reflects the version you have installed — updating the package updates the guidelines.
24
+
25
+ ### Options
26
+
27
+ | Option | Description |
28
+ | --------------- | ------------------------------------------------------------- |
29
+ | `--file <name>` | Target filename to create (default: `AGENTS.md`). Repeatable. |
30
+ | `--copy` | Copy the guidelines instead of symlinking them. |
31
+ | `--force` | Overwrite existing target file(s). |
32
+ | `-h`, `--help` | Show help. |
33
+
34
+ Create both `AGENTS.md` and a `CLAUDE.md` (which Claude Code auto-loads):
35
+
36
+ ```bash
37
+ npx instrument-guidelines --file AGENTS.md --file CLAUDE.md
38
+ ```
39
+
40
+ > **Note:** Install the package first (as above) so the symlink targets the stable copy
41
+ > in `node_modules`. For a one-off run via `npx` without installing, use `--copy`, since
42
+ > the ephemeral install location would otherwise leave a dangling link.
43
+
44
+ ## Pointing your agent at it
45
+
46
+ Once a `CLAUDE.md` (or `AGENTS.md`) exists at your project root, start Claude Code in that
47
+ directory — it reads the guidelines automatically. No further setup is required to begin
48
+ authoring instruments.
package/bin/cli.mjs ADDED
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { parseArgs } from 'node:util';
7
+
8
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
9
+ const source = path.join(packageRoot, 'AGENTS.md');
10
+
11
+ const HELP = `Usage: instrument-guidelines [options]
12
+
13
+ Links the Open Data Capture instrument-authoring guidelines into the current
14
+ directory so an agent (e.g. Claude Code) can read them.
15
+
16
+ Options:
17
+ --file <name> Target filename to create (default: AGENTS.md). Repeatable,
18
+ e.g. --file AGENTS.md --file CLAUDE.md to create both.
19
+ --copy Copy the guidelines instead of symlinking them.
20
+ --force Overwrite existing target file(s).
21
+ -h, --help Show this help.
22
+ `;
23
+
24
+ function fail(message) {
25
+ process.stderr.write(`error: ${message}\n`);
26
+ process.exit(1);
27
+ }
28
+
29
+ let parsed;
30
+ try {
31
+ parsed = parseArgs({
32
+ options: {
33
+ copy: { default: false, type: 'boolean' },
34
+ file: { multiple: true, type: 'string' },
35
+ force: { default: false, type: 'boolean' },
36
+ help: { default: false, short: 'h', type: 'boolean' }
37
+ }
38
+ });
39
+ } catch (err) {
40
+ fail(err.message);
41
+ }
42
+
43
+ const { copy, file, force, help } = parsed.values;
44
+
45
+ if (help) {
46
+ process.stdout.write(HELP);
47
+ process.exit(0);
48
+ }
49
+
50
+ if (!fs.existsSync(source)) {
51
+ fail(`could not find guidelines at ${source}`);
52
+ }
53
+
54
+ const targets = file && file.length > 0 ? file : ['AGENTS.md'];
55
+ const cwd = process.cwd();
56
+
57
+ for (const name of targets) {
58
+ const target = path.resolve(cwd, name);
59
+
60
+ if (fs.lstatSync(target, { throwIfNoEntry: false })) {
61
+ if (!force) {
62
+ process.stdout.write(`skipped ${name} (already exists; pass --force to overwrite)\n`);
63
+ continue;
64
+ }
65
+ fs.rmSync(target, { force: true });
66
+ }
67
+
68
+ if (copy) {
69
+ fs.copyFileSync(source, target);
70
+ process.stdout.write(`copied ${name}\n`);
71
+ continue;
72
+ }
73
+
74
+ const linkTarget = path.relative(path.dirname(target), source);
75
+ try {
76
+ fs.symlinkSync(linkTarget, target);
77
+ process.stdout.write(`linked ${name} -> ${linkTarget}\n`);
78
+ } catch (err) {
79
+ if (err.code === 'EPERM') {
80
+ fail(`cannot create symlink (${err.code}); re-run with --copy instead`);
81
+ }
82
+ fail(err.message);
83
+ }
84
+ }
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@opendatacapture/instrument-guidelines",
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "description": "Guidelines for authoring Open Data Capture instruments, intended to be read by an AI agent (e.g. Claude Code).",
6
+ "keywords": [
7
+ "opendatacapture",
8
+ "instrument",
9
+ "agent",
10
+ "guidelines",
11
+ "claude"
12
+ ],
13
+ "license": "Apache-2.0",
14
+ "bin": {
15
+ "instrument-guidelines": "./bin/cli.mjs"
16
+ },
17
+ "files": [
18
+ "bin",
19
+ "AGENTS.md"
20
+ ],
21
+ "exports": {
22
+ "./AGENTS.md": "./AGENTS.md",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "scripts": {
26
+ "format": "prettier --write bin",
27
+ "lint": "eslint --fix bin"
28
+ }
29
+ }