simpler-forms 0.1.0-alpha.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +300 -76
  2. package/dist/src/casing.d.ts +43 -0
  3. package/dist/src/casing.js +146 -0
  4. package/dist/src/casing.js.map +1 -0
  5. package/dist/src/decorators/index.d.ts +1 -0
  6. package/dist/src/decorators/index.js +1 -0
  7. package/dist/src/decorators/index.js.map +1 -1
  8. package/dist/src/decorators/mapping.d.ts +17 -0
  9. package/dist/src/decorators/mapping.js +122 -0
  10. package/dist/src/decorators/mapping.js.map +1 -0
  11. package/dist/src/decorators/meta.d.ts +15 -5
  12. package/dist/src/decorators/meta.js +31 -4
  13. package/dist/src/decorators/meta.js.map +1 -1
  14. package/dist/src/decorators/shared.d.ts +2 -2
  15. package/dist/src/decorators/shared.js.map +1 -1
  16. package/dist/src/decorators/ui.d.ts +14 -12
  17. package/dist/src/decorators/ui.js +20 -43
  18. package/dist/src/decorators/ui.js.map +1 -1
  19. package/dist/src/emitter.d.ts +8 -0
  20. package/dist/src/emitter.js +55 -16
  21. package/dist/src/emitter.js.map +1 -1
  22. package/dist/src/emitters/block-ui.d.ts +14 -3
  23. package/dist/src/emitters/block-ui.js +81 -119
  24. package/dist/src/emitters/block-ui.js.map +1 -1
  25. package/dist/src/emitters/layout-ui.d.ts +12 -0
  26. package/dist/src/emitters/layout-ui.js +225 -0
  27. package/dist/src/emitters/layout-ui.js.map +1 -0
  28. package/dist/src/emitters/overlay.d.ts +10 -8
  29. package/dist/src/emitters/overlay.js +30 -105
  30. package/dist/src/emitters/overlay.js.map +1 -1
  31. package/dist/src/forms.d.ts +23 -0
  32. package/dist/src/forms.js +54 -0
  33. package/dist/src/forms.js.map +1 -0
  34. package/dist/src/index.d.ts +22 -8
  35. package/dist/src/index.js +17 -3
  36. package/dist/src/index.js.map +1 -1
  37. package/dist/src/layout.d.ts +50 -0
  38. package/dist/src/layout.js +397 -0
  39. package/dist/src/layout.js.map +1 -0
  40. package/dist/src/lib.d.ts +585 -39
  41. package/dist/src/lib.js +258 -15
  42. package/dist/src/lib.js.map +1 -1
  43. package/dist/src/linter.js +8 -43
  44. package/dist/src/linter.js.map +1 -1
  45. package/dist/src/mapping-from.d.ts +21 -0
  46. package/dist/src/mapping-from.js +169 -0
  47. package/dist/src/mapping-from.js.map +1 -0
  48. package/dist/src/mapping.d.ts +65 -0
  49. package/dist/src/mapping.js +209 -0
  50. package/dist/src/mapping.js.map +1 -0
  51. package/dist/src/model.d.ts +143 -23
  52. package/dist/src/model.js +108 -21
  53. package/dist/src/model.js.map +1 -1
  54. package/dist/src/public.d.ts +20 -4
  55. package/dist/src/public.js +28 -4
  56. package/dist/src/public.js.map +1 -1
  57. package/dist/src/validate.d.ts +2 -1
  58. package/dist/src/validate.js +208 -58
  59. package/dist/src/validate.js.map +1 -1
  60. package/lib/main.tsp +1 -0
  61. package/lib/mapping.tsp +173 -0
  62. package/lib/meta.tsp +25 -6
  63. package/lib/types.tsp +24 -63
  64. package/lib/ui.tsp +34 -17
  65. package/package.json +17 -11
  66. package/src/casing.ts +172 -0
  67. package/src/decorators/index.ts +1 -0
  68. package/src/decorators/mapping.ts +200 -0
  69. package/src/decorators/meta.ts +56 -13
  70. package/src/decorators/shared.ts +6 -1
  71. package/src/decorators/ui.ts +43 -59
  72. package/src/emitter.ts +76 -16
  73. package/src/emitters/block-ui.ts +83 -135
  74. package/src/emitters/layout-ui.ts +280 -0
  75. package/src/emitters/overlay.ts +43 -116
  76. package/src/forms.ts +82 -0
  77. package/src/index.ts +17 -3
  78. package/src/layout.ts +592 -0
  79. package/src/lib.ts +264 -15
  80. package/src/linter.ts +17 -49
  81. package/src/mapping-from.ts +216 -0
  82. package/src/mapping.ts +358 -0
  83. package/src/model.ts +287 -46
  84. package/src/public.ts +60 -6
  85. package/src/validate.ts +221 -60
  86. package/dist/src/emitters/override-condition.d.ts +0 -12
  87. package/dist/src/emitters/override-condition.js +0 -25
  88. package/dist/src/emitters/override-condition.js.map +0 -1
  89. package/src/emitters/override-condition.ts +0 -37
@@ -1,26 +1,68 @@
1
- import type { Model, ModelProperty, Scalar } from "@typespec/compiler";
1
+ import type {
2
+ Enum,
3
+ EnumMember,
4
+ Model,
5
+ ModelProperty,
6
+ Namespace,
7
+ Scalar,
8
+ } from "@typespec/compiler";
2
9
  import { stateKeys } from "../lib.js";
3
- import { type Ctx, enumName, plain, publishAs, set } from "./shared.js";
10
+ import { type Ctx, enumName, plain, publishAs, set, unwrap } from "./shared.js";
11
+
12
+ /** The name a declared enum member is emitted under: its string value, or its name. */
13
+ const memberName = (member: EnumMember) =>
14
+ typeof member.value === "string" ? member.value : member.name;
4
15
 
5
16
  /**
6
17
  * `@Meta.question`: the question's stable identity, the entity it is asked about, and
7
18
  * its classification. Also establishes the JSON Schema `$id`, so this is what makes a
8
19
  * model a question rather than an ordinary model.
20
+ *
21
+ * The entity is recorded as its name now and as the member itself for `$onValidate`, which
22
+ * checks it against the declared sets once every `@Meta.entities` has run.
9
23
  */
10
- export const $question = (ctx: Ctx, target: Model | Scalar, meta: unknown) => {
24
+ export const $question = (
25
+ ctx: Ctx,
26
+ target: Model | Scalar | Enum,
27
+ meta: unknown,
28
+ ) => {
11
29
  const m = plain(ctx, meta) as {
12
30
  id: string;
13
31
  entity?: unknown;
14
32
  classification?: unknown;
15
33
  };
16
- if (m.entity !== undefined) m.entity = enumName(m.entity);
34
+ const entity = entityMember(meta);
35
+ if (entity) {
36
+ m.entity = memberName(entity);
37
+ set(ctx, stateKeys.entity, target, m.entity);
38
+ set(ctx, stateKeys.entityMember, target, entity);
39
+ } else if (m.entity !== undefined) {
40
+ m.entity = enumName(m.entity);
41
+ }
17
42
  if (m.classification !== undefined)
18
43
  m.classification = enumName(m.classification);
19
44
  set(ctx, stateKeys.questionMeta, target, m);
20
45
  publishAs(ctx, target, m.id);
21
46
  };
22
47
 
23
- /** `@Meta.form`: the form's identity and the provenance of the paper form it mirrors. */
48
+ /** The enum member a question meta's `entity` names, read before it is made plain. */
49
+ function entityMember(meta: unknown): EnumMember | undefined {
50
+ const member = unwrap((meta as { entity?: unknown })?.entity) as any;
51
+ return member?.kind === "EnumMember" ? (member as EnumMember) : undefined;
52
+ }
53
+
54
+ /** `@Meta.tags`: the tags the program catalogues its questions by. */
55
+ export const $tags = (ctx: Ctx, target: Namespace, tags: Enum) =>
56
+ set(ctx, stateKeys.tagSets, target, tags);
57
+
58
+ /** `@Meta.entities`: the entities the program's questions are asked about. */
59
+ export const $entities = (ctx: Ctx, target: Namespace, entities: Enum) =>
60
+ set(ctx, stateKeys.entitySets, target, entities);
61
+
62
+ /**
63
+ * `@Meta.form`: a form an applicant opens, and the data it submits. Publishes the model's
64
+ * JSON Schema, as `@Meta.question` does, so a form is a block.
65
+ */
24
66
  export const $form = (ctx: Ctx, target: Model, meta: unknown) => {
25
67
  const m = plain(ctx, meta) as { id: string };
26
68
  set(ctx, stateKeys.formMeta, target, m);
@@ -32,13 +74,14 @@ export const $form = (ctx: Ctx, target: Model, meta: unknown) => {
32
74
  * constrained scalar with no question identity, so it stays a decorator of its own
33
75
  * rather than a field of the question meta.
34
76
  */
35
- export const $tag = (ctx: Ctx, target: Model | Scalar, ...tags: unknown[]) =>
36
- set(
37
- ctx,
38
- stateKeys.tags,
39
- target,
40
- tags.map((t) => enumName(t)),
41
- );
77
+ export const $tag = (
78
+ ctx: Ctx,
79
+ target: Model | Scalar | Enum,
80
+ ...tags: EnumMember[]
81
+ ) => {
82
+ set(ctx, stateKeys.tags, target, tags.map(memberName));
83
+ set(ctx, stateKeys.tagMembers, target, tags);
84
+ };
42
85
 
43
86
  /**
44
87
  * `@Meta.role`: why a field exists in a response -- applicant input, calculated output,
@@ -47,6 +90,6 @@ export const $tag = (ctx: Ctx, target: Model | Scalar, ...tags: unknown[]) =>
47
90
  */
48
91
  export const $role = (
49
92
  ctx: Ctx,
50
- target: Model | Scalar | ModelProperty,
93
+ target: Model | Scalar | Enum | ModelProperty,
51
94
  role: unknown,
52
95
  ) => set(ctx, stateKeys.responseRole, target, enumName(role));
@@ -1,5 +1,6 @@
1
1
  import type {
2
2
  DecoratorContext,
3
+ Enum,
3
4
  Model,
4
5
  ModelProperty,
5
6
  Scalar,
@@ -74,7 +75,11 @@ export const blockSchemaRef = (id: string) => `${id}/schema.json`;
74
75
  * Delegate to the stock JSON Schema library, which resolves this relative id
75
76
  * against the namespace base and uses it for both `$id` and every `$ref` target.
76
77
  */
77
- export function publishAs(ctx: Ctx, target: Model | Scalar, id: string): void {
78
+ export function publishAs(
79
+ ctx: Ctx,
80
+ target: Model | Scalar | Enum,
81
+ id: string,
82
+ ): void {
78
83
  $jsonSchemaId(ctx as any, target as any, blockSchemaRef(id));
79
84
  }
80
85
 
@@ -1,11 +1,17 @@
1
- import type { Enum, Model, ModelProperty, Scalar } from "@typespec/compiler";
1
+ import type {
2
+ Enum,
3
+ EnumMember,
4
+ Model,
5
+ ModelProperty,
6
+ Namespace,
7
+ Scalar,
8
+ } from "@typespec/compiler";
2
9
  import { $summary } from "@typespec/compiler";
3
10
  import { stateKeys } from "../lib.js";
4
11
  import {
5
12
  type Ctx,
6
13
  condition,
7
14
  countCondition,
8
- enumName,
9
15
  literal,
10
16
  negatedCondition,
11
17
  plain,
@@ -13,64 +19,24 @@ import {
13
19
  set,
14
20
  } from "./shared.js";
15
21
 
16
- // --- sections -------------------------------------------------------------
22
+ // --- layouts --------------------------------------------------------------
17
23
 
18
- export const $sections = (ctx: Ctx, target: Model, sections: Enum) =>
19
- set(ctx, stateKeys.sections, target, sections);
24
+ export const $layout = (ctx: Ctx, target: Model, form: Model) =>
25
+ set(ctx, stateKeys.layout, target, form);
20
26
 
21
27
  /**
22
- * `valueof EnumMember` arrives as a value, not the member type, so resolve the
23
- * member's name and label here rather than in the emitters.
28
+ * Records the argument's syntax as well as the property it resolves to. A reference to a
29
+ * nested occurrence (`Form.payee::type.address`) resolves to the declaration, so the
30
+ * syntax is the only place the occurrence's path survives.
24
31
  */
25
- export const $section = (ctx: Ctx, target: ModelProperty, section: unknown) =>
26
- set(ctx, stateKeys.section, target, sectionRef(section));
27
-
28
- export function sectionRef(v: unknown): { name: string; label?: string } {
29
- const m = v as any;
30
- if (m && typeof m === "object") {
31
- if (m.name)
32
- return {
33
- name: String(m.name),
34
- label: m.value ? String(m.value) : undefined,
35
- };
36
- if (m.value?.name) {
37
- return {
38
- name: String(m.value.name),
39
- label: m.value.value ? String(m.value.value) : undefined,
40
- };
41
- }
42
- }
43
- return { name: String(v) };
44
- }
45
-
46
- // --- form-scoped overrides ------------------------------------------------
47
-
48
- function overridePlain(value: unknown): unknown {
49
- const candidate = value as any;
50
- if (
51
- candidate &&
52
- typeof candidate === "object" &&
53
- candidate.entityKind === "Value"
54
- ) {
55
- return literal(candidate);
56
- }
57
- if (Array.isArray(value)) return value.map(overridePlain);
58
- if (value && typeof value === "object") {
59
- return Object.fromEntries(
60
- Object.entries(value).map(([key, nested]) => [
61
- key,
62
- overridePlain(nested),
63
- ]),
64
- );
65
- }
66
- return value;
67
- }
68
-
69
- export const $overrides = (
70
- ctx: Ctx,
71
- target: Model | ModelProperty,
72
- patch: unknown,
73
- ) => set(ctx, stateKeys.overrides, target, overridePlain(plain(ctx, patch)));
32
+ export const $field = (ctx: Ctx, target: ModelProperty, field: ModelProperty) =>
33
+ set(ctx, stateKeys.layoutField, target, {
34
+ field,
35
+ node: ctx.getArgumentTarget(0),
36
+ });
37
+
38
+ export const $flatten = (ctx: Ctx, target: ModelProperty) =>
39
+ set(ctx, stateKeys.flatten, target, true);
74
40
 
75
41
  // --- presentation ---------------------------------------------------------
76
42
 
@@ -81,7 +47,7 @@ export const $overrides = (
81
47
  */
82
48
  export const $label = (
83
49
  ctx: Ctx,
84
- target: Model | Scalar | ModelProperty,
50
+ target: Model | Scalar | Enum | ModelProperty,
85
51
  text: string,
86
52
  ) => {
87
53
  set(ctx, stateKeys.label, target, text);
@@ -95,8 +61,26 @@ export const $label = (
95
61
  export const $helpText = (ctx: Ctx, target: ModelProperty, text: string) =>
96
62
  set(ctx, stateKeys.helpText, target, text);
97
63
 
98
- export const $widget = (ctx: Ctx, target: ModelProperty, widget: unknown) =>
99
- set(ctx, stateKeys.widget, target, enumName(widget));
64
+ export const $widgets = (ctx: Ctx, target: Namespace, widgets: Enum) =>
65
+ set(ctx, stateKeys.widgets, target, widgets);
66
+
67
+ /**
68
+ * Records the emitted name now and the member itself for `$onValidate`, which checks it
69
+ * against the declared sets once every `@UI.widgets` has run.
70
+ */
71
+ export const $widget = (
72
+ ctx: Ctx,
73
+ target: ModelProperty | Scalar | Model,
74
+ widget: EnumMember,
75
+ ) => {
76
+ set(
77
+ ctx,
78
+ stateKeys.widget,
79
+ target,
80
+ typeof widget.value === "string" ? widget.value : widget.name,
81
+ );
82
+ set(ctx, stateKeys.widgetMember, target, widget);
83
+ };
100
84
 
101
85
  export const $encodedCheckboxGroup = (
102
86
  ctx: Ctx,
package/src/emitter.ts CHANGED
@@ -11,11 +11,19 @@ import {
11
11
  getId,
12
12
  } from "@typespec/json-schema";
13
13
  import { allBlocks, type Block } from "./model.js";
14
+ import { type PublishedForm, resolveForms } from "./forms.js";
14
15
  import { reportDiagnostic } from "./lib.js";
15
16
  import { blockSchemaRef } from "./decorators/index.js";
16
- import { emitModelOverlay, emitSchemaOverlay } from "./emitters/overlay.js";
17
+ import {
18
+ emitModelOverlay,
19
+ emitSchemaOverlay,
20
+ type OwnsDefinition,
21
+ } from "./emitters/overlay.js";
17
22
  import { emitBlockUi } from "./emitters/block-ui.js";
23
+ import { emitLayoutUi } from "./emitters/layout-ui.js";
24
+ import { resolveLayout } from "./layout.js";
18
25
  import { emitBlockIndex } from "./emitters/block-index.js";
26
+ import { Casing, type PropertyCasing } from "./casing.js";
19
27
 
20
28
  export interface FormSpecOptions {
21
29
  /**
@@ -24,6 +32,13 @@ export interface FormSpecOptions {
24
32
  * its `@Meta.question.id`, not its URI.
25
33
  */
26
34
  "base-uri"?: string;
35
+ /**
36
+ * How a property's TypeSpec name is written in every artifact: `preserve` (the default)
37
+ * keeps it, `snake` converts `firstName` to `first_name`. String paths in decorators are
38
+ * still written in TypeSpec names, and `@encodedName("application/json", ...)` overrides
39
+ * the casing for one property.
40
+ */
41
+ "property-casing"?: PropertyCasing;
27
42
  }
28
43
 
29
44
  const STAGING = ".json-schema";
@@ -60,6 +75,9 @@ export async function $onEmit(
60
75
  byFile.set(name, doc);
61
76
  if (doc.$id) byId.set(doc.$id, doc);
62
77
  }
78
+ // The staged schemas are an intermediate in TypeSpec names, not an artifact, so they must
79
+ // not be left beside the published ones.
80
+ await program.host.rm(stagingDir, { recursive: true });
63
81
 
64
82
  const baseUri = context.options?.["base-uri"];
65
83
  const write = (rel: string, value: unknown) =>
@@ -68,8 +86,18 @@ export async function $onEmit(
68
86
  content: JSON.stringify(value, null, 2) + "\n",
69
87
  });
70
88
 
89
+ const casing = new Casing(
90
+ program,
91
+ context.options?.["property-casing"] ?? "preserve",
92
+ );
93
+
71
94
  const blocks = allBlocks(program);
95
+ const { forms } = resolveForms(program);
72
96
  const modelsByName = indexModels(program.getGlobalNamespaceType());
97
+ // A local model with a staged schema of its own is inlined into `$defs` with its overlay
98
+ // (see `resolveRefs`), so the overlays of models that use it don't repeat it.
99
+ const ownsDefinition = (model: Model) =>
100
+ modelsByName.get(model.name) === model && byFile.has(`${model.name}.json`);
73
101
  const refToDir = new Map(
74
102
  blocks.map((b) => [
75
103
  blockSchemaRef(b.id),
@@ -78,6 +106,9 @@ export async function $onEmit(
78
106
  );
79
107
 
80
108
  for (const block of blocks) {
109
+ // A form that cannot be published, such as one with two layouts, writes nothing.
110
+ const form = forms.find((f) => f.model === block.model);
111
+ if (block.kind === "form" && !form) continue;
81
112
  const dir = refToDir.get(blockSchemaRef(block.id))!;
82
113
  const stock = byId.get(resolvedSchemaId(program, block));
83
114
  if (!stock) {
@@ -103,31 +134,51 @@ export async function $onEmit(
103
134
  from: dir,
104
135
  program,
105
136
  modelsByName,
137
+ ownsDefinition,
106
138
  });
107
139
  if (Object.keys(defs).length) schema = { ...schema, $defs: defs };
108
140
 
109
141
  // 4. Fold in the conditional requiredness only we can know about.
110
- const overlay = emitSchemaOverlay(program, block);
142
+ const overlay = emitSchemaOverlay(program, block, ownsDefinition);
111
143
  if (overlay) schema = mergeSchema(schema, overlay);
112
144
 
113
- await write(`${dir}/schema.json`, schema);
114
- await write(`${dir}/ui.json`, emitBlockUi(program, block));
115
- await write(`${dir}/index.json`, emitBlockIndex(program, block));
145
+ const index = emitBlockIndex(program, block);
146
+ if (Array.isArray(index.fieldOccurrences))
147
+ index.fieldOccurrences = index.fieldOccurrences
148
+ .map((entry) => ({ ...entry, path: casing.pointer(entry.path) }))
149
+ .sort((a, b) => a.path.localeCompare(b.path));
116
150
 
117
- if (block.kind === "form") {
118
- await write(`${dir}/manifest.json`, {
119
- contract: "resolved-form-package/v1",
120
- form: block.meta,
121
- artifacts: {
122
- "schema.json": "generated",
123
- "ui.json": "generated",
124
- "index.json": "generated",
125
- },
126
- });
151
+ if (block.kind === "question") {
152
+ await write(`${dir}/schema.json`, casing.json(schema));
153
+ await write(`${dir}/ui.json`, casing.json(emitBlockUi(program, block)));
154
+ await write(`${dir}/index.json`, index);
155
+ continue;
127
156
  }
157
+
158
+ // A form's title is its own, in its manifest; its schema carries none.
159
+ const { title: _title, ...formSchema } = schema;
160
+ await write(`${dir}/schema.json`, casing.json(formSchema));
161
+ await write(`${dir}/ui.json`, casing.json(formUi(program, form!)));
162
+ await write(`${dir}/index.json`, index);
163
+ await write(`${dir}/manifest.json`, {
164
+ contract: "resolved-form-package/v1",
165
+ form: form!.meta,
166
+ artifacts: {
167
+ "schema.json": "generated",
168
+ "ui.json": "generated",
169
+ "index.json": "generated",
170
+ },
171
+ });
128
172
  }
129
173
  }
130
174
 
175
+ /** A form's UI: its layout's, or its own fields' presentation. */
176
+ function formUi(program: Program, form: PublishedForm) {
177
+ return form.layout
178
+ ? emitLayoutUi(program, resolveLayout(program, form.layout, form.model)).ui
179
+ : emitBlockUi(program, form.block);
180
+ }
181
+
131
182
  /**
132
183
  * The `$id` the stock emitter actually wrote for a block.
133
184
  *
@@ -160,6 +211,7 @@ interface RefCtx {
160
211
  from: string;
161
212
  program: EmitContext<FormSpecOptions>["program"];
162
213
  modelsByName: Map<string, Model>;
214
+ ownsDefinition: OwnsDefinition;
163
215
  }
164
216
 
165
217
  /** Rewrite every `$ref`: published blocks keep their identity, others become `$defs`. */
@@ -189,7 +241,11 @@ function resolveRefs(node: any, ctx: RefCtx, seen = new Set<string>()): any {
189
241
  seen.add(name);
190
242
  const { $schema, $id, ...body } = target;
191
243
  const overlay = ctx.modelsByName.has(name)
192
- ? emitModelOverlay(ctx.program, ctx.modelsByName.get(name)!)
244
+ ? emitModelOverlay(
245
+ ctx.program,
246
+ ctx.modelsByName.get(name)!,
247
+ ctx.ownsDefinition,
248
+ )
193
249
  : undefined;
194
250
  ctx.defs[name] = resolveRefs(
195
251
  overlay ? mergeSchema(body, overlay) : body,
@@ -247,6 +303,10 @@ function mergeSchema(a: Json, b: Json): Json {
247
303
  for (const [key, value] of Object.entries(b)) {
248
304
  if (key === "allOf" && Array.isArray(out.allOf)) {
249
305
  out.allOf = [...out.allOf, ...value];
306
+ } else if (key === "required" && Array.isArray(out.required)) {
307
+ // Requiredness only adds: a model-level @Validation.requiredPaths keeps what the model
308
+ // already requires.
309
+ out.required = [...new Set([...out.required, ...value])];
250
310
  } else if (
251
311
  key === "properties" &&
252
312
  isObject(out.properties) &&