@openhi/sdk 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +205 -1
  3. package/astro/OpenhiPreview.astro +59 -0
  4. package/lib/api-base.d.ts +2 -0
  5. package/lib/api-base.js +22 -0
  6. package/lib/astro/index.d.ts +8 -0
  7. package/lib/astro/index.js +8 -0
  8. package/lib/astro/loaders.d.ts +131 -0
  9. package/lib/astro/loaders.js +318 -0
  10. package/lib/content/asset.d.ts +69 -0
  11. package/lib/content/asset.js +151 -0
  12. package/lib/content/blocks/catalogue.d.ts +11 -0
  13. package/lib/content/blocks/catalogue.js +71 -0
  14. package/lib/content/blocks/declare.d.ts +143 -0
  15. package/lib/content/blocks/declare.js +210 -0
  16. package/lib/content/blocks/index.d.ts +2 -0
  17. package/lib/content/blocks/index.js +2 -0
  18. package/lib/content/content-type.d.ts +52 -0
  19. package/lib/content/content-type.js +97 -0
  20. package/lib/content/import-plan.d.ts +56 -0
  21. package/lib/content/import-plan.js +71 -0
  22. package/lib/content/index.d.ts +14 -0
  23. package/lib/content/index.js +14 -0
  24. package/lib/content/page.d.ts +91 -0
  25. package/lib/content/page.js +222 -0
  26. package/lib/content/sanitise-html.d.ts +36 -0
  27. package/lib/content/sanitise-html.js +92 -0
  28. package/lib/content/section.d.ts +60 -0
  29. package/lib/content/section.js +59 -0
  30. package/lib/content/shapes.d.ts +68 -0
  31. package/lib/content/shapes.js +9 -0
  32. package/lib/content/theme.d.ts +25 -0
  33. package/lib/content/theme.js +54 -0
  34. package/lib/content/types.d.ts +142 -0
  35. package/lib/content/types.js +121 -0
  36. package/lib/errors.d.ts +25 -0
  37. package/lib/errors.js +25 -0
  38. package/lib/forms/index.d.ts +107 -0
  39. package/lib/forms/index.js +201 -0
  40. package/lib/index.d.ts +10 -0
  41. package/lib/index.js +9 -0
  42. package/lib/node/bin.d.ts +2 -0
  43. package/lib/node/bin.js +14 -0
  44. package/lib/node/cli/api.d.ts +24 -0
  45. package/lib/node/cli/api.js +62 -0
  46. package/lib/node/cli/check.d.ts +26 -0
  47. package/lib/node/cli/check.js +265 -0
  48. package/lib/node/cli/context.d.ts +37 -0
  49. package/lib/node/cli/context.js +55 -0
  50. package/lib/node/cli/env-check.d.ts +4 -0
  51. package/lib/node/cli/env-check.js +47 -0
  52. package/lib/node/cli/init.d.ts +2 -0
  53. package/lib/node/cli/init.js +171 -0
  54. package/lib/node/cli/load-blocks.d.ts +15 -0
  55. package/lib/node/cli/load-blocks.js +109 -0
  56. package/lib/node/cli/local-content.d.ts +47 -0
  57. package/lib/node/cli/local-content.js +126 -0
  58. package/lib/node/cli/main.d.ts +3 -0
  59. package/lib/node/cli/main.js +58 -0
  60. package/lib/node/cli/optional-tool.d.ts +8 -0
  61. package/lib/node/cli/optional-tool.js +26 -0
  62. package/lib/node/cli/pull.d.ts +2 -0
  63. package/lib/node/cli/pull.js +113 -0
  64. package/lib/node/cli/push.d.ts +6 -0
  65. package/lib/node/cli/push.js +227 -0
  66. package/lib/node/env.d.ts +34 -0
  67. package/lib/node/env.js +66 -0
  68. package/lib/node/index.d.ts +9 -0
  69. package/lib/node/index.js +8 -0
  70. package/lib/node/media.d.ts +56 -0
  71. package/lib/node/media.js +176 -0
  72. package/lib/node/read.d.ts +19 -0
  73. package/lib/node/read.js +55 -0
  74. package/lib/paging.d.ts +14 -0
  75. package/lib/paging.js +41 -0
  76. package/lib/preview/apply-draft.d.ts +42 -0
  77. package/lib/preview/apply-draft.js +185 -0
  78. package/lib/preview/index.d.ts +7 -0
  79. package/lib/preview/index.js +4 -0
  80. package/lib/preview/marks.d.ts +25 -0
  81. package/lib/preview/marks.js +17 -0
  82. package/lib/preview/runtime.d.ts +17 -0
  83. package/lib/preview/runtime.js +85 -0
  84. package/lib/preview/studio-origin.d.ts +3 -0
  85. package/lib/preview/studio-origin.js +38 -0
  86. package/lib/transport.d.ts +25 -0
  87. package/lib/transport.js +58 -0
  88. package/lib/trim-slashes.d.ts +4 -0
  89. package/lib/trim-slashes.js +14 -0
  90. package/package.json +124 -3
@@ -0,0 +1,54 @@
1
+ /**
2
+ * A Theme as CSS variables, for a site that wants them.
3
+ *
4
+ * A theme holds an open list of tokens: `{ name, type, value, dark? }`.
5
+ * Each becomes `--<name>` on `:root` and, when it has a dark value, on the
6
+ * `.dark` selector (or the one asked for). A site that styles itself some
7
+ * other way never calls this.
8
+ */
9
+ const NAME = /^[A-Za-z][A-Za-z0-9_-]*$/;
10
+ /** A value that cannot close its declaration or its rule. */
11
+ const SAFE_VALUE = /^[^;{}<>\\]*$/;
12
+ /** A value that opens a comment, or leaves a quote open to swallow the rest of the sheet. */
13
+ function opensComment(value) {
14
+ return value.includes("/*") || value.includes("*/");
15
+ }
16
+ function balancedQuotes(value) {
17
+ let open;
18
+ for (const char of value) {
19
+ if (open === undefined && (char === '"' || char === "'"))
20
+ open = char;
21
+ else if (char === open)
22
+ open = undefined;
23
+ }
24
+ return open === undefined;
25
+ }
26
+ function declarations(tokens, pick) {
27
+ return tokens
28
+ .flatMap((token) => {
29
+ const value = pick(token);
30
+ // A name or value that could break out of its declaration is dropped:
31
+ // the theme is tenant-authored and this text is put into a stylesheet.
32
+ if (value === undefined ||
33
+ !NAME.test(token.name) ||
34
+ !SAFE_VALUE.test(value) ||
35
+ opensComment(value) ||
36
+ !balancedQuotes(value) ||
37
+ /[\r\n]/.test(value))
38
+ return [];
39
+ return [` --${token.name}: ${value.trim()};`];
40
+ })
41
+ .join("\n");
42
+ }
43
+ /** The stylesheet text for a theme, or an empty string when it has no usable tokens. */
44
+ export function themeTokens(theme, options = {}) {
45
+ const tokens = theme?.token ?? [];
46
+ const light = declarations(tokens, (token) => token.value);
47
+ const dark = declarations(tokens, (token) => token.dark);
48
+ return [
49
+ light.length > 0 ? `${options.light ?? ":root"} {\n${light}\n}` : "",
50
+ dark.length > 0 ? `${options.dark ?? ".dark"} {\n${dark}\n}` : "",
51
+ ]
52
+ .filter((rule) => rule.length > 0)
53
+ .join("\n");
54
+ }
@@ -0,0 +1,142 @@
1
+ import { z } from "zod";
2
+ import type { FormItem, LayoutSection, PageData, Reference, ResourceMeta, ResourceStatus } from "./shapes.js";
3
+ export type { FormItem, LayoutSection, PageData, Reference, ResourceMeta, ResourceStatus, };
4
+ /**
5
+ * The shapes the kit maps between: a site's content files on one side and
6
+ * OpenHI's `Page`, `Section` and `Form` records on the other.
7
+ *
8
+ * These are the kit's defaults and no more. The content model is the
9
+ * site's: it hands its own Zod schemas to `openhiCollections()` and those
10
+ * decide what is valid. What the kit needs of a record is only what the
11
+ * mapping reads, which is what is declared here.
12
+ */
13
+ /** FHIR-like Reference: points at another resource by type/id. */
14
+ export declare const referenceSchema: z.ZodObject<{
15
+ reference: z.ZodString;
16
+ display: z.ZodOptional<z.ZodString>;
17
+ type: z.ZodOptional<z.ZodString>;
18
+ }, z.core.$strip>;
19
+ /** FHIR-like `Resource.meta` subset used by content envelopes. */
20
+ export declare const metaSchema: z.ZodObject<{
21
+ versionId: z.ZodOptional<z.ZodString>;
22
+ lastUpdated: z.ZodOptional<z.ZodString>;
23
+ profile: z.ZodOptional<z.ZodArray<z.ZodString>>;
24
+ }, z.core.$strip>;
25
+ /** What a site distinguishes: rendered or not. OpenHI's `retired` and `draft` are both "not". */
26
+ export declare const resourceStatusSchema: z.ZodEnum<{
27
+ active: "active";
28
+ inactive: "inactive";
29
+ }>;
30
+ /**
31
+ * One block on a page, as the site renders it. `component` is the block's
32
+ * code, a name and not a closed set: content arrives from OpenHI as well
33
+ * as from git, and a block type published there that this build has never
34
+ * heard of must not fail the build.
35
+ */
36
+ export declare const layoutSectionSchema: z.ZodObject<{
37
+ id: z.ZodString;
38
+ identifier: z.ZodString;
39
+ component: z.ZodString;
40
+ data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
41
+ geometry: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
42
+ }, z.core.$strip>;
43
+ export declare const seoSchema: z.ZodObject<{
44
+ metaTitle: z.ZodString;
45
+ metaDescription: z.ZodString;
46
+ ogImage: z.ZodOptional<z.ZodString>;
47
+ ogImageRef: z.ZodOptional<z.ZodObject<{
48
+ reference: z.ZodString;
49
+ display: z.ZodOptional<z.ZodString>;
50
+ type: z.ZodOptional<z.ZodString>;
51
+ }, z.core.$strip>>;
52
+ ogImageAlt: z.ZodOptional<z.ZodString>;
53
+ noindex: z.ZodOptional<z.ZodBoolean>;
54
+ }, z.core.$strip>;
55
+ export declare const pageSchema: z.ZodObject<{
56
+ resourceType: z.ZodLiteral<"Page">;
57
+ id: z.ZodString;
58
+ meta: z.ZodOptional<z.ZodObject<{
59
+ versionId: z.ZodOptional<z.ZodString>;
60
+ lastUpdated: z.ZodOptional<z.ZodString>;
61
+ profile: z.ZodOptional<z.ZodArray<z.ZodString>>;
62
+ }, z.core.$strip>>;
63
+ status: z.ZodDefault<z.ZodEnum<{
64
+ active: "active";
65
+ inactive: "inactive";
66
+ }>>;
67
+ title: z.ZodString;
68
+ intro: z.ZodOptional<z.ZodString>;
69
+ slug: z.ZodString;
70
+ permalink: z.ZodString;
71
+ shell: z.ZodEnum<{
72
+ home: "home";
73
+ page: "page";
74
+ }>;
75
+ cover: z.ZodOptional<z.ZodObject<{
76
+ reference: z.ZodString;
77
+ display: z.ZodOptional<z.ZodString>;
78
+ type: z.ZodOptional<z.ZodString>;
79
+ }, z.core.$strip>>;
80
+ seo: z.ZodOptional<z.ZodObject<{
81
+ metaTitle: z.ZodString;
82
+ metaDescription: z.ZodString;
83
+ ogImage: z.ZodOptional<z.ZodString>;
84
+ ogImageRef: z.ZodOptional<z.ZodObject<{
85
+ reference: z.ZodString;
86
+ display: z.ZodOptional<z.ZodString>;
87
+ type: z.ZodOptional<z.ZodString>;
88
+ }, z.core.$strip>>;
89
+ ogImageAlt: z.ZodOptional<z.ZodString>;
90
+ noindex: z.ZodOptional<z.ZodBoolean>;
91
+ }, z.core.$strip>>;
92
+ layout: z.ZodArray<z.ZodObject<{
93
+ id: z.ZodString;
94
+ identifier: z.ZodString;
95
+ component: z.ZodString;
96
+ data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
97
+ geometry: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
98
+ }, z.core.$strip>>;
99
+ }, z.core.$strip>;
100
+ /** A site-wide piece such as navigation or a footer: a section of the site, not a page of it. */
101
+ export declare const sectionSchema: z.ZodObject<{
102
+ resourceType: z.ZodLiteral<"Section">;
103
+ id: z.ZodString;
104
+ meta: z.ZodOptional<z.ZodObject<{
105
+ versionId: z.ZodOptional<z.ZodString>;
106
+ lastUpdated: z.ZodOptional<z.ZodString>;
107
+ profile: z.ZodOptional<z.ZodArray<z.ZodString>>;
108
+ }, z.core.$strip>>;
109
+ status: z.ZodDefault<z.ZodEnum<{
110
+ active: "active";
111
+ inactive: "inactive";
112
+ }>>;
113
+ slug: z.ZodString;
114
+ data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
115
+ }, z.core.$strip>;
116
+ /** A form item, kept as the API has it: the site draws each by its type. */
117
+ export declare const formItemSchema: z.ZodType<FormItem>;
118
+ /**
119
+ * A form the site renders from content (OpenHI's `Form`): its shape and
120
+ * where its answers go, with the site's own design around it. `id` is the
121
+ * API's record id when the site was built from OpenHI, and absent when
122
+ * built from git alone, in which case the form shows but has nowhere to
123
+ * send answers.
124
+ */
125
+ export declare const formSchema: z.ZodObject<{
126
+ resourceType: z.ZodLiteral<"Form">;
127
+ id: z.ZodOptional<z.ZodString>;
128
+ status: z.ZodDefault<z.ZodString>;
129
+ name: z.ZodString;
130
+ title: z.ZodString;
131
+ description: z.ZodOptional<z.ZodString>;
132
+ confirmation: z.ZodOptional<z.ZodString>;
133
+ item: z.ZodOptional<z.ZodArray<z.ZodType<FormItem, unknown, z.core.$ZodTypeInternals<FormItem, unknown>>>>;
134
+ integration: z.ZodOptional<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
135
+ payment: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
136
+ amount: z.ZodNumber;
137
+ }, z.core.$strip>, z.ZodObject<{
138
+ amountItem: z.ZodString;
139
+ }, z.core.$strip>]>>;
140
+ }, z.core.$strip>;
141
+ export type SectionData = z.infer<typeof sectionSchema>;
142
+ export type FormData = z.infer<typeof formSchema>;
@@ -0,0 +1,121 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * The shapes the kit maps between: a site's content files on one side and
4
+ * OpenHI's `Page`, `Section` and `Form` records on the other.
5
+ *
6
+ * These are the kit's defaults and no more. The content model is the
7
+ * site's: it hands its own Zod schemas to `openhiCollections()` and those
8
+ * decide what is valid. What the kit needs of a record is only what the
9
+ * mapping reads, which is what is declared here.
10
+ */
11
+ /** FHIR-like Reference: points at another resource by type/id. */
12
+ export const referenceSchema = z.object({
13
+ reference: z.string().min(1),
14
+ display: z.string().optional(),
15
+ type: z.string().optional(),
16
+ });
17
+ /** FHIR-like `Resource.meta` subset used by content envelopes. */
18
+ export const metaSchema = z.object({
19
+ versionId: z.string().optional(),
20
+ lastUpdated: z.string().optional(),
21
+ profile: z.array(z.string()).optional(),
22
+ });
23
+ /** What a site distinguishes: rendered or not. OpenHI's `retired` and `draft` are both "not". */
24
+ export const resourceStatusSchema = z.enum(["active", "inactive"]);
25
+ /**
26
+ * One block on a page, as the site renders it. `component` is the block's
27
+ * code, a name and not a closed set: content arrives from OpenHI as well
28
+ * as from git, and a block type published there that this build has never
29
+ * heard of must not fail the build.
30
+ */
31
+ export const layoutSectionSchema = z.object({
32
+ id: z.string(),
33
+ identifier: z.string(),
34
+ component: z.string(),
35
+ data: z.record(z.string(), z.unknown()),
36
+ /** Where the block sits on Studio's canvas (`col`, `row`, `w`, `h`), kept so a push gives it back unchanged. */
37
+ geometry: z.record(z.string(), z.unknown()).optional(),
38
+ });
39
+ export const seoSchema = z.object({
40
+ metaTitle: z.string(),
41
+ metaDescription: z.string(),
42
+ ogImage: z.string().optional(),
43
+ /** Prefer Reference when assets live as `ContentAsset` records. */
44
+ ogImageRef: referenceSchema.optional(),
45
+ ogImageAlt: z.string().optional(),
46
+ noindex: z.boolean().optional(),
47
+ });
48
+ export const pageSchema = z.object({
49
+ resourceType: z.literal("Page"),
50
+ id: z.string(),
51
+ meta: metaSchema.optional(),
52
+ status: resourceStatusSchema.default("active"),
53
+ title: z.string(),
54
+ intro: z.string().optional(),
55
+ slug: z.string(),
56
+ permalink: z.string(),
57
+ shell: z.enum(["home", "page"]),
58
+ cover: referenceSchema.optional(),
59
+ seo: seoSchema.optional(),
60
+ layout: z.array(layoutSectionSchema),
61
+ });
62
+ /** A site-wide piece such as navigation or a footer: a section of the site, not a page of it. */
63
+ export const sectionSchema = z.object({
64
+ resourceType: z.literal("Section"),
65
+ id: z.string(),
66
+ meta: metaSchema.optional(),
67
+ status: resourceStatusSchema.default("active"),
68
+ slug: z.string(),
69
+ data: z.record(z.string(), z.unknown()),
70
+ });
71
+ /** A form item, kept as the API has it: the site draws each by its type. */
72
+ export const formItemSchema = z.lazy(() => z.object({
73
+ linkId: z.string(),
74
+ type: z.string(),
75
+ text: z.string().optional(),
76
+ required: z.boolean().optional(),
77
+ repeats: z.boolean().optional(),
78
+ helpText: z.string().optional(),
79
+ maxLength: z.number().optional(),
80
+ answerOption: z
81
+ .array(z.object({
82
+ value: z.string(),
83
+ label: z.string().optional(),
84
+ initialSelected: z.boolean().optional(),
85
+ }))
86
+ .optional(),
87
+ item: z.array(formItemSchema).optional(),
88
+ }));
89
+ /**
90
+ * A form the site renders from content (OpenHI's `Form`): its shape and
91
+ * where its answers go, with the site's own design around it. `id` is the
92
+ * API's record id when the site was built from OpenHI, and absent when
93
+ * built from git alone, in which case the form shows but has nowhere to
94
+ * send answers.
95
+ */
96
+ export const formSchema = z.object({
97
+ resourceType: z.literal("Form"),
98
+ id: z.string().optional(),
99
+ status: z.string().default("active"),
100
+ name: z.string(),
101
+ title: z.string(),
102
+ description: z.string().optional(),
103
+ confirmation: z.string().optional(),
104
+ item: z.array(formItemSchema).optional(),
105
+ /**
106
+ * What OpenHI does with a response. Read by `push` from git; the loaders
107
+ * remove it before a page is built, because it holds recipients and
108
+ * connection refs.
109
+ */
110
+ integration: z.array(z.record(z.string(), z.unknown())).optional(),
111
+ /**
112
+ * The only part of the form's integrations a built page carries: whether
113
+ * a card is wanted. Recipients and connection refs stay out of the HTML.
114
+ */
115
+ payment: z
116
+ .union([
117
+ z.object({ amount: z.number() }),
118
+ z.object({ amountItem: z.string() }),
119
+ ])
120
+ .optional(),
121
+ });
@@ -0,0 +1,25 @@
1
+ /** The API answered with a refusal or a failure. */
2
+ export declare class OpenhiApiError extends Error {
3
+ /** The HTTP method of the request that failed. */
4
+ readonly method: string;
5
+ /** The request path, without the API base. */
6
+ readonly path: string;
7
+ /** The HTTP status the API answered with. */
8
+ readonly status: number;
9
+ /** The first `diagnostics` of the OperationOutcome the API sent, when it sent one. */
10
+ readonly diagnostics: string | undefined;
11
+ /** The parsed response body, when it was JSON. */
12
+ readonly body: unknown;
13
+ readonly name = "OpenhiApiError";
14
+ constructor(
15
+ /** The HTTP method of the request that failed. */
16
+ method: string,
17
+ /** The request path, without the API base. */
18
+ path: string,
19
+ /** The HTTP status the API answered with. */
20
+ status: number,
21
+ /** The first `diagnostics` of the OperationOutcome the API sent, when it sent one. */
22
+ diagnostics: string | undefined,
23
+ /** The parsed response body, when it was JSON. */
24
+ body: unknown);
25
+ }
package/lib/errors.js ADDED
@@ -0,0 +1,25 @@
1
+ /** The API answered with a refusal or a failure. */
2
+ export class OpenhiApiError extends Error {
3
+ constructor(
4
+ /** The HTTP method of the request that failed. */
5
+ method,
6
+ /** The request path, without the API base. */
7
+ path,
8
+ /** The HTTP status the API answered with. */
9
+ status,
10
+ /** The first `diagnostics` of the OperationOutcome the API sent, when it sent one. */
11
+ diagnostics,
12
+ /** The parsed response body, when it was JSON. */
13
+ body) {
14
+ super(`${method} ${path} → ${status}` +
15
+ (diagnostics !== undefined && diagnostics.length > 0
16
+ ? `: ${diagnostics}`
17
+ : ""));
18
+ this.method = method;
19
+ this.path = path;
20
+ this.status = status;
21
+ this.diagnostics = diagnostics;
22
+ this.body = body;
23
+ this.name = "OpenhiApiError";
24
+ }
25
+ }
@@ -0,0 +1,107 @@
1
+ import type { FormItem } from "../content/shapes.js";
2
+ /**
3
+ * Headless form submission.
4
+ *
5
+ * A `Form` record is the shape: which fields, what type, what is required,
6
+ * what the choices are, and what happens after, email, Slack and a payment.
7
+ * The site is the design: it draws each field itself, and this does the
8
+ * rest — `POST /Form/{id}/$submit`, preview mode and
9
+ * the card step of a payment integration. The SDK draws nothing.
10
+ *
11
+ * Built from git alone the form has no id and nowhere to send answers, so
12
+ * there is no target and `submit()` says so rather than pretending.
13
+ */
14
+ export type FormValues = Record<string, string | string[] | undefined>;
15
+ export interface Answer {
16
+ readonly linkId: string;
17
+ readonly answer: string[];
18
+ }
19
+ /** The answers the API takes, from what the person typed. */
20
+ export declare function answersFrom(items: readonly FormItem[] | undefined, values: FormValues): Answer[];
21
+ /** The values a form starts with: the options it marks as selected. */
22
+ export declare function initialValues(items: readonly FormItem[] | undefined): FormValues;
23
+ /**
24
+ * The form's payment, when it has one: a fixed price the form sets, or the
25
+ * field whose answer is the sum. Either way the charge is the server's;
26
+ * this only decides when a card is wanted.
27
+ */
28
+ export type Payment = {
29
+ readonly amount: number;
30
+ } | {
31
+ readonly amountItem: string;
32
+ };
33
+ export declare function paymentOf(form: {
34
+ readonly integration?: ReadonlyArray<Record<string, unknown>> | undefined;
35
+ }): Payment | undefined;
36
+ /**
37
+ * Whether a build is a preview, from the site's own setting
38
+ * (openhi.org uses `PUBLIC_OPENHI_FORM_MODE`). A preview's submissions run
39
+ * each integration's preview settings in OpenHI, a test Stripe connection
40
+ * and preview recipients, or nothing, so it pairs with a test publishable
41
+ * key. Anything else is live.
42
+ */
43
+ export declare function isPreviewMode(setting: unknown): boolean;
44
+ /**
45
+ * What a payment needs of the site's card element: obtain a payment method
46
+ * id (Stripe hands one back; the card never touches the page's markup) and
47
+ * finish a step the card needs after the server charged.
48
+ */
49
+ export interface CardAdapter {
50
+ obtain(billing: {
51
+ name?: string;
52
+ email?: string;
53
+ }): Promise<string>;
54
+ finish(clientSecret: string): Promise<void>;
55
+ }
56
+ export interface FormSubmitterOptions {
57
+ readonly form: {
58
+ readonly id?: string | undefined;
59
+ readonly item?: readonly FormItem[] | undefined;
60
+ readonly confirmation?: string | undefined;
61
+ /** The form's `payment` from the loader, never its raw integrations. */
62
+ readonly payment?: Payment | undefined;
63
+ };
64
+ /** The API the built site posts to. */
65
+ readonly apiBase?: string | undefined;
66
+ /** A preview build says so on `$submit`. @default "live" */
67
+ readonly mode?: "live" | "preview";
68
+ /** The site's card element, for a form with a payment. */
69
+ readonly card?: CardAdapter | undefined;
70
+ /** Replaces the global `fetch`. */
71
+ readonly fetch?: typeof fetch;
72
+ }
73
+ export interface SubmitResult {
74
+ /** What to tell the person: the server's, else the form's, else "Thank you.". */
75
+ readonly confirmation: string;
76
+ /** Whether a payment was taken with this submission. */
77
+ readonly paid: boolean;
78
+ }
79
+ /** A failure to send, whose message is fit to show the person. */
80
+ export declare class SubmitError extends Error {
81
+ readonly status?: number | undefined;
82
+ readonly name = "SubmitError";
83
+ constructor(message: string, status?: number | undefined);
84
+ }
85
+ export interface FormSubmitter {
86
+ /** Where answers are posted, or `undefined` for a form with no id or no API. */
87
+ readonly target: string | undefined;
88
+ /** Whether submitting needs a card for these values. */
89
+ needsCard(values: FormValues): boolean;
90
+ /**
91
+ * Send the answers. Throws a `SubmitError` with a message to show.
92
+ *
93
+ * Safe against a second click and a failed card step: a second call
94
+ * while one is running is refused, and a charge the server already made
95
+ * that is waiting on the card's own step is finished by the retry, never
96
+ * submitted, and charged, again.
97
+ */
98
+ submit(values: FormValues, extras?: {
99
+ honeypot?: string;
100
+ }): Promise<SubmitResult>;
101
+ }
102
+ export declare function createFormSubmitter(options: FormSubmitterOptions): FormSubmitter;
103
+ /** One-shot submission, for a form with no payment step to retry. */
104
+ export declare function submitForm(options: FormSubmitterOptions & {
105
+ readonly values: FormValues;
106
+ readonly honeypot?: string;
107
+ }): Promise<SubmitResult>;
@@ -0,0 +1,201 @@
1
+ import { trimTrailingSlashes } from "../trim-slashes.js";
2
+ /** The answers the API takes, from what the person typed. */
3
+ export function answersFrom(items, values) {
4
+ const answers = [];
5
+ for (const item of items ?? []) {
6
+ if (item.type === "group") {
7
+ answers.push(...answersFrom(item.item, values));
8
+ continue;
9
+ }
10
+ if (item.type === "display")
11
+ continue;
12
+ const value = values[item.linkId];
13
+ const list = Array.isArray(value)
14
+ ? value
15
+ : value === undefined
16
+ ? []
17
+ : [value];
18
+ const kept = list.map((one) => one.trim()).filter((one) => one.length > 0);
19
+ if (kept.length > 0)
20
+ answers.push({ linkId: item.linkId, answer: kept });
21
+ }
22
+ return answers;
23
+ }
24
+ /** The values a form starts with: the options it marks as selected. */
25
+ export function initialValues(items) {
26
+ const values = {};
27
+ for (const item of items ?? []) {
28
+ if (item.type === "group")
29
+ Object.assign(values, initialValues(item.item));
30
+ const chosen = (item.answerOption ?? [])
31
+ .filter((option) => option.initialSelected)
32
+ .map((option) => option.value);
33
+ if (chosen.length > 0)
34
+ values[item.linkId] = item.repeats ? chosen : chosen[0];
35
+ }
36
+ return values;
37
+ }
38
+ export function paymentOf(form) {
39
+ const found = (form.integration ?? []).find((one) => one.kind === "payment");
40
+ if (found === undefined)
41
+ return undefined;
42
+ const amount = found.amount;
43
+ if (typeof amount === "number" && Number.isFinite(amount) && amount > 0)
44
+ return { amount };
45
+ const amountItem = found.amountItem;
46
+ return typeof amountItem === "string" && amountItem.length > 0
47
+ ? { amountItem }
48
+ : undefined;
49
+ }
50
+ /**
51
+ * Whether a build is a preview, from the site's own setting
52
+ * (openhi.org uses `PUBLIC_OPENHI_FORM_MODE`). A preview's submissions run
53
+ * each integration's preview settings in OpenHI, a test Stripe connection
54
+ * and preview recipients, or nothing, so it pairs with a test publishable
55
+ * key. Anything else is live.
56
+ */
57
+ export function isPreviewMode(setting) {
58
+ return setting === "preview";
59
+ }
60
+ /** The first answer to a field of this type, for a card's billing details. */
61
+ function firstOfType(items, values, type) {
62
+ for (const item of items ?? []) {
63
+ if (item.type === "group") {
64
+ const nested = firstOfType(item.item, values, type);
65
+ if (nested !== undefined)
66
+ return nested;
67
+ }
68
+ if (item.type === type) {
69
+ const value = values[item.linkId];
70
+ if (typeof value === "string" && value.trim().length > 0)
71
+ return value.trim();
72
+ }
73
+ }
74
+ return undefined;
75
+ }
76
+ /** A name for the billing details, from whatever name fields the form has. */
77
+ function nameFrom(items, values) {
78
+ const parts = [];
79
+ const walk = (list) => {
80
+ for (const item of list ?? []) {
81
+ if (item.type === "group")
82
+ walk(item.item);
83
+ if (/name/i.test(item.linkId) && item.type === "string") {
84
+ const value = values[item.linkId];
85
+ if (typeof value === "string" && value.trim().length > 0)
86
+ parts.push(value.trim());
87
+ }
88
+ }
89
+ };
90
+ walk(items);
91
+ return parts.length > 0 ? parts.join(" ") : undefined;
92
+ }
93
+ /** A failure to send, whose message is fit to show the person. */
94
+ export class SubmitError extends Error {
95
+ constructor(message, status) {
96
+ super(message);
97
+ this.status = status;
98
+ this.name = "SubmitError";
99
+ }
100
+ }
101
+ export function createFormSubmitter(options) {
102
+ const { form, card } = options;
103
+ const post = options.fetch ?? ((...args) => fetch(...args));
104
+ const apiBase = options.apiBase;
105
+ const target = form.id !== undefined && apiBase !== undefined && apiBase.length > 0
106
+ ? `${trimTrailingSlashes(apiBase)}/Form/${encodeURIComponent(form.id)}/$submit`
107
+ : undefined;
108
+ const payment = form.payment;
109
+ const amountOf = (values) => {
110
+ if (payment === undefined)
111
+ return 0;
112
+ if ("amount" in payment)
113
+ return payment.amount;
114
+ const raw = values[payment.amountItem];
115
+ return typeof raw === "string" ? Number(raw) : 0;
116
+ };
117
+ const needsCard = (values) => {
118
+ const amount = amountOf(values);
119
+ return (payment !== undefined &&
120
+ card !== undefined &&
121
+ Number.isFinite(amount) &&
122
+ amount > 0);
123
+ };
124
+ // A lock beside the work: a second click in the gap before the first has
125
+ // finished is a second charge.
126
+ let sending = false;
127
+ // A charge the server already made that is waiting on the card's own step.
128
+ let pending;
129
+ return {
130
+ target,
131
+ needsCard,
132
+ async submit(values, extras = {}) {
133
+ if (target === undefined) {
134
+ throw new SubmitError("This form is not connected yet.");
135
+ }
136
+ if (sending)
137
+ throw new SubmitError("Already sending.");
138
+ sending = true;
139
+ try {
140
+ if (pending !== undefined && card !== undefined) {
141
+ await card.finish(pending);
142
+ pending = undefined;
143
+ return {
144
+ confirmation: form.confirmation ?? "Thank you.",
145
+ paid: true,
146
+ };
147
+ }
148
+ const paying = needsCard(values);
149
+ if (paying &&
150
+ payment !== undefined &&
151
+ "amountItem" in payment &&
152
+ amountOf(values) < 1) {
153
+ throw new SubmitError("Enter an amount of at least 1.");
154
+ }
155
+ const name = nameFrom(form.item, values);
156
+ const email = firstOfType(form.item, values, "email");
157
+ const paymentMethod = paying && card !== undefined
158
+ ? await card.obtain({
159
+ ...(name !== undefined && { name }),
160
+ ...(email !== undefined && { email }),
161
+ })
162
+ : undefined;
163
+ const response = await post(target, {
164
+ method: "POST",
165
+ headers: { "Content-Type": "application/json" },
166
+ body: JSON.stringify({
167
+ answers: answersFrom(form.item, values),
168
+ honeypot: extras.honeypot ?? "",
169
+ ...(paymentMethod !== undefined && { payment: { paymentMethod } }),
170
+ ...(options.mode === "preview" && { mode: "preview" }),
171
+ }),
172
+ });
173
+ if (!response.ok) {
174
+ const outcome = (await response.json().catch(() => undefined));
175
+ throw new SubmitError(outcome?.issue?.[0]?.diagnostics ??
176
+ (response.status === 402
177
+ ? "The payment did not go through."
178
+ : `The form could not be sent (${response.status}).`), response.status);
179
+ }
180
+ const answer = (await response.json().catch(() => ({})));
181
+ if (answer.next?.clientSecret !== undefined && card !== undefined) {
182
+ pending = answer.next.clientSecret;
183
+ await card.finish(answer.next.clientSecret);
184
+ pending = undefined;
185
+ }
186
+ return {
187
+ confirmation: answer.confirmation ?? form.confirmation ?? "Thank you.",
188
+ paid: paymentMethod !== undefined,
189
+ };
190
+ }
191
+ finally {
192
+ sending = false;
193
+ }
194
+ },
195
+ };
196
+ }
197
+ /** One-shot submission, for a form with no payment step to retry. */
198
+ export function submitForm(options) {
199
+ const { values, honeypot, ...rest } = options;
200
+ return createFormSubmitter(rest).submit(values, honeypot === undefined ? {} : { honeypot });
201
+ }