@aglyn/plugins-forms 1.0.0-beta.290 → 1.0.0-beta.292

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 (61) hide show
  1. package/README.md +11 -1
  2. package/package.json +14 -14
  3. package/src/lib/components/form-detail-card.js +122 -2
  4. package/src/lib/components/form-detail-card.js.map +1 -1
  5. package/src/lib/components/form-file-upload-body.d.ts +32 -0
  6. package/src/lib/components/form-file-upload-body.js +349 -0
  7. package/src/lib/components/form-file-upload-body.js.map +1 -0
  8. package/src/lib/components/form-file-upload.d.ts +39 -0
  9. package/src/lib/components/form-file-upload.js +175 -0
  10. package/src/lib/components/form-file-upload.js.map +1 -0
  11. package/src/lib/components/form-upload-context.d.ts +31 -0
  12. package/src/lib/components/form-upload-context.js +19 -0
  13. package/src/lib/components/form-upload-context.js.map +1 -0
  14. package/src/lib/components/form.js +48 -4
  15. package/src/lib/components/form.js.map +1 -1
  16. package/src/lib/declarations.console-server.js +14 -0
  17. package/src/lib/declarations.console-server.js.map +1 -1
  18. package/src/lib/declarations.server.js +18 -0
  19. package/src/lib/declarations.server.js.map +1 -1
  20. package/src/lib/model/form-request.d.ts +102 -0
  21. package/src/lib/model/form-request.js +187 -0
  22. package/src/lib/model/form-request.js.map +1 -0
  23. package/src/lib/server/form-confirmation-email.d.ts +70 -0
  24. package/src/lib/server/form-confirmation-email.js +194 -0
  25. package/src/lib/server/form-confirmation-email.js.map +1 -0
  26. package/src/lib/server/form-submit-files.d.ts +42 -0
  27. package/src/lib/server/form-submit-files.js +98 -0
  28. package/src/lib/server/form-submit-files.js.map +1 -0
  29. package/src/lib/server/form-submit.js +115 -7
  30. package/src/lib/server/form-submit.js.map +1 -1
  31. package/src/lib/server/form-upload-sweep.d.ts +30 -0
  32. package/src/lib/server/form-upload-sweep.js +83 -0
  33. package/src/lib/server/form-upload-sweep.js.map +1 -0
  34. package/src/lib/server/form-upload.d.ts +41 -0
  35. package/src/lib/server/form-upload.js +226 -0
  36. package/src/lib/server/form-upload.js.map +1 -0
  37. package/src/lib/server/form-uploads.d.ts +34 -0
  38. package/src/lib/server/form-uploads.js +29 -0
  39. package/src/lib/server/form-uploads.js.map +1 -0
  40. package/src/lib/server/submission-access.d.ts +38 -0
  41. package/src/lib/server/submission-access.js +37 -0
  42. package/src/lib/server/submission-access.js.map +1 -0
  43. package/src/lib/server/submission-facts.d.ts +37 -0
  44. package/src/lib/server/submission-facts.js +227 -0
  45. package/src/lib/server/submission-facts.js.map +1 -0
  46. package/src/lib/server/submission-files.d.ts +41 -0
  47. package/src/lib/server/submission-files.js +126 -0
  48. package/src/lib/server/submission-files.js.map +1 -0
  49. package/src/lib/server.js +22 -0
  50. package/src/lib/server.js.map +1 -1
  51. package/src/lib/site.js +8 -0
  52. package/src/lib/site.js.map +1 -1
  53. package/src/lib/tenant-emails.d.ts +29 -0
  54. package/src/lib/tenant-emails.js +125 -0
  55. package/src/lib/tenant-emails.js.map +1 -0
  56. package/src/lib/testing/stand-in-firestore.d.ts +27 -0
  57. package/src/lib/testing/stand-in-firestore.js +128 -0
  58. package/src/lib/testing/stand-in-firestore.js.map +1 -0
  59. package/src/lib/utils/form-confirmation-content.d.ts +47 -0
  60. package/src/lib/utils/form-confirmation-content.js +109 -0
  61. package/src/lib/utils/form-confirmation-content.js.map +1 -0
@@ -0,0 +1,194 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { resolveHostToken, siteContactEmail } from "@aglyn/aglyn/app-utils/host-tokens";
18
+ import { resolveBrandingProfile } from "@aglyn/aglyn/app-utils/plan-entitlements";
19
+ import { emailThreadAfterSend, isEmailConfigured, mintEmailMessageId, nextThreadHeaders, sendEmail } from "@aglyn/shared-util-email";
20
+ import { consumeRateLimit, emailSuppressionKey, firebaseAdmin, hostSendingIdentity, meterHostEmail, renderHostEmailWithTokens, transactionalAddressSuppression } from "@aglyn/tenant-data-admin";
21
+ import { FORM_CONFIRMATION_EMAIL_KEY } from "../tenant-emails.js";
22
+ import { formConfirmationContent } from "../utils/form-confirmation-content.js";
23
+ /*==========================================
24
+ * THE CONFIRMATION A FORM EMAILS THE PERSON WHO SENT IT (AGL-4098).
25
+ *
26
+ * Loaded only by the submit route, and only for a form set to "Email the
27
+ * person a confirmation" whose submission named an address, so the renderer
28
+ * stays out of every other submission.
29
+ *
30
+ * One email, the `form-confirmation` catalog key in the site's theme and its
31
+ * header and footer (or the site's own design of it):
32
+ *
33
+ * - FROM the site's sending identity, under the site's name;
34
+ * - REPLY-TO the site's contact email (its listing's, else its support
35
+ * email), so a reply reaches the business; none when the site has none;
36
+ * - STARTING A CONVERSATION: a `Message-ID` minted on the sending domain
37
+ * and the conversation's root in `References` (`nextThreadHeaders`),
38
+ * answered as the thread the submission keeps (`emailThread`), so a
39
+ * quote started from the request later replies into it;
40
+ * - TRANSACTIONAL: the person asked for it by sending the form, so only an
41
+ * address that bounced for good or reported mail as spam is refused
42
+ * (`transactionalAddressSuppression`), never one that unsubscribed from
43
+ * the site's newsletter;
44
+ * - LIMITED: three confirmations an hour to one address from one site, and
45
+ * three hundred an hour from one site, so a form cannot be used to flood
46
+ * somebody else's inbox with a site's mail. Whoever sends a form types
47
+ * the address, so the answers are echoed with their links taken out
48
+ * (`form-confirmation-content.ts`), and the send is not declared owed:
49
+ * the outbound screen judges it like any mail the site writes;
50
+ * - METERED as a site's transactional email.
51
+ *
52
+ * Never throws and never fails the submission: the submission is stored
53
+ * before this runs, and a confirmation that could not go is logged.
54
+ *=========================================*/ /** Confirmations one address may be sent by one site, per hour. */ export const FORM_CONFIRMATIONS_PER_ADDRESS = {
55
+ limit: 3,
56
+ windowMs: 60 * 60000
57
+ };
58
+ /** Confirmations one site may send, per hour. */ export const FORM_CONFIRMATIONS_PER_SITE = {
59
+ limit: 300,
60
+ windowMs: 60 * 60000
61
+ };
62
+ export function defaultFormConfirmationDeps() {
63
+ return {
64
+ configured: ()=>isEmailConfigured(),
65
+ sendingIdentity: (hostId)=>hostSendingIdentity(hostId),
66
+ render: (hostId, key, tokens)=>renderHostEmailWithTokens(firebaseAdmin.app().firestore(), hostId, key, tokens),
67
+ send: (options)=>sendEmail(options),
68
+ meter: async (hostId)=>{
69
+ await meterHostEmail(hostId);
70
+ },
71
+ suppression: (email)=>transactionalAddressSuppression(email),
72
+ consumeRateLimit: (key, options)=>consumeRateLimit(key, options)
73
+ };
74
+ }
75
+ /** The business's name as its emails print it. */ export function formBusinessName(host) {
76
+ var _ref, _host_displayName;
77
+ const named = resolveHostToken('businessName', host);
78
+ return String(named != null ? named : '').trim() || String((_ref = (_host_displayName = host['displayName']) != null ? _host_displayName : host['name']) != null ? _ref : '').trim();
79
+ }
80
+ /** The phone the site's listing gives, or null. */ function listedPhone(host) {
81
+ var _ref;
82
+ var _host_seo;
83
+ const entity = (_ref = (_host_seo = host['seo']) == null ? void 0 : _host_seo['entity']) != null ? _ref : null;
84
+ const phone = typeof (entity == null ? void 0 : entity['telephone']) === 'string' ? entity['telephone'].trim().slice(0, 40) : '';
85
+ return phone || null;
86
+ }
87
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
88
+ /** Sends one form's confirmation; never throws. */ export async function sendFormConfirmation(input, deps = defaultFormConfirmationDeps()) {
89
+ try {
90
+ var _emailSuppressionKey, _input_host_cname, _result_id;
91
+ var _rendered_subject;
92
+ const to = input.to.trim();
93
+ if (!EMAIL.test(to)) return {
94
+ sent: false,
95
+ reason: 'no-address'
96
+ };
97
+ if (!deps.configured()) return {
98
+ sent: false,
99
+ reason: 'unconfigured'
100
+ };
101
+ if (await deps.suppression(to)) return {
102
+ sent: false,
103
+ reason: 'suppressed'
104
+ };
105
+ const recipientKey = (_emailSuppressionKey = emailSuppressionKey(to)) != null ? _emailSuppressionKey : to.toLowerCase();
106
+ for (const [key, rate] of [
107
+ [
108
+ `form-confirmation:${input.hostId}:${recipientKey}`,
109
+ FORM_CONFIRMATIONS_PER_ADDRESS
110
+ ],
111
+ [
112
+ `form-confirmation-site:${input.hostId}`,
113
+ FORM_CONFIRMATIONS_PER_SITE
114
+ ]
115
+ ]){
116
+ if (!(await deps.consumeRateLimit(key, rate)).allowed) return {
117
+ sent: false,
118
+ reason: 'rate-limited'
119
+ };
120
+ }
121
+ const businessName = formBusinessName(input.host);
122
+ const contact = siteContactEmail(input.host);
123
+ const content = formConfirmationContent({
124
+ businessName,
125
+ request: input.request,
126
+ answers: input.answers,
127
+ decls: input.decls,
128
+ consentFieldName: input.consentFieldName,
129
+ fileNames: input.fileNames,
130
+ contactEmail: contact && EMAIL.test(contact) ? contact : null,
131
+ contactPhone: listedPhone(input.host)
132
+ });
133
+ const identity = await deps.sendingIdentity(input.hostId);
134
+ const rendered = await deps.render(input.hostId, FORM_CONFIRMATION_EMAIL_KEY, content.tokens);
135
+ const siteHost = String((_input_host_cname = input.host['cname']) != null ? _input_host_cname : '').trim() || null;
136
+ // The first message of the conversation: its own id, and the root every
137
+ // later message shares in `References`.
138
+ const messageId = mintEmailMessageId([
139
+ identity == null ? void 0 : identity.domain,
140
+ identity == null ? void 0 : identity.from,
141
+ siteHost
142
+ ], {
143
+ label: 'form',
144
+ atMs: input.atMs
145
+ });
146
+ const subject = (rendered == null ? void 0 : (_rendered_subject = rendered.subject) == null ? void 0 : _rendered_subject.trim()) || content.subject;
147
+ const result = await deps.send(_extends({
148
+ to,
149
+ subject,
150
+ text: (rendered == null ? void 0 : rendered.text) || content.text
151
+ }, (rendered == null ? void 0 : rendered.html) ? {
152
+ html: rendered.html
153
+ } : {}, {
154
+ headers: nextThreadHeaders(null, messageId)
155
+ }, contact && EMAIL.test(contact) ? {
156
+ replyTo: contact
157
+ } : {}, {
158
+ fromName: resolveBrandingProfile(input.org).fromName,
159
+ sendingIdentity: identity,
160
+ audience: 'tenant',
161
+ context: 'form confirmation'
162
+ }));
163
+ if (!result.sent) {
164
+ var _result_reason;
165
+ return {
166
+ sent: false,
167
+ reason: String((_result_reason = result.reason) != null ? _result_reason : 'not-sent')
168
+ };
169
+ }
170
+ // Cost meter (AGL-1438), as every transactional site email.
171
+ await deps.meter(input.hostId).catch((error)=>console.error('[forms] confirmation not metered', error));
172
+ return {
173
+ sent: true,
174
+ messageId,
175
+ providerId: (_result_id = result.id) != null ? _result_id : null,
176
+ subject,
177
+ thread: emailThreadAfterSend(null, {
178
+ messageId,
179
+ subject
180
+ })
181
+ };
182
+ } catch (error) {
183
+ console.error('[forms] confirmation failed', {
184
+ hostId: input.hostId,
185
+ error
186
+ });
187
+ return {
188
+ sent: false,
189
+ reason: 'error'
190
+ };
191
+ }
192
+ }
193
+
194
+ //# sourceMappingURL=form-confirmation-email.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/server/form-confirmation-email.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { resolveHostToken, siteContactEmail, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type { FormFieldDecl, FormRequest } from '@aglyn/aglyn/app-utils/forms'\nimport {\n emailThreadAfterSend,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n sendEmail,\n type EmailThread,\n type RenderedHostEmail,\n type SendEmailOptions,\n type SendEmailResult,\n type SendingIdentityVerdict,\n} from '@aglyn/shared-util-email'\nimport {\n consumeRateLimit,\n emailSuppressionKey,\n firebaseAdmin,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport { FORM_CONFIRMATION_EMAIL_KEY } from '../tenant-emails'\nimport { formConfirmationContent } from '../utils/form-confirmation-content'\n\n/*==========================================\n * THE CONFIRMATION A FORM EMAILS THE PERSON WHO SENT IT (AGL-4098).\n *\n * Loaded only by the submit route, and only for a form set to \"Email the\n * person a confirmation\" whose submission named an address, so the renderer\n * stays out of every other submission.\n *\n * One email, the `form-confirmation` catalog key in the site's theme and its\n * header and footer (or the site's own design of it):\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email (its listing's, else its support\n * email), so a reply reaches the business; none when the site has none;\n * - STARTING A CONVERSATION: a `Message-ID` minted on the sending domain\n * and the conversation's root in `References` (`nextThreadHeaders`),\n * answered as the thread the submission keeps (`emailThread`), so a\n * quote started from the request later replies into it;\n * - TRANSACTIONAL: the person asked for it by sending the form, so only an\n * address that bounced for good or reported mail as spam is refused\n * (`transactionalAddressSuppression`), never one that unsubscribed from\n * the site's newsletter;\n * - LIMITED: three confirmations an hour to one address from one site, and\n * three hundred an hour from one site, so a form cannot be used to flood\n * somebody else's inbox with a site's mail. Whoever sends a form types\n * the address, so the answers are echoed with their links taken out\n * (`form-confirmation-content.ts`), and the send is not declared owed:\n * the outbound screen judges it like any mail the site writes;\n * - METERED as a site's transactional email.\n *\n * Never throws and never fails the submission: the submission is stored\n * before this runs, and a confirmation that could not go is logged.\n *=========================================*/\n\n/** Confirmations one address may be sent by one site, per hour. */\nexport const FORM_CONFIRMATIONS_PER_ADDRESS = { limit: 3, windowMs: 60 * 60_000 }\n/** Confirmations one site may send, per hour. */\nexport const FORM_CONFIRMATIONS_PER_SITE = { limit: 300, windowMs: 60 * 60_000 }\n\nexport interface FormConfirmationInput {\n hostId: string\n host: Record<string, unknown>\n org: unknown\n to: string\n request: FormRequest | null\n answers: Readonly<Record<string, string>>\n decls: readonly FormFieldDecl[]\n consentFieldName: string | null\n fileNames: readonly string[]\n atMs: number\n}\n\nexport type FormConfirmationResult =\n | { sent: true; messageId: string; providerId: string | null; subject: string; thread: EmailThread }\n | { sent: false; reason: string }\n\nexport interface FormConfirmationDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: the person asked for this email. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean }>\n}\n\nexport function defaultFormConfirmationDeps(): FormConfirmationDeps {\n return {\n configured: () => isEmailConfigured(),\n sendingIdentity: (hostId) => hostSendingIdentity(hostId),\n render: (hostId, key, tokens) =>\n renderHostEmailWithTokens(firebaseAdmin.app().firestore(), hostId, key, tokens),\n send: (options) => sendEmail(options),\n meter: async (hostId) => {\n await meterHostEmail(hostId)\n },\n suppression: (email) => transactionalAddressSuppression(email),\n consumeRateLimit: (key, options) => consumeRateLimit(key, options),\n }\n}\n\n/** The business's name as its emails print it. */\nexport function formBusinessName(host: Record<string, unknown>): string {\n const named = resolveHostToken('businessName', host as HostTokenSource)\n return String(named ?? '').trim() || String(host['displayName'] ?? host['name'] ?? '').trim()\n}\n\n/** The phone the site's listing gives, or null. */\nfunction listedPhone(host: Record<string, unknown>): string | null {\n const entity = ((host['seo'] as Record<string, unknown> | undefined)?.['entity'] ?? null) as Record<string, unknown> | null\n const phone = typeof entity?.['telephone'] === 'string' ? entity['telephone'].trim().slice(0, 40) : ''\n return phone || null\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** Sends one form's confirmation; never throws. */\nexport async function sendFormConfirmation(\n input: FormConfirmationInput,\n deps: FormConfirmationDeps = defaultFormConfirmationDeps(),\n): Promise<FormConfirmationResult> {\n try {\n const to = input.to.trim()\n if (!EMAIL.test(to)) return { sent: false, reason: 'no-address' }\n if (!deps.configured()) return { sent: false, reason: 'unconfigured' }\n if (await deps.suppression(to)) return { sent: false, reason: 'suppressed' }\n const recipientKey = emailSuppressionKey(to) ?? to.toLowerCase()\n for (const [key, rate] of [\n [`form-confirmation:${input.hostId}:${recipientKey}`, FORM_CONFIRMATIONS_PER_ADDRESS],\n [`form-confirmation-site:${input.hostId}`, FORM_CONFIRMATIONS_PER_SITE],\n ] as const) {\n if (!(await deps.consumeRateLimit(key, rate)).allowed) return { sent: false, reason: 'rate-limited' }\n }\n\n const businessName = formBusinessName(input.host)\n const contact = siteContactEmail(input.host as never)\n const content = formConfirmationContent({\n businessName,\n request: input.request,\n answers: input.answers,\n decls: input.decls,\n consentFieldName: input.consentFieldName,\n fileNames: input.fileNames,\n contactEmail: contact && EMAIL.test(contact) ? contact : null,\n contactPhone: listedPhone(input.host),\n })\n const identity = await deps.sendingIdentity(input.hostId)\n const rendered = await deps.render(input.hostId, FORM_CONFIRMATION_EMAIL_KEY, content.tokens)\n const siteHost = String(input.host['cname'] ?? '').trim() || null\n // The first message of the conversation: its own id, and the root every\n // later message shares in `References`.\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'form',\n atMs: input.atMs,\n })\n const subject = rendered?.subject?.trim() || content.subject\n const result = await deps.send({\n to,\n subject,\n text: rendered?.text || content.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n headers: nextThreadHeaders(null, messageId),\n ...(contact && EMAIL.test(contact) ? { replyTo: contact } : {}),\n fromName: resolveBrandingProfile(input.org as never).fromName,\n sendingIdentity: identity,\n audience: 'tenant',\n context: 'form confirmation',\n // Not declared owed: its answers were typed by whoever sent the form,\n // so the outbound screen judges it as fully as a merchant's own mail.\n })\n if (!result.sent) {\n return { sent: false, reason: String((result as { reason?: string }).reason ?? 'not-sent') }\n }\n // Cost meter (AGL-1438), as every transactional site email.\n await deps.meter(input.hostId).catch((error) => console.error('[forms] confirmation not metered', error))\n return {\n sent: true,\n messageId,\n providerId: (result as Extract<SendEmailResult, { sent: true }>).id ?? null,\n subject,\n thread: emailThreadAfterSend(null, { messageId, subject }),\n }\n } catch (error) {\n console.error('[forms] confirmation failed', { hostId: input.hostId, error })\n return { sent: false, reason: 'error' }\n }\n}\n"],"names":["resolveHostToken","siteContactEmail","resolveBrandingProfile","emailThreadAfterSend","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","sendEmail","consumeRateLimit","emailSuppressionKey","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","transactionalAddressSuppression","FORM_CONFIRMATION_EMAIL_KEY","formConfirmationContent","FORM_CONFIRMATIONS_PER_ADDRESS","limit","windowMs","FORM_CONFIRMATIONS_PER_SITE","defaultFormConfirmationDeps","configured","sendingIdentity","hostId","render","key","tokens","app","firestore","send","options","meter","suppression","email","formBusinessName","host","named","String","trim","listedPhone","entity","phone","slice","EMAIL","sendFormConfirmation","input","deps","rendered","to","test","sent","reason","recipientKey","toLowerCase","rate","allowed","businessName","contact","content","request","answers","decls","consentFieldName","fileNames","contactEmail","contactPhone","identity","siteHost","messageId","domain","from","label","atMs","subject","result","text","html","headers","replyTo","fromName","org","audience","context","catch","error","console","providerId","id","thread"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClB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,OAAOxB,IAAI,EAAE;gBACqB;YAArC,OAAO;gBAAEA,MAAM;gBAAOC,QAAQd,QAAO,iBAAA,AAACqC,OAA+BvB,MAAM,YAAtC,iBAA0C;YAAY;QAC7F;QACA,4DAA4D;QAC5D,MAAML,KAAKf,KAAK,CAACc,MAAMtB,MAAM,EAAE4D,KAAK,CAAC,CAACC,QAAUC,QAAQD,KAAK,CAAC,oCAAoCA;QAClG,OAAO;YACLlC,MAAM;YACNkB;YACAkB,UAAU,GAAE,aAAA,AAACZ,OAAoDa,EAAE,YAAvD,aAA2D;YACvEd;YACAe,QAAQtF,qBAAqB,MAAM;gBAAEkE;gBAAWK;YAAQ;QAC1D;IACF,EAAE,OAAOW,OAAO;QACdC,QAAQD,KAAK,CAAC,+BAA+B;YAAE7D,QAAQsB,MAAMtB,MAAM;YAAE6D;QAAM;QAC3E,OAAO;YAAElC,MAAM;YAAOC,QAAQ;QAAQ;IACxC;AACF"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { FormFieldDecl } from '@aglyn/aglyn/app-utils/forms';
18
+ import { type FormFileRefs, type FormSubmissionFile } from '../model/form-request';
19
+ import type { FormUploadCalls } from './form-uploads';
20
+ export type AttachedFormFiles = {
21
+ ok: true;
22
+ /** The pending key, which the submission takes as its id. */
23
+ key: string;
24
+ files: FormSubmissionFile[];
25
+ /** Each file field's answer: its files' names. */
26
+ answers: Record<string, string>;
27
+ /** Deletes the key's upload record once the submission holds the files. Never throws. */
28
+ release(): Promise<void>;
29
+ } | {
30
+ ok: false;
31
+ status: number;
32
+ error: string;
33
+ };
34
+ export declare function attachFormFiles(input: {
35
+ firestore: FirebaseFirestore.Firestore;
36
+ hostId: string;
37
+ /** The verified form's id, or null for a form no entity binds. */
38
+ formId: string | null;
39
+ decls: readonly FormFieldDecl[];
40
+ refs: FormFileRefs;
41
+ uploads: Pick<FormUploadCalls, 'read'>;
42
+ }): Promise<AttachedFormFiles>;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { visitorUploadTypeInKinds, VISITOR_UPLOAD_MAX_FILES } from "@aglyn/aglyn/app-utils/visitor-upload";
17
+ import { formFileFieldAnswer, formFileFields, formFileScope, formSubmissionFileOf } from "../model/form-request.js";
18
+ import { formUploadKeyFiles, formUploadKeyRef } from "./form-upload.js";
19
+ const MISSING = 'One of your files didn’t arrive. Remove it, attach it again and send the form.';
20
+ const LAPSED = 'Your files took too long to send. Attach them again and send the form.';
21
+ export async function attachFormFiles(input) {
22
+ const { firestore, hostId, formId, decls, refs, uploads } = input;
23
+ // Only a bound form takes files: the upload route refuses every other.
24
+ if (!formId) return {
25
+ ok: false,
26
+ status: 400,
27
+ error: 'This form doesn’t take files.'
28
+ };
29
+ const fileFields = formFileFields(decls);
30
+ const markerRef = formUploadKeyRef(firestore, hostId, formId, refs.key);
31
+ const marker = await markerRef.get();
32
+ if (!marker.exists) return {
33
+ ok: false,
34
+ status: 409,
35
+ error: LAPSED
36
+ };
37
+ const held = formUploadKeyFiles(marker.data());
38
+ const perField = new Map();
39
+ for (const ref of refs.refs){
40
+ var _perField_get, _decl_maxFiles;
41
+ const decl = fileFields.get(ref.field);
42
+ if (!decl) return {
43
+ ok: false,
44
+ status: 400,
45
+ error: 'This form doesn’t take files there.'
46
+ };
47
+ if (held[ref.id] !== ref.field) return {
48
+ ok: false,
49
+ status: 400,
50
+ error: MISSING
51
+ };
52
+ const count = ((_perField_get = perField.get(ref.field)) != null ? _perField_get : 0) + 1;
53
+ if (count > ((_decl_maxFiles = decl.maxFiles) != null ? _decl_maxFiles : VISITOR_UPLOAD_MAX_FILES)) {
54
+ return {
55
+ ok: false,
56
+ status: 400,
57
+ error: `${decl.label || 'A file field'} takes fewer files than were sent.`
58
+ };
59
+ }
60
+ perField.set(ref.field, count);
61
+ }
62
+ const scope = formFileScope(hostId, refs.key);
63
+ const kept = await Promise.all(refs.refs.map((ref)=>uploads.read(scope, ref.id)));
64
+ const files = [];
65
+ for (const [index, ref] of refs.refs.entries()){
66
+ var _fileFields_get;
67
+ const file = kept[index];
68
+ if (!file) return {
69
+ ok: false,
70
+ status: 400,
71
+ error: MISSING
72
+ };
73
+ if (!visitorUploadTypeInKinds(file.contentType, (_fileFields_get = fileFields.get(ref.field)) == null ? void 0 : _fileFields_get.fileKinds)) {
74
+ return {
75
+ ok: false,
76
+ status: 400,
77
+ error: `${file.name} isn’t a kind of file this form takes.`
78
+ };
79
+ }
80
+ files.push(formSubmissionFileOf(ref.field, file));
81
+ }
82
+ const answers = {};
83
+ for (const field of fileFields.keys()){
84
+ const named = files.filter((file)=>file.field === field);
85
+ if (named.length) answers[field] = formFileFieldAnswer(named);
86
+ }
87
+ return {
88
+ ok: true,
89
+ key: refs.key,
90
+ files,
91
+ answers,
92
+ release: async ()=>{
93
+ await markerRef.delete().catch((error)=>console.error('[forms] upload record not released', error));
94
+ }
95
+ };
96
+ }
97
+
98
+ //# sourceMappingURL=form-submit-files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/server/form-submit-files.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FormFieldDecl } from '@aglyn/aglyn/app-utils/forms'\nimport { visitorUploadTypeInKinds, VISITOR_UPLOAD_MAX_FILES } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport {\n formFileFieldAnswer,\n formFileFields,\n formFileScope,\n formSubmissionFileOf,\n type FormFileRefs,\n type FormSubmissionFile,\n} from '../model/form-request'\nimport { formUploadKeyFiles, formUploadKeyRef } from './form-upload'\nimport type { FormUploadCalls } from './form-uploads'\n\n/*==========================================\n * THE FILES A SUBMISSION NAMES, CHECKED BEFORE IT IS STORED (AGL-4098).\n *\n * A form sends its files by id, under the pending key the page minted. Each\n * is held to:\n *\n * - the FORM: a bound form on this site, whose upload record for the key\n * (`forms/{formId}/formUploadKeys/{key}`) exists — so the key was minted\n * for this form by the upload route, and has not been swept;\n * - the FIELD: a File upload field the form declares, which the upload\n * record says the file was sent for, within the field's number;\n * - the FILE: kept under the key's scope (`readVisitorUpload`), of a kind\n * the field takes.\n *\n * Any one that fails refuses the whole submission with a sentence the page\n * shows, before anything is written or counted. What passes is recorded on\n * the submission as `files` (id, field, name, type, size), and each file\n * field's answer becomes the names of its files, read from what was kept\n * rather than from what the page said.\n *=========================================*/\n\nexport type AttachedFormFiles =\n | {\n ok: true\n /** The pending key, which the submission takes as its id. */\n key: string\n files: FormSubmissionFile[]\n /** Each file field's answer: its files' names. */\n answers: Record<string, string>\n /** Deletes the key's upload record once the submission holds the files. Never throws. */\n release(): Promise<void>\n }\n | { ok: false; status: number; error: string }\n\nconst MISSING = 'One of your files didn’t arrive. Remove it, attach it again and send the form.'\nconst LAPSED = 'Your files took too long to send. Attach them again and send the form.'\n\nexport async function attachFormFiles(input: {\n firestore: FirebaseFirestore.Firestore\n hostId: string\n /** The verified form's id, or null for a form no entity binds. */\n formId: string | null\n decls: readonly FormFieldDecl[]\n refs: FormFileRefs\n uploads: Pick<FormUploadCalls, 'read'>\n}): Promise<AttachedFormFiles> {\n const { firestore, hostId, formId, decls, refs, uploads } = input\n // Only a bound form takes files: the upload route refuses every other.\n if (!formId) return { ok: false, status: 400, error: 'This form doesn’t take files.' }\n const fileFields = formFileFields(decls)\n const markerRef = formUploadKeyRef(firestore, hostId, formId, refs.key)\n const marker = await markerRef.get()\n if (!marker.exists) return { ok: false, status: 409, error: LAPSED }\n const held = formUploadKeyFiles(marker.data() as Record<string, unknown> | undefined)\n\n const perField = new Map<string, number>()\n for (const ref of refs.refs) {\n const decl = fileFields.get(ref.field)\n if (!decl) return { ok: false, status: 400, error: 'This form doesn’t take files there.' }\n if (held[ref.id] !== ref.field) return { ok: false, status: 400, error: MISSING }\n const count = (perField.get(ref.field) ?? 0) + 1\n if (count > (decl.maxFiles ?? VISITOR_UPLOAD_MAX_FILES)) {\n return { ok: false, status: 400, error: `${decl.label || 'A file field'} takes fewer files than were sent.` }\n }\n perField.set(ref.field, count)\n }\n\n const scope = formFileScope(hostId, refs.key)\n const kept = await Promise.all(refs.refs.map((ref) => uploads.read(scope, ref.id)))\n const files: FormSubmissionFile[] = []\n for (const [index, ref] of refs.refs.entries()) {\n const file = kept[index]\n if (!file) return { ok: false, status: 400, error: MISSING }\n if (!visitorUploadTypeInKinds(file.contentType, fileFields.get(ref.field)?.fileKinds)) {\n return { ok: false, status: 400, error: `${file.name} isn’t a kind of file this form takes.` }\n }\n files.push(formSubmissionFileOf(ref.field, file))\n }\n const answers: Record<string, string> = {}\n for (const field of fileFields.keys()) {\n const named = files.filter((file) => file.field === field)\n if (named.length) answers[field] = formFileFieldAnswer(named)\n }\n return {\n ok: true,\n key: refs.key,\n files,\n answers,\n release: async () => {\n await markerRef.delete().catch((error: unknown) => console.error('[forms] upload record not released', error))\n },\n }\n}\n"],"names":["visitorUploadTypeInKinds","VISITOR_UPLOAD_MAX_FILES","formFileFieldAnswer","formFileFields","formFileScope","formSubmissionFileOf","formUploadKeyFiles","formUploadKeyRef","MISSING","LAPSED","attachFormFiles","input","firestore","hostId","formId","decls","refs","uploads","ok","status","error","fileFields","markerRef","key","marker","get","exists","held","data","perField","Map","ref","decl","field","id","count","maxFiles","label","set","scope","kept","Promise","all","map","read","files","index","entries","file","contentType","fileKinds","name","push","answers","keys","named","filter","length","release","delete","catch","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,wBAAwB,EAAEC,wBAAwB,QAAQ,wCAAuC;AAC1G,SACEC,mBAAmB,EACnBC,cAAc,EACdC,aAAa,EACbC,oBAAoB,QAGf,2BAAuB;AAC9B,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,mBAAe;AAqCpE,MAAMC,UAAU;AAChB,MAAMC,SAAS;AAEf,OAAO,eAAeC,gBAAgBC,KAQrC;IACC,MAAM,EAAEC,SAAS,EAAEC,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAEC,IAAI,EAAEC,OAAO,EAAE,GAAGN;IAC5D,uEAAuE;IACvE,IAAI,CAACG,QAAQ,OAAO;QAAEI,IAAI;QAAOC,QAAQ;QAAKC,OAAO;IAAgC;IACrF,MAAMC,aAAalB,eAAeY;IAClC,MAAMO,YAAYf,iBAAiBK,WAAWC,QAAQC,QAAQE,KAAKO,GAAG;IACtE,MAAMC,SAAS,MAAMF,UAAUG,GAAG;IAClC,IAAI,CAACD,OAAOE,MAAM,EAAE,OAAO;QAAER,IAAI;QAAOC,QAAQ;QAAKC,OAAOX;IAAO;IACnE,MAAMkB,OAAOr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,gBAA2B6B,SAAS,GAAG;YACrF,OAAO;gBAAEhC,IAAI;gBAAOC,QAAQ;gBAAKC,OAAO,GAAG4B,KAAKG,IAAI,CAAC,sCAAsC,CAAC;YAAC;QAC/F;QACAN,MAAMO,IAAI,CAAC/C,qBAAqB0B,IAAIE,KAAK,EAAEe;IAC7C;IACA,MAAMK,UAAkC,CAAC;IACzC,KAAK,MAAMpB,SAASZ,WAAWiC,IAAI,GAAI;QACrC,MAAMC,QAAQV,MAAMW,MAAM,CAAC,CAACR,OAASA,KAAKf,KAAK,KAAKA;QACpD,IAAIsB,MAAME,MAAM,EAAEJ,OAAO,CAACpB,MAAM,GAAG/B,oBAAoBqD;IACzD;IACA,OAAO;QACLrC,IAAI;QACJK,KAAKP,KAAKO,GAAG;QACbsB;QACAQ;QACAK,SAAS;YACP,MAAMpC,UAAUqC,MAAM,GAAGC,KAAK,CAAC,CAACxC,QAAmByC,QAAQzC,KAAK,CAAC,sCAAsCA;QACzG;IACF;AACF"}
@@ -38,6 +38,9 @@ import { FieldValue } from "firebase-admin/firestore";
38
38
  import { isCredentialFieldName } from "@aglyn/shared-util-email/hosted-page-screen";
39
39
  import { FORMS_OFF_FOR_SITE_REFUSAL, formSubmissionDoorPlugin } from "../model/form-door.js";
40
40
  import { FORM_ABUSE_CEILING_CODE } from "../model/form-unavailable.js";
41
+ import { formSendsConfirmation, readFormRequest } from "@aglyn/aglyn/app-utils/forms";
42
+ import { FORM_FILES_BODY_KEY, FORM_FILES_REFUSAL_CODE, parseFormFileRefs, splitFormFieldData } from "../model/form-request.js";
43
+ import { attachFormFiles } from "./form-submit-files.js";
41
44
  import { incrementFormStats } from "./increment-form-stats.js";
42
45
  import { NO_CLIENT_ADDRESS_BUCKET, readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
43
46
  const MAX_FIELDS = 20;
@@ -425,16 +428,32 @@ export async function POST(request) {
425
428
  * review never read — a marketplace plugin's frame, a hand-built request
426
429
  * — could still post one here. Such a field is dropped, never stored,
427
430
  * never forwarded to a workflow or a contact.
428
- */ const sanitizedFields = {};
431
+ */ const postedFields = {};
429
432
  for (const [key, value] of Object.entries(fields)){
430
433
  if (isCredentialFieldName(String(key))) continue;
431
- sanitizedFields[String(key).slice(0, 64)] = String(value).slice(0, 2000);
434
+ postedFields[String(key).slice(0, 64)] = String(value).slice(0, 2000);
432
435
  }
436
+ /*
437
+ * THE ANSWERS, APART FROM THE MACHINE VALUES BESIDE THEM (AGL-4098). A
438
+ * field such as a product and its options posts a readable line under its
439
+ * name and a value only the plugin that drew it reads under
440
+ * `{name}__data`. The line is the answer every reader shows; the value is
441
+ * kept as `fieldData`, never shown, emailed or searched.
442
+ */ const { answers: sanitizedFields, fieldData } = splitFormFieldData(postedFields);
433
443
  if (!Object.keys(sanitizedFields).length) {
434
444
  return json({
435
445
  error: 'Invalid submission'
436
446
  }, 400);
437
447
  }
448
+ // The files the page sent, by id (AGL-4098): shape only here; each is
449
+ // checked against the verified form below, before anything is written.
450
+ const fileRefs = parseFormFileRefs(payload[FORM_FILES_BODY_KEY]);
451
+ if (fileRefs && 'error' in fileRefs) {
452
+ return json({
453
+ error: fileRefs.error,
454
+ code: FORM_FILES_REFUSAL_CODE
455
+ }, 400);
456
+ }
438
457
  /*
439
458
  * The bound form entity (`docs/specs/reusable-forms.md` §2c).
440
459
  *
@@ -508,6 +527,36 @@ export async function POST(request) {
508
527
  * affirmative value.
509
528
  */ const formFieldDecls = Array.isArray(form == null ? void 0 : form.get('fields')) ? form == null ? void 0 : form.get('fields') : [];
510
529
  /*
530
+ * THE FILES, each read back from the scope of the key the page minted
531
+ * and held to the field that asked for it (`form-submit-files.ts`). A
532
+ * file that did not arrive refuses the submission here, before it is
533
+ * stored or counted; the files that did become the field's answer by
534
+ * name. The upload pipeline loads only for a submission that has files.
535
+ */ let attached = null;
536
+ if (fileRefs) {
537
+ var _ref2;
538
+ const checked = await attachFormFiles({
539
+ firestore,
540
+ hostId,
541
+ formId: (_ref2 = form == null ? void 0 : form.id) != null ? _ref2 : null,
542
+ decls: formFieldDecls,
543
+ refs: fileRefs,
544
+ uploads: (await import("./form-uploads.js")).formUploadCalls()
545
+ });
546
+ if ('error' in checked) {
547
+ return json({
548
+ error: checked.error,
549
+ code: FORM_FILES_REFUSAL_CODE
550
+ }, checked.status);
551
+ }
552
+ attached = checked;
553
+ Object.assign(sanitizedFields, checked.answers);
554
+ }
555
+ /*
556
+ * WHAT THE FORM ASKS FOR (AGL-4098), off the verified document only: a
557
+ * request body cannot make an ordinary message a quote request.
558
+ */ const formRequest = form ? readFormRequest(form.data()) : null;
559
+ /*
511
560
  * A SIGN-UP form says so on the entity (`optInOnSubmit`): its one purpose
512
561
  * is subscribing, so the submission IS the opt-in. Read off the verified
513
562
  * document only — a request cannot claim it — and only as the literal
@@ -592,7 +641,7 @@ export async function POST(request) {
592
641
  * write, and the `hostIndex` mirror the plan gate resolved through.
593
642
  */ const hostOrgId = hostSnapshot.get('orgId');
594
643
  const submissionOrgId = typeof hostOrgId === 'string' && hostOrgId ? hostOrgId : owningOrg == null ? void 0 : owningOrg.orgId;
595
- const submissionRef = await hostRef.collection('formSubmissions').add(_extends({}, submissionOrgId ? {
644
+ const submissionData = _extends({}, submissionOrgId ? {
596
645
  orgId: submissionOrgId
597
646
  } : {}, {
598
647
  hostId
@@ -611,7 +660,33 @@ export async function POST(request) {
611
660
  createdAt: FieldValue.serverTimestamp()
612
661
  }, rate.degraded ? {
613
662
  rateDegraded: true
614
- } : {}));
663
+ } : {}, (attached == null ? void 0 : attached.files.length) ? {
664
+ files: attached.files
665
+ } : {}, formRequest ? {
666
+ request: formRequest
667
+ } : {}, Object.keys(fieldData).length ? {
668
+ fieldData
669
+ } : {});
670
+ /*
671
+ * A submission with files takes the key its files were sent under as its
672
+ * id, so they are always at `form-file/{submissionId}`. `create` refuses a
673
+ * key already used: a page that sends twice is answered as received, and
674
+ * nothing is written over.
675
+ */ let submissionRef;
676
+ if (attached) {
677
+ submissionRef = hostRef.collection('formSubmissions').doc(attached.key);
678
+ try {
679
+ await submissionRef.create(submissionData);
680
+ } catch (error) {
681
+ if ((error == null ? void 0 : error.code) === 6) return json({
682
+ received: true
683
+ });
684
+ throw error;
685
+ }
686
+ await attached.release();
687
+ } else {
688
+ submissionRef = await hostRef.collection('formSubmissions').add(submissionData);
689
+ }
615
690
  // Contacts ingestion (AGL-197): forms don't guarantee an email field —
616
691
  // best-effort extraction; never blocks the submission.
617
692
  const contactEmail = extractEmailFromFields(sanitizedFields);
@@ -684,7 +759,7 @@ export async function POST(request) {
684
759
  containerIds: filedUnder
685
760
  }) : Promise.resolve(null);
686
761
  if (contactEmail) {
687
- var _ref2, _sanitizedFields_name, _captured_sourceAdded;
762
+ var _ref3, _sanitizedFields_name, _captured_sourceAdded;
688
763
  var _form_get1;
689
764
  /*
690
765
  * WHICH RECORD THE PERSON LANDS ON is the record system's decision
@@ -711,7 +786,7 @@ export async function POST(request) {
711
786
  * costs the capture nothing — and refusing to record the person over
712
787
  * it would turn a lookup failure into a lost contact, silently, which
713
788
  * is the failure this whole seam is arranged to avoid.
714
- */ orgId: (_ref2 = owningOrg == null ? void 0 : owningOrg.orgId) != null ? _ref2 : '',
789
+ */ orgId: (_ref3 = owningOrg == null ? void 0 : owningOrg.orgId) != null ? _ref3 : '',
715
790
  hostId,
716
791
  identity: {
717
792
  email: contactEmail,
@@ -848,7 +923,7 @@ export async function POST(request) {
848
923
  */ const alertPath = typeof path === 'string' ? path.slice(0, 500) : '';
849
924
  const notifyingManagers = notifyHostManagers(hostId, _extends({
850
925
  type: 'content.formSubmission',
851
- title: `New form submission — ${resolvedFormName}`,
926
+ title: formRequest ? `New quote request — ${resolvedFormName}` : `New form submission — ${resolvedFormName}`,
852
927
  body: [
853
928
  `Someone submitted “${resolvedFormName}” on {site}` + (alertPath ? ` (page ${alertPath}).` : '.'),
854
929
  ...conversionDescriptionSentences(await describing)
@@ -923,7 +998,40 @@ export async function POST(request) {
923
998
  }, SITE_JOURNEY_ID_PATTERN.test(String((_payload_SITE_JOURNEY_SUBMISSION_FIELD = payload[SITE_JOURNEY_SUBMISSION_FIELD]) != null ? _payload_SITE_JOURNEY_SUBMISSION_FIELD : '')) ? {
924
999
  journeyId: String(payload[SITE_JOURNEY_SUBMISSION_FIELD])
925
1000
  } : {}));
1001
+ /*
1002
+ * THE CONFIRMATION TO THE PERSON (AGL-4098), for a form set to send one
1003
+ * and a submission that named an address: what they sent and what
1004
+ * happens next, from the site, in its theme. It starts the conversation
1005
+ * the business's answer replies into, kept on the submission as
1006
+ * `emailThread`. Loaded only here; it never fails the submission, and it
1007
+ * is awaited for the reason the managers' alert is.
1008
+ */ const confirming = form && contactEmail && formSendsConfirmation(form.data()) ? import("./form-confirmation-email.js").then(({ sendFormConfirmation })=>{
1009
+ var _hostSnapshot_data, _ref;
1010
+ return sendFormConfirmation({
1011
+ hostId,
1012
+ host: (_hostSnapshot_data = hostSnapshot.data()) != null ? _hostSnapshot_data : {},
1013
+ org: orgBilling != null ? orgBilling : null,
1014
+ to: contactEmail,
1015
+ request: formRequest,
1016
+ answers: sanitizedFields,
1017
+ decls: formFieldDecls,
1018
+ consentFieldName: form.get('consentFieldName') ? String(form.get('consentFieldName')) : null,
1019
+ fileNames: ((_ref = attached == null ? void 0 : attached.files) != null ? _ref : []).map((file)=>file.name),
1020
+ atMs: submittedAtMs
1021
+ });
1022
+ }).then(async (sent)=>{
1023
+ if (!sent.sent) return;
1024
+ await submissionRef.update({
1025
+ emailThread: sent.thread,
1026
+ confirmation: {
1027
+ to: contactEmail,
1028
+ sentAtMs: submittedAtMs,
1029
+ messageId: sent.messageId
1030
+ }
1031
+ });
1032
+ }).catch((error)=>console.error('form confirmation not recorded', error)) : null;
926
1033
  await notifyingManagers;
1034
+ await confirming;
927
1035
  return json({
928
1036
  received: true,
929
1037
  alerts