@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.
- package/README.md +11 -1
- package/package.json +14 -14
- package/src/lib/components/form-detail-card.js +122 -2
- package/src/lib/components/form-detail-card.js.map +1 -1
- package/src/lib/components/form-file-upload-body.d.ts +32 -0
- package/src/lib/components/form-file-upload-body.js +349 -0
- package/src/lib/components/form-file-upload-body.js.map +1 -0
- package/src/lib/components/form-file-upload.d.ts +39 -0
- package/src/lib/components/form-file-upload.js +175 -0
- package/src/lib/components/form-file-upload.js.map +1 -0
- package/src/lib/components/form-upload-context.d.ts +31 -0
- package/src/lib/components/form-upload-context.js +19 -0
- package/src/lib/components/form-upload-context.js.map +1 -0
- package/src/lib/components/form.js +48 -4
- package/src/lib/components/form.js.map +1 -1
- package/src/lib/declarations.console-server.js +14 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/declarations.server.js +18 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/form-request.d.ts +102 -0
- package/src/lib/model/form-request.js +187 -0
- package/src/lib/model/form-request.js.map +1 -0
- package/src/lib/server/form-confirmation-email.d.ts +70 -0
- package/src/lib/server/form-confirmation-email.js +194 -0
- package/src/lib/server/form-confirmation-email.js.map +1 -0
- package/src/lib/server/form-submit-files.d.ts +42 -0
- package/src/lib/server/form-submit-files.js +98 -0
- package/src/lib/server/form-submit-files.js.map +1 -0
- package/src/lib/server/form-submit.js +115 -7
- package/src/lib/server/form-submit.js.map +1 -1
- package/src/lib/server/form-upload-sweep.d.ts +30 -0
- package/src/lib/server/form-upload-sweep.js +83 -0
- package/src/lib/server/form-upload-sweep.js.map +1 -0
- package/src/lib/server/form-upload.d.ts +41 -0
- package/src/lib/server/form-upload.js +226 -0
- package/src/lib/server/form-upload.js.map +1 -0
- package/src/lib/server/form-uploads.d.ts +34 -0
- package/src/lib/server/form-uploads.js +29 -0
- package/src/lib/server/form-uploads.js.map +1 -0
- package/src/lib/server/submission-access.d.ts +38 -0
- package/src/lib/server/submission-access.js +37 -0
- package/src/lib/server/submission-access.js.map +1 -0
- package/src/lib/server/submission-facts.d.ts +37 -0
- package/src/lib/server/submission-facts.js +227 -0
- package/src/lib/server/submission-facts.js.map +1 -0
- package/src/lib/server/submission-files.d.ts +41 -0
- package/src/lib/server/submission-files.js +126 -0
- package/src/lib/server/submission-files.js.map +1 -0
- package/src/lib/server.js +22 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/site.js +8 -0
- package/src/lib/site.js.map +1 -1
- package/src/lib/tenant-emails.d.ts +29 -0
- package/src/lib/tenant-emails.js +125 -0
- package/src/lib/tenant-emails.js.map +1 -0
- package/src/lib/testing/stand-in-firestore.d.ts +27 -0
- package/src/lib/testing/stand-in-firestore.js +128 -0
- package/src/lib/testing/stand-in-firestore.js.map +1 -0
- package/src/lib/utils/form-confirmation-content.d.ts +47 -0
- package/src/lib/utils/form-confirmation-content.js +109 -0
- package/src/lib/utils/form-confirmation-content.js.map +1 -0
|
@@ -0,0 +1,227 @@
|
|
|
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 { extractEmailFromFields } from "@aglyn/aglyn/app-utils/contacts";
|
|
17
|
+
import { visitorUploadFinalPath } from "@aglyn/aglyn/app-utils/visitor-upload";
|
|
18
|
+
import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
19
|
+
import { formFileScope, FORM_SUBMISSION_FACTS_RESOURCE, readFormSubmissionFiles, readSubmissionRequest, readSubmissionThread } from "../model/form-request.js";
|
|
20
|
+
import { memberMayReadSubmissions } from "./submission-access.js";
|
|
21
|
+
/*==========================================
|
|
22
|
+
* A FORM SUBMISSION'S FACTS, FOR ANOTHER PLUGIN (AGL-4098), on the core's
|
|
23
|
+
* record-facts seam under {@link FORM_SUBMISSION_FACTS_RESOURCE}.
|
|
24
|
+
*
|
|
25
|
+
* Commerce starts a quote from a quote request in the Inbox, and must not read
|
|
26
|
+
* this plugin's collection to do it. It asks here, for the member it has
|
|
27
|
+
* verified, and gets:
|
|
28
|
+
*
|
|
29
|
+
* record: 'formSubmission'
|
|
30
|
+
* hostId, formId (null when no form entity filed it), formName, createdAtMs
|
|
31
|
+
* request: { kind: 'quote' } | null
|
|
32
|
+
* person: { name, email, phone, company } — each '' when the form had none
|
|
33
|
+
* capturedRecord: { kind: 'lead' | 'contact', id } | null — the person the
|
|
34
|
+
* CRM filed the submission as, when it filed one
|
|
35
|
+
* message: the request's own words (a message, details or notes field,
|
|
36
|
+
* else the form's first multi-line field), or ''
|
|
37
|
+
* answers: [{ field, label, value }] in the order they were sent
|
|
38
|
+
* fieldData: { [field]: string } — machine values a field posted beside its
|
|
39
|
+
* answer (a product and its options), for the plugin that wrote them
|
|
40
|
+
* files: [{ id, field, name, contentType, size, path }] — `path` is the
|
|
41
|
+
* private object, for a server that streams it behind its own gate;
|
|
42
|
+
* never to be sent to a browser
|
|
43
|
+
* emailThread: the conversation the confirmation started, or null
|
|
44
|
+
*
|
|
45
|
+
* Read on the rules the Inbox reads on: the site must belong to the
|
|
46
|
+
* organization asked about, and the member must be one who may read the
|
|
47
|
+
* site's submissions (`memberMayReadSubmissions`). Nothing here writes.
|
|
48
|
+
*=========================================*/ export { FORM_SUBMISSION_FACTS_RESOURCE };
|
|
49
|
+
export function defaultSubmissionFactsDeps() {
|
|
50
|
+
const firestore = ()=>firebaseAdmin.app().firestore();
|
|
51
|
+
return {
|
|
52
|
+
firestore,
|
|
53
|
+
orgMember: async (orgId, uid)=>{
|
|
54
|
+
const snapshot = await firestore().collection('orgs').doc(orgId).collection('members').doc(uid).get();
|
|
55
|
+
return snapshot.exists ? snapshot.data() : null;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const MESSAGE_KEYS = [
|
|
60
|
+
'message',
|
|
61
|
+
'details',
|
|
62
|
+
'description',
|
|
63
|
+
'notes',
|
|
64
|
+
'comments',
|
|
65
|
+
'comment',
|
|
66
|
+
'project',
|
|
67
|
+
'request'
|
|
68
|
+
];
|
|
69
|
+
/** The first of `keys` the person filled in, trimmed. */ function firstOf(fields, keys) {
|
|
70
|
+
const lower = new Map(Object.keys(fields).map((key)=>[
|
|
71
|
+
key.toLowerCase(),
|
|
72
|
+
key
|
|
73
|
+
]));
|
|
74
|
+
for (const key of keys){
|
|
75
|
+
var _fields_found;
|
|
76
|
+
const found = lower.get(key.toLowerCase());
|
|
77
|
+
const value = found ? String((_fields_found = fields[found]) != null ? _fields_found : '').trim() : '';
|
|
78
|
+
if (value) return value;
|
|
79
|
+
}
|
|
80
|
+
return '';
|
|
81
|
+
}
|
|
82
|
+
/** Who sent it, as far as the answers say. */ export function submissionPerson(fields) {
|
|
83
|
+
var _extractEmailFromFields;
|
|
84
|
+
const first = firstOf(fields, [
|
|
85
|
+
'firstName',
|
|
86
|
+
'first_name',
|
|
87
|
+
'givenName'
|
|
88
|
+
]);
|
|
89
|
+
const last = firstOf(fields, [
|
|
90
|
+
'lastName',
|
|
91
|
+
'last_name',
|
|
92
|
+
'familyName'
|
|
93
|
+
]);
|
|
94
|
+
return {
|
|
95
|
+
name: (firstOf(fields, [
|
|
96
|
+
'name',
|
|
97
|
+
'fullName',
|
|
98
|
+
'full_name',
|
|
99
|
+
'yourName'
|
|
100
|
+
]) || [
|
|
101
|
+
first,
|
|
102
|
+
last
|
|
103
|
+
].filter(Boolean).join(' ')).slice(0, 200),
|
|
104
|
+
email: ((_extractEmailFromFields = extractEmailFromFields(fields)) != null ? _extractEmailFromFields : '').slice(0, 200),
|
|
105
|
+
phone: firstOf(fields, [
|
|
106
|
+
'phone',
|
|
107
|
+
'phoneNumber',
|
|
108
|
+
'tel',
|
|
109
|
+
'mobile',
|
|
110
|
+
'telephone'
|
|
111
|
+
]).slice(0, 40),
|
|
112
|
+
company: firstOf(fields, [
|
|
113
|
+
'company',
|
|
114
|
+
'companyName',
|
|
115
|
+
'business',
|
|
116
|
+
'businessName',
|
|
117
|
+
'organization'
|
|
118
|
+
]).slice(0, 200)
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/** The request's own words: a message field, else the form's first multi-line field. */ export function submissionMessage(fields, decls) {
|
|
122
|
+
const named = firstOf(fields, MESSAGE_KEYS);
|
|
123
|
+
if (named) return named.slice(0, 5000);
|
|
124
|
+
const multiline = decls.find((decl)=>{
|
|
125
|
+
var _fields_decl_fieldName;
|
|
126
|
+
return (decl == null ? void 0 : decl.fieldType) === 'textarea' && String((_fields_decl_fieldName = fields[decl.fieldName]) != null ? _fields_decl_fieldName : '').trim();
|
|
127
|
+
});
|
|
128
|
+
return multiline ? String(fields[multiline.fieldName]).trim().slice(0, 5000) : '';
|
|
129
|
+
}
|
|
130
|
+
/** The lead or contact the submission was filed as, or null. */ function capturedRecordOf(raw) {
|
|
131
|
+
const record = raw != null ? raw : null;
|
|
132
|
+
return ((record == null ? void 0 : record.kind) === 'lead' || (record == null ? void 0 : record.kind) === 'contact') && typeof record.id === 'string' && record.id ? {
|
|
133
|
+
kind: record.kind,
|
|
134
|
+
id: record.id
|
|
135
|
+
} : null;
|
|
136
|
+
}
|
|
137
|
+
export async function readSubmissionFacts(deps, request) {
|
|
138
|
+
var _host_get, _ref, _data_fields, _data_fieldData, _data_formName;
|
|
139
|
+
const { hostId, id, orgId, uid } = request;
|
|
140
|
+
if (!hostId || !id) return {
|
|
141
|
+
ok: false,
|
|
142
|
+
status: 400,
|
|
143
|
+
error: 'A submission is read under its site.'
|
|
144
|
+
};
|
|
145
|
+
const firestore = deps.firestore();
|
|
146
|
+
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
147
|
+
const [host, submission] = await Promise.all([
|
|
148
|
+
hostRef.get(),
|
|
149
|
+
hostRef.collection('formSubmissions').doc(id).get()
|
|
150
|
+
]);
|
|
151
|
+
if (!host.exists || String((_host_get = host.get('orgId')) != null ? _host_get : '') !== orgId) {
|
|
152
|
+
return {
|
|
153
|
+
ok: false,
|
|
154
|
+
status: 404,
|
|
155
|
+
error: 'That submission is no longer in the Inbox.'
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
const allowed = await memberMayReadSubmissions({
|
|
159
|
+
uid,
|
|
160
|
+
staff: request.staff === true,
|
|
161
|
+
host,
|
|
162
|
+
orgId: String((_ref = submission.get == null ? void 0 : submission.get.call(submission, 'orgId')) != null ? _ref : '') || orgId,
|
|
163
|
+
orgMember: deps.orgMember
|
|
164
|
+
});
|
|
165
|
+
if (!allowed) return {
|
|
166
|
+
ok: false,
|
|
167
|
+
status: 403,
|
|
168
|
+
error: 'You can’t read this site’s submissions.'
|
|
169
|
+
};
|
|
170
|
+
if (!submission.exists) return {
|
|
171
|
+
ok: false,
|
|
172
|
+
status: 404,
|
|
173
|
+
error: 'That submission is no longer in the Inbox.'
|
|
174
|
+
};
|
|
175
|
+
const data = submission.data();
|
|
176
|
+
const fields = Object.fromEntries(Object.entries((_data_fields = data['fields']) != null ? _data_fields : {}).map(([key, value])=>[
|
|
177
|
+
key,
|
|
178
|
+
String(value != null ? value : '')
|
|
179
|
+
]));
|
|
180
|
+
const formId = typeof data['formId'] === 'string' && data['formId'] ? data['formId'] : null;
|
|
181
|
+
const form = formId ? await hostRef.collection('forms').doc(formId).get() : null;
|
|
182
|
+
const decls = Array.isArray(form == null ? void 0 : form.get('fields')) ? form == null ? void 0 : form.get('fields') : [];
|
|
183
|
+
const label = (field)=>{
|
|
184
|
+
var _decls_find_label, _decls_find;
|
|
185
|
+
return ((_decls_find = decls.find((decl)=>(decl == null ? void 0 : decl.fieldName) === field)) == null ? void 0 : (_decls_find_label = _decls_find.label) == null ? void 0 : _decls_find_label.trim()) || field;
|
|
186
|
+
};
|
|
187
|
+
const createdAt = data['createdAt'];
|
|
188
|
+
const scope = formFileScope(hostId, id);
|
|
189
|
+
const fieldData = Object.fromEntries(Object.entries((_data_fieldData = data['fieldData']) != null ? _data_fieldData : {}).filter((entry)=>typeof entry[1] === 'string').map(([key, value])=>[
|
|
190
|
+
key,
|
|
191
|
+
value.slice(0, 2000)
|
|
192
|
+
]));
|
|
193
|
+
return {
|
|
194
|
+
ok: true,
|
|
195
|
+
facts: {
|
|
196
|
+
record: 'formSubmission',
|
|
197
|
+
hostId,
|
|
198
|
+
formId,
|
|
199
|
+
formName: String((_data_formName = data['formName']) != null ? _data_formName : '') || 'Form',
|
|
200
|
+
createdAtMs: typeof (createdAt == null ? void 0 : createdAt.toMillis) === 'function' ? createdAt.toMillis() : null,
|
|
201
|
+
request: readSubmissionRequest(data['request']),
|
|
202
|
+
person: submissionPerson(fields),
|
|
203
|
+
capturedRecord: capturedRecordOf(data['capturedRecord']),
|
|
204
|
+
message: submissionMessage(fields, decls),
|
|
205
|
+
answers: Object.entries(fields).map(([field, value])=>({
|
|
206
|
+
field,
|
|
207
|
+
label: label(field),
|
|
208
|
+
value
|
|
209
|
+
})),
|
|
210
|
+
fieldData,
|
|
211
|
+
files: readFormSubmissionFiles(data['files']).map((file)=>({
|
|
212
|
+
id: file.id,
|
|
213
|
+
field: file.field,
|
|
214
|
+
name: file.name,
|
|
215
|
+
contentType: file.contentType,
|
|
216
|
+
size: file.size,
|
|
217
|
+
path: visitorUploadFinalPath(scope, file.id)
|
|
218
|
+
})),
|
|
219
|
+
emailThread: readSubmissionThread(data['emailThread'])
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
/** The reader as the seam registers it; its module loads with the first read. */ export const formSubmissionFactsReader = {
|
|
224
|
+
read: (request)=>readSubmissionFacts(defaultSubmissionFactsDeps(), request)
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
//# sourceMappingURL=submission-facts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/server/submission-facts.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 { extractEmailFromFields } from '@aglyn/aglyn/app-utils/contacts'\nimport type { FormFieldDecl } from '@aglyn/aglyn/app-utils/forms'\nimport { visitorUploadFinalPath } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport type {\n PluginRecordFactsRead,\n PluginRecordFactsReader,\n PluginRecordFactsRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-facts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport {\n formFileScope,\n FORM_SUBMISSION_FACTS_RESOURCE,\n readFormSubmissionFiles,\n readSubmissionRequest,\n readSubmissionThread,\n} from '../model/form-request'\nimport { memberMayReadSubmissions } from './submission-access'\n\n/*==========================================\n * A FORM SUBMISSION'S FACTS, FOR ANOTHER PLUGIN (AGL-4098), on the core's\n * record-facts seam under {@link FORM_SUBMISSION_FACTS_RESOURCE}.\n *\n * Commerce starts a quote from a quote request in the Inbox, and must not read\n * this plugin's collection to do it. It asks here, for the member it has\n * verified, and gets:\n *\n * record: 'formSubmission'\n * hostId, formId (null when no form entity filed it), formName, createdAtMs\n * request: { kind: 'quote' } | null\n * person: { name, email, phone, company } — each '' when the form had none\n * capturedRecord: { kind: 'lead' | 'contact', id } | null — the person the\n * CRM filed the submission as, when it filed one\n * message: the request's own words (a message, details or notes field,\n * else the form's first multi-line field), or ''\n * answers: [{ field, label, value }] in the order they were sent\n * fieldData: { [field]: string } — machine values a field posted beside its\n * answer (a product and its options), for the plugin that wrote them\n * files: [{ id, field, name, contentType, size, path }] — `path` is the\n * private object, for a server that streams it behind its own gate;\n * never to be sent to a browser\n * emailThread: the conversation the confirmation started, or null\n *\n * Read on the rules the Inbox reads on: the site must belong to the\n * organization asked about, and the member must be one who may read the\n * site's submissions (`memberMayReadSubmissions`). Nothing here writes.\n *=========================================*/\n\nexport { FORM_SUBMISSION_FACTS_RESOURCE }\n\nexport interface SubmissionFactsDeps {\n firestore(): FirebaseFirestore.Firestore\n orgMember(orgId: string, uid: string): Promise<Record<string, unknown> | null>\n}\n\nexport function defaultSubmissionFactsDeps(): SubmissionFactsDeps {\n const firestore = () => firebaseAdmin.app().firestore()\n return {\n firestore,\n orgMember: async (orgId, uid) => {\n const snapshot = await firestore().collection('orgs').doc(orgId).collection('members').doc(uid).get()\n return snapshot.exists ? (snapshot.data() as Record<string, unknown>) : null\n },\n }\n}\n\nconst MESSAGE_KEYS = ['message', 'details', 'description', 'notes', 'comments', 'comment', 'project', 'request']\n\n/** The first of `keys` the person filled in, trimmed. */\nfunction firstOf(fields: Record<string, string>, keys: readonly string[]): string {\n const lower = new Map(Object.keys(fields).map((key) => [key.toLowerCase(), key]))\n for (const key of keys) {\n const found = lower.get(key.toLowerCase())\n const value = found ? String(fields[found] ?? '').trim() : ''\n if (value) return value\n }\n return ''\n}\n\n/** Who sent it, as far as the answers say. */\nexport function submissionPerson(fields: Record<string, string>): {\n name: string\n email: string\n phone: string\n company: string\n} {\n const first = firstOf(fields, ['firstName', 'first_name', 'givenName'])\n const last = firstOf(fields, ['lastName', 'last_name', 'familyName'])\n return {\n name: (firstOf(fields, ['name', 'fullName', 'full_name', 'yourName']) || [first, last].filter(Boolean).join(' ')).slice(0, 200),\n email: (extractEmailFromFields(fields) ?? '').slice(0, 200),\n phone: firstOf(fields, ['phone', 'phoneNumber', 'tel', 'mobile', 'telephone']).slice(0, 40),\n company: firstOf(fields, ['company', 'companyName', 'business', 'businessName', 'organization']).slice(0, 200),\n }\n}\n\n/** The request's own words: a message field, else the form's first multi-line field. */\nexport function submissionMessage(fields: Record<string, string>, decls: readonly FormFieldDecl[]): string {\n const named = firstOf(fields, MESSAGE_KEYS)\n if (named) return named.slice(0, 5000)\n const multiline = decls.find((decl) => decl?.fieldType === 'textarea' && String(fields[decl.fieldName] ?? '').trim())\n return multiline ? String(fields[multiline.fieldName]).trim().slice(0, 5000) : ''\n}\n\n/** The lead or contact the submission was filed as, or null. */\nfunction capturedRecordOf(raw: unknown): { kind: 'lead' | 'contact'; id: string } | null {\n const record = (raw ?? null) as { kind?: unknown; id?: unknown } | null\n return (record?.kind === 'lead' || record?.kind === 'contact') && typeof record.id === 'string' && record.id\n ? { kind: record.kind, id: record.id }\n : null\n}\n\nexport async function readSubmissionFacts(\n deps: SubmissionFactsDeps,\n request: PluginRecordFactsRequest,\n): Promise<PluginRecordFactsRead> {\n const { hostId, id, orgId, uid } = request\n if (!hostId || !id) return { ok: false, status: 400, error: 'A submission is read under its site.' }\n const firestore = deps.firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [host, submission] = await Promise.all([hostRef.get(), hostRef.collection('formSubmissions').doc(id).get()])\n if (!host.exists || String(host.get('orgId') ?? '') !== orgId) {\n return { ok: false, status: 404, error: 'That submission is no longer in the Inbox.' }\n }\n const allowed = await memberMayReadSubmissions({\n uid,\n staff: request.staff === true,\n host,\n orgId: String(submission.get?.('orgId') ?? '') || orgId,\n orgMember: deps.orgMember,\n })\n if (!allowed) return { ok: false, status: 403, error: 'You can’t read this site’s submissions.' }\n if (!submission.exists) return { ok: false, status: 404, error: 'That submission is no longer in the Inbox.' }\n\n const data = submission.data() as Record<string, unknown>\n const fields = Object.fromEntries(\n Object.entries((data['fields'] ?? {}) as Record<string, unknown>).map(([key, value]) => [key, String(value ?? '')]),\n )\n const formId = typeof data['formId'] === 'string' && data['formId'] ? data['formId'] : null\n const form = formId ? await hostRef.collection('forms').doc(formId).get() : null\n const decls = Array.isArray(form?.get('fields')) ? (form?.get('fields') as FormFieldDecl[]) : []\n const label = (field: string) => decls.find((decl) => decl?.fieldName === field)?.label?.trim() || field\n const createdAt = data['createdAt'] as { toMillis?: () => number } | null | undefined\n const scope = formFileScope(hostId, id)\n const fieldData = Object.fromEntries(\n Object.entries((data['fieldData'] ?? {}) as Record<string, unknown>)\n .filter((entry): entry is [string, string] => typeof entry[1] === 'string')\n .map(([key, value]) => [key, value.slice(0, 2000)]),\n )\n return {\n ok: true,\n facts: {\n record: 'formSubmission',\n hostId,\n formId,\n formName: String(data['formName'] ?? '') || 'Form',\n createdAtMs: typeof createdAt?.toMillis === 'function' ? createdAt.toMillis() : null,\n request: readSubmissionRequest(data['request']),\n person: submissionPerson(fields),\n capturedRecord: capturedRecordOf(data['capturedRecord']),\n message: submissionMessage(fields, decls),\n answers: Object.entries(fields).map(([field, value]) => ({ field, label: label(field), value })),\n fieldData,\n files: readFormSubmissionFiles(data['files']).map((file) => ({\n id: file.id,\n field: file.field,\n name: file.name,\n contentType: file.contentType,\n size: file.size,\n path: visitorUploadFinalPath(scope, file.id),\n })),\n emailThread: readSubmissionThread(data['emailThread']),\n },\n }\n}\n\n/** The reader as the seam registers it; its module loads with the first read. */\nexport const formSubmissionFactsReader: PluginRecordFactsReader = {\n read: (request) => readSubmissionFacts(defaultSubmissionFactsDeps(), request),\n}\n"],"names":["extractEmailFromFields","visitorUploadFinalPath","firebaseAdmin","formFileScope","FORM_SUBMISSION_FACTS_RESOURCE","readFormSubmissionFiles","readSubmissionRequest","readSubmissionThread","memberMayReadSubmissions","defaultSubmissionFactsDeps","firestore","app","orgMember","orgId","uid","snapshot","collection","doc","get","exists","data","MESSAGE_KEYS","firstOf","fields","keys","lower","Map","Object","map","key","toLowerCase","found","value","String","trim","submissionPerson","first","last","name","filter","Boolean","join","slice","email","phone","company","submissionMessage","decls","named","multiline","find","decl","fieldType","fieldName","capturedRecordOf","raw","record","kind","id","readSubmissionFacts","deps","request","host","hostId","ok","status","error","hostRef","submission","Promise","all","allowed","staff","fromEntries","entries","formId","form","Array","isArray","label","field","createdAt","scope","fieldData","entry","facts","formName","createdAtMs","toMillis","person","capturedRecord","message","answers","files","file","contentType","size","path","emailThread","formSubmissionFactsReader","read"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,kCAAiC;AAExE,SAASC,sBAAsB,QAAQ,wCAAuC;AAM9E,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SACEC,aAAa,EACbC,8BAA8B,EAC9BC,uBAAuB,EACvBC,qBAAqB,EACrBC,oBAAoB,QACf,2BAAuB;AAC9B,SAASC,wBAAwB,QAAQ,yBAAqB;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA2B2C,GAE3C,SAASJ,8BAA8B,GAAE;AAOzC,OAAO,SAASK;IACd,MAAMC,YAAY,IAAMR,cAAcS,GAAG,GAAGD,SAAS;IACrD,OAAO;QACLA;QACAE,WAAW,OAAOC,OAAOC;YACvB,MAAMC,WAAW,MAAML,YAAYM,UAAU,CAAC,QAAQC,GAAG,CAACJ,OAAOG,UAAU,CAAC,WAAWC,GAAG,CAACH,KAAKI,GAAG;YACnG,OAAOH,SAASI,MAAM,GAAIJ,SAASK,IAAI,KAAiC;QAC1E;IACF;AACF;AAEA,MAAMC,eAAe;IAAC;IAAW;IAAW;IAAe;IAAS;IAAY;IAAW;IAAW;CAAU;AAEhH,uDAAuD,GACvD,SAASC,QAAQC,MAA8B,EAAEC,IAAuB;IACtE,MAAMC,QAAQ,IAAIC,IAAIC,OAAOH,IA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AoBlD,8BAA8BoD;AACvE,EAAC"}
|
|
@@ -0,0 +1,41 @@
|
|
|
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 { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server';
|
|
18
|
+
import type { FormUploadCalls } from './form-uploads';
|
|
19
|
+
export interface SubmissionFilesDeps {
|
|
20
|
+
verifyIdToken(token: string): Promise<{
|
|
21
|
+
uid: string;
|
|
22
|
+
staff?: unknown;
|
|
23
|
+
}>;
|
|
24
|
+
firestore(): FirebaseFirestore.Firestore;
|
|
25
|
+
uploads(): Promise<FormUploadCalls>;
|
|
26
|
+
orgMember(orgId: string, uid: string): Promise<Record<string, unknown> | null>;
|
|
27
|
+
}
|
|
28
|
+
export declare function defaultSubmissionFilesDeps(): SubmissionFilesDeps;
|
|
29
|
+
type Outcome = {
|
|
30
|
+
status: number;
|
|
31
|
+
body: Record<string, unknown>;
|
|
32
|
+
file?: {
|
|
33
|
+
path: string;
|
|
34
|
+
name: string;
|
|
35
|
+
contentType: string;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
export declare function handleSubmissionFiles(deps: SubmissionFilesDeps, req: PluginApiRequest): Promise<Outcome>;
|
|
39
|
+
/** `POST /api/forms/submission-file`. */
|
|
40
|
+
export declare const submissionFilesHandler: PluginApiHandler;
|
|
41
|
+
export {};
|
|
@@ -0,0 +1,126 @@
|
|
|
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 { visitorUploadFinalPath } from "@aglyn/aglyn/app-utils/visitor-upload";
|
|
17
|
+
import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
18
|
+
import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
19
|
+
import { formFileScope, readFormSubmissionFiles } from "../model/form-request.js";
|
|
20
|
+
import { memberMayReadSubmissions } from "./submission-access.js";
|
|
21
|
+
export function defaultSubmissionFilesDeps() {
|
|
22
|
+
const firestore = ()=>firebaseAdmin.app().firestore();
|
|
23
|
+
return {
|
|
24
|
+
verifyIdToken: (token)=>firebaseAdmin.app().auth().verifyIdToken(token),
|
|
25
|
+
firestore,
|
|
26
|
+
uploads: async ()=>(await import("./form-uploads.js")).formUploadCalls(),
|
|
27
|
+
orgMember: async (orgId, uid)=>{
|
|
28
|
+
const snapshot = await firestore().collection('orgs').doc(orgId).collection('members').doc(uid).get();
|
|
29
|
+
return snapshot.exists ? snapshot.data() : null;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
const refuse = (status, error)=>({
|
|
34
|
+
status,
|
|
35
|
+
body: {
|
|
36
|
+
error
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
const DOC_ID = /^(?!__.*__$)[^/]{1,128}$/;
|
|
40
|
+
function bodyOf(req) {
|
|
41
|
+
const raw = req.body;
|
|
42
|
+
if (typeof raw === 'string') {
|
|
43
|
+
try {
|
|
44
|
+
const parsed = JSON.parse(raw);
|
|
45
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
46
|
+
} catch (unused) {
|
|
47
|
+
return {};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return raw && typeof raw === 'object' ? raw : {};
|
|
51
|
+
}
|
|
52
|
+
export async function handleSubmissionFiles(deps, req) {
|
|
53
|
+
var _req_headers, _ref, _headers_authorization, _body_action, _body_hostId, _body_submissionId, _submission_get, _host_get;
|
|
54
|
+
if (req.method !== 'POST') return refuse(405, 'Method not allowed');
|
|
55
|
+
const headers = (_req_headers = req.headers) != null ? _req_headers : {};
|
|
56
|
+
const authorization = String((_ref = (_headers_authorization = headers['authorization']) != null ? _headers_authorization : headers['Authorization']) != null ? _ref : '');
|
|
57
|
+
const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : '';
|
|
58
|
+
if (!idToken) return refuse(401, 'Unauthenticated');
|
|
59
|
+
const body = bodyOf(req);
|
|
60
|
+
const action = String((_body_action = body['action']) != null ? _body_action : '');
|
|
61
|
+
const hostId = String((_body_hostId = body['hostId']) != null ? _body_hostId : '');
|
|
62
|
+
const submissionId = String((_body_submissionId = body['submissionId']) != null ? _body_submissionId : '');
|
|
63
|
+
if (!DOC_ID.test(hostId) || !DOC_ID.test(submissionId)) return refuse(400, 'Missing hostId or submissionId');
|
|
64
|
+
let decoded;
|
|
65
|
+
try {
|
|
66
|
+
decoded = await deps.verifyIdToken(idToken);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (!isRefusedIdToken(error)) throw error;
|
|
69
|
+
return refuse(401, 'Unauthenticated');
|
|
70
|
+
}
|
|
71
|
+
const firestore = deps.firestore();
|
|
72
|
+
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
73
|
+
const [host, submission] = await Promise.all([
|
|
74
|
+
hostRef.get(),
|
|
75
|
+
hostRef.collection('formSubmissions').doc(submissionId).get()
|
|
76
|
+
]);
|
|
77
|
+
if (!host.exists) return refuse(404, 'Unknown site');
|
|
78
|
+
const allowed = await memberMayReadSubmissions({
|
|
79
|
+
uid: decoded.uid,
|
|
80
|
+
staff: decoded.staff === true,
|
|
81
|
+
host,
|
|
82
|
+
orgId: submission.exists ? String((_submission_get = submission.get('orgId')) != null ? _submission_get : '') || null : String((_host_get = host.get('orgId')) != null ? _host_get : '') || null,
|
|
83
|
+
orgMember: deps.orgMember
|
|
84
|
+
});
|
|
85
|
+
if (!allowed) return refuse(403, 'You can’t read this site’s submissions.');
|
|
86
|
+
if (action === 'download') {
|
|
87
|
+
var _body_fileId;
|
|
88
|
+
if (!submission.exists) return refuse(404, 'That submission is no longer in the Inbox.');
|
|
89
|
+
const fileId = String((_body_fileId = body['fileId']) != null ? _body_fileId : '');
|
|
90
|
+
const file = readFormSubmissionFiles(submission.get('files')).find((entry)=>entry.id === fileId);
|
|
91
|
+
if (!file) return refuse(404, 'That file is no longer on this submission.');
|
|
92
|
+
return {
|
|
93
|
+
status: 200,
|
|
94
|
+
body: {},
|
|
95
|
+
file: {
|
|
96
|
+
path: visitorUploadFinalPath(formFileScope(hostId, submissionId), file.id),
|
|
97
|
+
name: file.name,
|
|
98
|
+
contentType: file.contentType
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
if (action === 'release') {
|
|
103
|
+
// Only the files of a submission that is gone.
|
|
104
|
+
if (submission.exists) return refuse(409, 'This submission is still in the Inbox.');
|
|
105
|
+
const uploads = await deps.uploads();
|
|
106
|
+
await uploads.removeAll(formFileScope(hostId, submissionId));
|
|
107
|
+
return {
|
|
108
|
+
status: 200,
|
|
109
|
+
body: {
|
|
110
|
+
released: true
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
return refuse(400, 'Unknown action');
|
|
115
|
+
}
|
|
116
|
+
/** `POST /api/forms/submission-file`. */ export const submissionFilesHandler = async (req, res)=>{
|
|
117
|
+
const deps = defaultSubmissionFilesDeps();
|
|
118
|
+
const outcome = await handleSubmissionFiles(deps, req);
|
|
119
|
+
if (outcome.file) {
|
|
120
|
+
const uploads = await deps.uploads();
|
|
121
|
+
return uploads.send(res, outcome.file);
|
|
122
|
+
}
|
|
123
|
+
return res.status(outcome.status).json(outcome.body);
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
//# sourceMappingURL=submission-files.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/server/submission-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 { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { visitorUploadFinalPath } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { formFileScope, readFormSubmissionFiles } from '../model/form-request'\nimport type { FormUploadCalls } from './form-uploads'\nimport { memberMayReadSubmissions } from './submission-access'\n\n/*==========================================\n * A SUBMISSION'S FILES IN THE CONSOLE (AGL-4098): `POST /api/forms/submission-file`.\n *\n * { action: 'download', hostId, submissionId, fileId } → the file, streamed\n * { action: 'release', hostId, submissionId } → { released: true }\n *\n * DOWNLOAD serves one of the files a submission names to a member who may\n * read the site's submissions (`memberMayReadSubmissions`, the Inbox's own\n * read): never a file the submission does not name, and through the shared\n * upload's serving headers (`nosniff`, a sandboxing CSP, a download for\n * anything but the pictures a browser draws safely).\n *\n * RELEASE deletes the files of a submission that is gone. The Inbox deletes a\n * submission from the browser, which cannot reach private storage, so it asks\n * here after the delete; the files go only once the document no longer\n * exists, so nothing a submission still names can be released. A submission\n * removed by the API or a person's erasure releases its files through\n * `host.records.removed` (`declarations.server.ts`) instead.\n *=========================================*/\n\nexport interface SubmissionFilesDeps {\n verifyIdToken(token: string): Promise<{ uid: string; staff?: unknown }>\n firestore(): FirebaseFirestore.Firestore\n uploads(): Promise<FormUploadCalls>\n orgMember(orgId: string, uid: string): Promise<Record<string, unknown> | null>\n}\n\nexport function defaultSubmissionFilesDeps(): SubmissionFilesDeps {\n const firestore = () => firebaseAdmin.app().firestore()\n return {\n verifyIdToken: (token) => firebaseAdmin.app().auth().verifyIdToken(token),\n firestore,\n uploads: async () => (await import('./form-uploads')).formUploadCalls(),\n orgMember: async (orgId, uid) => {\n const snapshot = await firestore().collection('orgs').doc(orgId).collection('members').doc(uid).get()\n return snapshot.exists ? (snapshot.data() as Record<string, unknown>) : null\n },\n }\n}\n\ntype Outcome = { status: number; body: Record<string, unknown>; file?: { path: string; name: string; contentType: string } }\n\nconst refuse = (status: number, error: string): Outcome => ({ status, body: { error } })\nconst DOC_ID = /^(?!__.*__$)[^/]{1,128}$/\n\nfunction bodyOf(req: PluginApiRequest): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}\n}\n\nexport async function handleSubmissionFiles(deps: SubmissionFilesDeps, req: PluginApiRequest): Promise<Outcome> {\n if (req.method !== 'POST') return refuse(405, 'Method not allowed')\n const headers = (req.headers ?? {}) as Record<string, unknown>\n const authorization = String(headers['authorization'] ?? headers['Authorization'] ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!idToken) return refuse(401, 'Unauthenticated')\n const body = bodyOf(req)\n const action = String(body['action'] ?? '')\n const hostId = String(body['hostId'] ?? '')\n const submissionId = String(body['submissionId'] ?? '')\n if (!DOC_ID.test(hostId) || !DOC_ID.test(submissionId)) return refuse(400, 'Missing hostId or submissionId')\n\n let decoded: { uid: string; staff?: unknown }\n try {\n decoded = await deps.verifyIdToken(idToken)\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n return refuse(401, 'Unauthenticated')\n }\n const firestore = deps.firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [host, submission] = await Promise.all([\n hostRef.get(),\n hostRef.collection('formSubmissions').doc(submissionId).get(),\n ])\n if (!host.exists) return refuse(404, 'Unknown site')\n const allowed = await memberMayReadSubmissions({\n uid: decoded.uid,\n staff: decoded.staff === true,\n host,\n orgId: submission.exists ? String(submission.get('orgId') ?? '') || null : String(host.get('orgId') ?? '') || null,\n orgMember: deps.orgMember,\n })\n if (!allowed) return refuse(403, 'You can’t read this site’s submissions.')\n\n if (action === 'download') {\n if (!submission.exists) return refuse(404, 'That submission is no longer in the Inbox.')\n const fileId = String(body['fileId'] ?? '')\n const file = readFormSubmissionFiles(submission.get('files')).find((entry) => entry.id === fileId)\n if (!file) return refuse(404, 'That file is no longer on this submission.')\n return {\n status: 200,\n body: {},\n file: {\n path: visitorUploadFinalPath(formFileScope(hostId, submissionId), file.id),\n name: file.name,\n contentType: file.contentType,\n },\n }\n }\n\n if (action === 'release') {\n // Only the files of a submission that is gone.\n if (submission.exists) return refuse(409, 'This submission is still in the Inbox.')\n const uploads = await deps.uploads()\n await uploads.removeAll(formFileScope(hostId, submissionId))\n return { status: 200, body: { released: true } }\n }\n\n return refuse(400, 'Unknown action')\n}\n\n/** `POST /api/forms/submission-file`. */\nexport const submissionFilesHandler: PluginApiHandler = async (req, res) => {\n const deps = defaultSubmissionFilesDeps()\n const outcome = await handleSubmissionFiles(deps, req)\n if (outcome.file) {\n const uploads = await deps.uploads()\n return uploads.send(res as never, outcome.file)\n }\n return res.status(outcome.status).json(outcome.body)\n}\n"],"names":["visitorUploadFinalPath","firebaseAdmin","isRefusedIdToken","formFileScope","readFormSubmissionFiles","memberMayReadSubmissions","defaultSubmissionFilesDeps","firestore","app","verifyIdToken","token","auth","uploads","formUploadCalls","orgMember","orgId","uid","snapshot","collection","doc","get","exists","data","refuse","status","error","body","DOC_ID","bodyOf","req","raw","parsed","JSON","parse","handleSubmissionFiles","deps","headers","submission","host","method","authorization","String","idToken","startsWith","slice","length","action","hostId","submissionId","test","decoded","hostRef","Promise","all","allowed","staff","fileId","file","find","entry","id","path","name","contentType","removeAll","released","submissionFilesHandler","res","outcome","send","json"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,aAAa,EAAEC,uBAAuB,QAAQ,2BAAuB;AAE9E,SAASC,wBAAwB,QAAQ,yBAAqB;AA6B9D,OAAO,SAASC;IACd,MAAMC,YAAY,IAAMN,cAAcO,GAAG,GAAGD,SAAS;IACrD,OAAO;QACLE,eAAe,CAACC,QAAUT,cAAcO,GAAG,GAAGG,IAAI,GAAGF,aAAa,CAACC;QACnEH;QACAK,SAAS,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,oBAAgB,EAAGC,eAAe;QACrEC,WAAW,OAAOC,OAAOC;YACvB,MAAMC,WAAW,MAAMV,YAAYW,UAAU,CAAC,QAAQC,GAAG,CAACJ,OAAOG,UAAU,CAAC,WAAWC,GAAG,CAACH,KAAKI,GAAG;YACnG,OAAOH,SAASI,MAAM,GAAIJ,SAASK,IAAI,KAAiC;QAC1E;IACF;AACF;AAI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BAAuBG,cAAc4C,QAAQC,eAAeS,KAAKG,EAAE;gBACzEE,MAAML,KAAKK,IAAI;gBACfC,aAAaN,KAAKM,WAAW;YAC/B;QACF;IACF;IAEA,IAAIjB,WAAW,WAAW;QACxB,+CAA+C;QAC/C,IAAIT,WAAWhB,MAAM,EAAE,OAAOE,OAAO,KAAK;QAC1C,MAAMX,UAAU,MAAMuB,KAAKvB,OAAO;QAClC,MAAMA,QAAQoD,SAAS,CAAC7D,cAAc4C,QAAQC;QAC9C,OAAO;YAAExB,QAAQ;YAAKE,MAAM;gBAAEuC,UAAU;YAAK;QAAE;IACjD;IAEA,OAAO1C,OAAO,KAAK;AACrB;AAEA,uCAAuC,GACvC,OAAO,MAAM2C,yBAA2C,OAAOrC,KAAKsC;IAClE,MAAMhC,OAAO7B;IACb,MAAM8D,UAAU,MAAMlC,sBAAsBC,MAAMN;IAClD,IAAIuC,QAAQX,IAAI,EAAE;QAChB,MAAM7C,UAAU,MAAMuB,KAAKvB,OAAO;QAClC,OAAOA,QAAQyD,IAAI,CAACF,KAAcC,QAAQX,IAAI;IAChD;IACA,OAAOU,IAAI3C,MAAM,CAAC4C,QAAQ5C,MAAM,EAAE8C,IAAI,CAACF,QAAQ1C,IAAI;AACrD,EAAC"}
|
package/src/lib/server.js
CHANGED
|
@@ -18,6 +18,9 @@ import { firebaseAdmin, isImpersonationSession } from "@aglyn/tenant-data-admin"
|
|
|
18
18
|
import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
19
19
|
import { FORM_STATS_RECOUNT_MAX, recountFormStats } from "./server/form-stats.js";
|
|
20
20
|
import { formPromoteHandler } from "./server/form-promote-route.js";
|
|
21
|
+
import { registerPluginRecordFactsReader } from "@aglyn/aglyn/plugin-manager/plugin-record-facts";
|
|
22
|
+
import { BUNDLE_ID } from "./constants/bundle-common.js";
|
|
23
|
+
import { FORM_SUBMISSION_FACTS_RESOURCE } from "./model/form-request.js";
|
|
21
24
|
/**
|
|
22
25
|
* `POST /api/forms/stats` — recount the named forms' counters from their
|
|
23
26
|
* rows (AGL-3330).
|
|
@@ -130,9 +133,28 @@ import { formPromoteHandler } from "./server/form-promote-route.js";
|
|
|
130
133
|
}, {
|
|
131
134
|
ownVisitorGates: true
|
|
132
135
|
});
|
|
136
|
+
// A form's files, sent before the form (AGL-4098): tickets, finalize and
|
|
137
|
+
// remove for a File upload field. An ordinary visitor write, so the
|
|
138
|
+
// dispatcher's cross-origin check, the site's Forms switch, lockdown and
|
|
139
|
+
// write limit stand in front of the upload's own limits.
|
|
140
|
+
registerPluginApiRoute('forms/upload', {
|
|
141
|
+
web: async (request)=>(await import("./server/form-upload.js")).POST(request)
|
|
142
|
+
});
|
|
133
143
|
}
|
|
134
144
|
/** Console API registration. */ export function registerFormsConsoleApi() {
|
|
135
145
|
registerPluginApiRoute('forms/stats', formStatsHandler);
|
|
146
|
+
// A submission's files (AGL-4098): downloaded by a member who may read the
|
|
147
|
+
// site's submissions, and released once the Inbox deleted the submission.
|
|
148
|
+
registerPluginApiRoute('forms/submission-file', async (req, res)=>(await import("./server/submission-files.js")).submissionFilesHandler(req, res));
|
|
149
|
+
// A submission's facts for another plugin in this process (AGL-4098):
|
|
150
|
+
// commerce starts a quote from a quote request through it, on the Inbox's
|
|
151
|
+
// read rules, without reading this plugin's collection. Registered with the
|
|
152
|
+
// console's routes, as the CRM's readers are, so the routes that ask find it.
|
|
153
|
+
registerPluginRecordFactsReader(FORM_SUBMISSION_FACTS_RESOURCE, {
|
|
154
|
+
read: async (request)=>(await import("./server/submission-facts.js")).formSubmissionFactsReader.read(request)
|
|
155
|
+
}, {
|
|
156
|
+
pluginId: BUNDLE_ID
|
|
157
|
+
});
|
|
136
158
|
// A form's publish — the `besignerDocuments` publish route
|
|
137
159
|
// `plugins.config.json` declares for it.
|
|
138
160
|
registerPluginApiRoute('forms/promote', {
|
package/src/lib/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/forms/src/lib/server.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 { registerPluginApiRoute, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { FORM_STATS_RECOUNT_MAX, recountFormStats } from './server/form-stats'\nimport { formPromoteHandler } from './server/form-promote-route'\n\n/**\n * `POST /api/forms/stats` — recount the named forms' counters from their\n * rows (AGL-3330).\n *\n * A form's `stats` are server-written: the rules refuse a client write that\n * touches them, because a merchant who could set their own submission count\n * could make any lead rate read however they liked. So a CONSOLE act that\n * changes what they should say — deleting a submission from the Inbox,\n * switching lead routing (a lead-routing form holds `0` leads rather than\n * none) — asks for them to be recounted here, and `recountFormStats` counts\n * the rows and writes what they say.\n *\n * Nothing the caller sends is written: it names forms, and the figures come\n * from Firestore. That is why any member of the site may ask — a recount can\n * only ever put a form's counters in agreement with rows the member can\n * already list — and why it needs no role beyond membership. It is bounded at\n * {@link FORM_STATS_RECOUNT_MAX} forms a request, three aggregation reads\n * each, and a form already in agreement is not written.\n *\n * Body: `{ hostId, formIds: string[] }`. Answers each form's recount, or\n * `null` for an id that is not a form on the site.\n */\nexport const formStatsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = typeof req.body?.hostId === 'string' ? req.body.hostId : ''\n const formIds = Array.isArray(req.body?.formIds)\n ? [\n ...new Set(\n (req.body.formIds as unknown[]).filter(\n (id): id is string => typeof id === 'string' && id.length > 0 && id.length <= 64,\n ),\n ),\n ]\n : []\n if (!hostId || !formIds.length) {\n return res.status(400).json({ error: 'Missing hostId or formIds' })\n }\n if (formIds.length > FORM_STATS_RECOUNT_MAX) {\n return res\n .status(400)\n .json({ error: `At most ${FORM_STATS_RECOUNT_MAX} forms a request` })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return res.status(403).json({ error: 'Verify your email address first' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n const staff = decoded['staff'] === true\n const memberRole = (host.get('memberRoles') ?? {})[decoded.uid]\n if (!staff && !memberRole) {\n return res.status(403).json({ error: 'Not a member of this site' })\n }\n const recounts: Record<string, unknown> = {}\n for (const formId of formIds) {\n const recount = await recountFormStats({ firestore, hostId, formId })\n recounts[formId] = recount\n ? { recounted: recount.recounted, drift: recount.drift, written: recount.written }\n : null\n }\n return res.status(200).json({ ok: true, recounts })\n } catch (error) {\n // A refused credential is a 401; anything else is a fault of ours.\n if (isRefusedIdToken(error)) {\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n console.error('[forms] stats recount failed', error)\n return res.status(500).json({ error: 'Recount failed' })\n }\n}\n\n/**\n * Tenant API registration: every form's door, `POST /api/forms/submit`, at\n * the address it has always had (AGL-3080).\n *\n * It keeps its own visitor gates (`ownVisitorGates`), so the dispatcher hands\n * it the request untouched — see `server/form-submit.ts` for why each gate is\n * the route's to answer. Its module, with everything a submission reaches,\n * loads with the first submission rather than with the tenant's API surface.\n */\nexport function registerFormsApi(): void {\n registerPluginApiRoute(\n 'forms/submit',\n { web: async (request) => (await import('./server/form-submit')).POST(request) },\n { ownVisitorGates: true },\n )\n}\n\n/** Console API registration. */\nexport function registerFormsConsoleApi(): void {\n registerPluginApiRoute('forms/stats', formStatsHandler)\n // A form's publish — the `besignerDocuments` publish route\n // `plugins.config.json` declares for it.\n registerPluginApiRoute('forms/promote', { web: formPromoteHandler })\n}\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { formsPlanEntitlements } from './plan-entitlements'\n"],"names":["registerPluginApiRoute","firebaseAdmin","isImpersonationSession","isRefusedIdToken","FORM_STATS_RECOUNT_MAX","recountFormStats","formPromoteHandler","formStatsHandler","req","res","method","status","json","error","hostId","body","formIds","Array","isArray","Set","filter","id","length","authorization","String","headers","idToken","startsWith","slice","undefined","host","decoded","app","auth","verifyIdToken","email_verified","firestore","collection","doc","get","exists","staff","memberRole","uid","recounts","formId","recount","recounted","drift","written","ok","console","registerFormsApi","web","request","POST","ownVisitorGates","registerFormsConsoleApi"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAA+B,sBAAqB;AACnF,SAASC,aAAa,EAAEC,sBAAsB,QAAQ,2BAA0B;AAChF,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,yBAAqB;AAC9E,SAASC,kBAAkB,QAAQ,iCAA6B;AAEhE;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,MAAMC,mBAAqC,OAAOC,KAAKC;QAsB/BD;QAlBPA,WACQA;IAJ9B,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAAS,SAAON,YAAAA,IAAIO,IAAI,qBAARP,UAAUM,MAAM,MAAK,WAAWN,IAAIO,IAAI,CAACD,MAAM,GAAG;IACxE,M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BAAiB;QAAEqD,KAAK/C;IAAmB;AACpE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/forms/src/lib/server.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 { registerPluginApiRoute, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { FORM_STATS_RECOUNT_MAX, recountFormStats } from './server/form-stats'\nimport { formPromoteHandler } from './server/form-promote-route'\nimport { registerPluginRecordFactsReader } from '@aglyn/aglyn/plugin-manager/plugin-record-facts'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { FORM_SUBMISSION_FACTS_RESOURCE } from './model/form-request'\n\n/**\n * `POST /api/forms/stats` — recount the named forms' counters from their\n * rows (AGL-3330).\n *\n * A form's `stats` are server-written: the rules refuse a client write that\n * touches them, because a merchant who could set their own submission count\n * could make any lead rate read however they liked. So a CONSOLE act that\n * changes what they should say — deleting a submission from the Inbox,\n * switching lead routing (a lead-routing form holds `0` leads rather than\n * none) — asks for them to be recounted here, and `recountFormStats` counts\n * the rows and writes what they say.\n *\n * Nothing the caller sends is written: it names forms, and the figures come\n * from Firestore. That is why any member of the site may ask — a recount can\n * only ever put a form's counters in agreement with rows the member can\n * already list — and why it needs no role beyond membership. It is bounded at\n * {@link FORM_STATS_RECOUNT_MAX} forms a request, three aggregation reads\n * each, and a form already in agreement is not written.\n *\n * Body: `{ hostId, formIds: string[] }`. Answers each form's recount, or\n * `null` for an id that is not a form on the site.\n */\nexport const formStatsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = typeof req.body?.hostId === 'string' ? req.body.hostId : ''\n const formIds = Array.isArray(req.body?.formIds)\n ? [\n ...new Set(\n (req.body.formIds as unknown[]).filter(\n (id): id is string => typeof id === 'string' && id.length > 0 && id.length <= 64,\n ),\n ),\n ]\n : []\n if (!hostId || !formIds.length) {\n return res.status(400).json({ error: 'Missing hostId or formIds' })\n }\n if (formIds.length > FORM_STATS_RECOUNT_MAX) {\n return res\n .status(400)\n .json({ error: `At most ${FORM_STATS_RECOUNT_MAX} forms a request` })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return res.status(403).json({ error: 'Verify your email address first' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n const staff = decoded['staff'] === true\n const memberRole = (host.get('memberRoles') ?? {})[decoded.uid]\n if (!staff && !memberRole) {\n return res.status(403).json({ error: 'Not a member of this site' })\n }\n const recounts: Record<string, unknown> = {}\n for (const formId of formIds) {\n const recount = await recountFormStats({ firestore, hostId, formId })\n recounts[formId] = recount\n ? { recounted: recount.recounted, drift: recount.drift, written: recount.written }\n : null\n }\n return res.status(200).json({ ok: true, recounts })\n } catch (error) {\n // A refused credential is a 401; anything else is a fault of ours.\n if (isRefusedIdToken(error)) {\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n console.error('[forms] stats recount failed', error)\n return res.status(500).json({ error: 'Recount failed' })\n }\n}\n\n/**\n * Tenant API registration: every form's door, `POST /api/forms/submit`, at\n * the address it has always had (AGL-3080).\n *\n * It keeps its own visitor gates (`ownVisitorGates`), so the dispatcher hands\n * it the request untouched — see `server/form-submit.ts` for why each gate is\n * the route's to answer. Its module, with everything a submission reaches,\n * loads with the first submission rather than with the tenant's API surface.\n */\nexport function registerFormsApi(): void {\n registerPluginApiRoute(\n 'forms/submit',\n { web: async (request) => (await import('./server/form-submit')).POST(request) },\n { ownVisitorGates: true },\n )\n // A form's files, sent before the form (AGL-4098): tickets, finalize and\n // remove for a File upload field. An ordinary visitor write, so the\n // dispatcher's cross-origin check, the site's Forms switch, lockdown and\n // write limit stand in front of the upload's own limits.\n registerPluginApiRoute('forms/upload', {\n web: async (request) => (await import('./server/form-upload')).POST(request),\n })\n}\n\n/** Console API registration. */\nexport function registerFormsConsoleApi(): void {\n registerPluginApiRoute('forms/stats', formStatsHandler)\n // A submission's files (AGL-4098): downloaded by a member who may read the\n // site's submissions, and released once the Inbox deleted the submission.\n registerPluginApiRoute('forms/submission-file', async (req, res) =>\n (await import('./server/submission-files')).submissionFilesHandler(req, res),\n )\n // A submission's facts for another plugin in this process (AGL-4098):\n // commerce starts a quote from a quote request through it, on the Inbox's\n // read rules, without reading this plugin's collection. Registered with the\n // console's routes, as the CRM's readers are, so the routes that ask find it.\n registerPluginRecordFactsReader(\n FORM_SUBMISSION_FACTS_RESOURCE,\n {\n read: async (request) =>\n (await import('./server/submission-facts')).formSubmissionFactsReader.read(request),\n },\n { pluginId: BUNDLE_ID },\n )\n // A form's publish — the `besignerDocuments` publish route\n // `plugins.config.json` declares for it.\n registerPluginApiRoute('forms/promote', { web: formPromoteHandler })\n}\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { formsPlanEntitlements } from './plan-entitlements'\n"],"names":["registerPluginApiRoute","firebaseAdmin","isImpersonationSession","isRefusedIdToken","FORM_STATS_RECOUNT_MAX","recountFormStats","formPromoteHandler","registerPluginRecordFactsReader","BUNDLE_ID","FORM_SUBMISSION_FACTS_RESOURCE","formStatsHandler","req","res","method","status","json","error","hostId","body","formIds","Array","isArray","Set","filter","id","length","authorization","String","headers","idToken","startsWith","slice","undefined","host","decoded","app","auth","verifyIdToken","email_verified","firestore","collection","doc","get","exists","staff","memberRole","uid","recounts","formId","recount","recounted","drift","written","ok","console","registerFormsApi","web","request","POST","ownVisitorGates","registerFormsConsoleApi","submissionFilesHandler","read","formSubmissionFactsReader","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAA+B,sBAAqB;AACnF,SAASC,aAAa,EAAEC,sBAAsB,QAAQ,2BAA0B;AAChF,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,yBAAqB;AAC9E,SAASC,kBAAkB,QAAQ,iCAA6B;AAChE,SAASC,+BAA+B,QAAQ,kDAAiD;AACjG,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,8BAA8B,QAAQ,0BAAsB;AAErE;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,MAAMC,mBAAqC,OAAOC,KAAKC;QAsB/BD;QAlBPA,WACQA;IAJ9B,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAAS,SAAON,YAAAA,IAAIO,IAAI,qBAARP,UAAUM,MAAM,MAAK,WAAWN,IAAIO,IAAI,CAACD,MAAM,GAAG;IACxE,MAAME,UAAUC,MAAMC,OAAO,EAACV,aAAAA,IAAIO,IAAI,qBAARP,WAAUQ,OAAO,IAC3C;WACK,IAAIG,IACL,AAACX,IAAIO,IAAI,CAACC,OAAO,CAAeI,MAAM,CACpC,CAACC,KAAqB,OAAOA,OAAO,YAAYA,GAAGC,MAAM,GAAG,KAAKD,GAAGC,MAAM,IAAI;KAGnF,GACD,EAAE;IACN,IAA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AAsB,CAAClD,KAAKC;IAE1E,sEAAsE;IACtE,0EAA0E;IAC1E,4EAA4E;IAC5E,8EAA8E;IAC9EL,gCACEE,gCACA;QACEqD,MAAM,OAAOL,UACX,AAAC,CAAA,MAAM,MAAM,CAAC,+BAA2B,EAAGM,yBAAyB,CAACD,IAAI,CAACL;IAC/E,GACA;QAAEO,UAAUxD;IAAU;IAExB,2DAA2D;IAC3D,yCAAyC;IACzCR,uBAAuB,iBAAiB;QAAEwD,KAAKlD;IAAmB;AACpE"}
|
package/src/lib/site.js
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/ import * as Aglyn from "@aglyn/aglyn";
|
|
17
17
|
import { mdiEmailFastOutline } from "@aglyn/shared-data-mdi";
|
|
18
18
|
import * as FormComponents from "./components/form.js";
|
|
19
|
+
import * as FileUpload from "./components/form-file-upload.js";
|
|
19
20
|
import { BUNDLE_ID } from "./constants/bundle-common.js";
|
|
20
21
|
/**
|
|
21
22
|
* The canvas half: the form and the fields inside it.
|
|
@@ -37,6 +38,13 @@ import { BUNDLE_ID } from "./constants/bundle-common.js";
|
|
|
37
38
|
// off the FIELD entry only because the registry reads presets per entry;
|
|
38
39
|
// what it places is the form above.
|
|
39
40
|
presets: FormComponents.formBlockPresets
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
// Files a person attaches to a form (AGL-4098). Its body, with the
|
|
44
|
+
// upload code, is a chunk of its own that loads where the field draws.
|
|
45
|
+
component: FileUpload.FormFileUpload,
|
|
46
|
+
schema: FileUpload.formFileUploadSchema,
|
|
47
|
+
presets: FileUpload.formFileUploadPresets
|
|
40
48
|
}
|
|
41
49
|
];
|
|
42
50
|
/**
|
package/src/lib/site.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/forms/src/lib/site.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 * as Aglyn from '@aglyn/aglyn'\nimport { mdiEmailFastOutline } from '@aglyn/shared-data-mdi'\nimport * as FormComponents from './components/form'\nimport { BUNDLE_ID } from './constants/bundle-common'\n\n/**\n * The canvas half: the form and the fields inside it.\n *\n * `formField` ships beside `form` rather than staying with the generic\n * elements because it is not a generic input — it publishes its own\n * name/dataset mapping to the enclosing form through a hidden input, and a\n * field with no form around it submits nowhere.\n */\nexport const FORMS_BUNDLE: Aglyn.FeatureBundleEntry[] = [\n {\n component: FormComponents.Form,\n schema: FormComponents.formSchema,\n presets: FormComponents.formPresets,\n },\n {\n component: FormComponents.FormField,\n schema: FormComponents.formFieldSchema,\n // The composed Contact Section, offered under Sections & Blocks. It hangs\n // off the FIELD entry only because the registry reads presets per entry;\n // what it places is the form above.\n presets: FormComponents.formBlockPresets,\n },\n]\n\n/**\n * Forms feature plugin: a canvas element and a console surface, the shape a\n * capability with both halves takes.\n *\n * ## On for every workspace, switchable per site (AGL-3029)\n *\n * A form has two halves, and only one of them is this bundle. The bundle\n * DRAWS the form; its server half is core — `/api/forms/submit` is a core\n * tenant route and `form-contract.ts` a core module the publish path runs —\n * because core may not import a plugin. A switch on the bundle alone would\n * stop only the drawing: a published contact page would render a hole while\n * the endpoint behind it kept answering.\n *\n * So the switch is not the bundle's. `forms` carries `alwaysOnForWorkspace`\n * in the catalog — the catalog and the submissions already stored belong to\n * the workspace, and no workspace switch is offered — and a site switches it\n * off through its ordinary deny-list. Every half asks the site's plugin set\n * about `FORMS_PLUGIN_ID`, never this package: the submit route refuses, the\n * contract check refuses to publish a form or a page carrying one, and the\n * published page stops drawing the element, on the server as on the client.\n *\n * On is not the same as loaded. `requiredSitePlugins` narrows the pre-render\n * set by each node's `pluginId`, so a page with no form on it does not wait\n * for this bundle — which is the saving the move buys, since every page used\n * to carry the form element inside `mui`.\n */\nexport function registerFormsPlugin(): void {\n // The canvas half only. The console registers the console half through its\n // own `console` surface, and a published page must never load console code\n // (AGL-3116): this runs on every page that places one of these elements.\n if (Aglyn.plugins.getDependency(BUNDLE_ID)) return\n Aglyn.plugins.addDependency(\n Aglyn.defineUiFeatureBundle(\n {\n bundleId: BUNDLE_ID,\n displayName: 'Forms',\n description: 'Forms and their fields: contact, signup, survey',\n icon: { path: mdiEmailFastOutline.path },\n components: FORMS_BUNDLE,\n },\n Aglyn.components,\n ),\n )\n}\n"],"names":["Aglyn","mdiEmailFastOutline","FormComponents","BUNDLE_ID","FORMS_BUNDLE","component","Form","schema","formSchema","presets","formPresets","FormField","formFieldSchema","formBlockPresets","registerFormsPlugin","plugins","getDependency","addDependency","defineUiFeatureBundle","bundleId","displayName","description","icon","path","components"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,mBAAmB,QAAQ,yBAAwB;AAC5D,YAAYC,oBAAoB,uBAAmB;AACnD,SAASC,SAAS,QAAQ,+BAA2B;AAErD;;;;;;;CAOC,GACD,OAAO,MAAMC,eAA2C;IACtD;QACEC,
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/forms/src/lib/site.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 * as Aglyn from '@aglyn/aglyn'\nimport { mdiEmailFastOutline } from '@aglyn/shared-data-mdi'\nimport * as FormComponents from './components/form'\nimport * as FileUpload from './components/form-file-upload'\nimport { BUNDLE_ID } from './constants/bundle-common'\n\n/**\n * The canvas half: the form and the fields inside it.\n *\n * `formField` ships beside `form` rather than staying with the generic\n * elements because it is not a generic input — it publishes its own\n * name/dataset mapping to the enclosing form through a hidden input, and a\n * field with no form around it submits nowhere.\n */\nexport const FORMS_BUNDLE: Aglyn.FeatureBundleEntry[] = [\n {\n component: FormComponents.Form,\n schema: FormComponents.formSchema,\n presets: FormComponents.formPresets,\n },\n {\n component: FormComponents.FormField,\n schema: FormComponents.formFieldSchema,\n // The composed Contact Section, offered under Sections & Blocks. It hangs\n // off the FIELD entry only because the registry reads presets per entry;\n // what it places is the form above.\n presets: FormComponents.formBlockPresets,\n },\n {\n // Files a person attaches to a form (AGL-4098). Its body, with the\n // upload code, is a chunk of its own that loads where the field draws.\n component: FileUpload.FormFileUpload,\n schema: FileUpload.formFileUploadSchema,\n presets: FileUpload.formFileUploadPresets,\n },\n]\n\n/**\n * Forms feature plugin: a canvas element and a console surface, the shape a\n * capability with both halves takes.\n *\n * ## On for every workspace, switchable per site (AGL-3029)\n *\n * A form has two halves, and only one of them is this bundle. The bundle\n * DRAWS the form; its server half is core — `/api/forms/submit` is a core\n * tenant route and `form-contract.ts` a core module the publish path runs —\n * because core may not import a plugin. A switch on the bundle alone would\n * stop only the drawing: a published contact page would render a hole while\n * the endpoint behind it kept answering.\n *\n * So the switch is not the bundle's. `forms` carries `alwaysOnForWorkspace`\n * in the catalog — the catalog and the submissions already stored belong to\n * the workspace, and no workspace switch is offered — and a site switches it\n * off through its ordinary deny-list. Every half asks the site's plugin set\n * about `FORMS_PLUGIN_ID`, never this package: the submit route refuses, the\n * contract check refuses to publish a form or a page carrying one, and the\n * published page stops drawing the element, on the server as on the client.\n *\n * On is not the same as loaded. `requiredSitePlugins` narrows the pre-render\n * set by each node's `pluginId`, so a page with no form on it does not wait\n * for this bundle — which is the saving the move buys, since every page used\n * to carry the form element inside `mui`.\n */\nexport function registerFormsPlugin(): void {\n // The canvas half only. The console registers the console half through its\n // own `console` surface, and a published page must never load console code\n // (AGL-3116): this runs on every page that places one of these elements.\n if (Aglyn.plugins.getDependency(BUNDLE_ID)) return\n Aglyn.plugins.addDependency(\n Aglyn.defineUiFeatureBundle(\n {\n bundleId: BUNDLE_ID,\n displayName: 'Forms',\n description: 'Forms and their fields: contact, signup, survey',\n icon: { path: mdiEmailFastOutline.path },\n components: FORMS_BUNDLE,\n },\n Aglyn.components,\n ),\n )\n}\n"],"names":["Aglyn","mdiEmailFastOutline","FormComponents","FileUpload","BUNDLE_ID","FORMS_BUNDLE","component","Form","schema","formSchema","presets","formPresets","FormField","formFieldSchema","formBlockPresets","FormFileUpload","formFileUploadSchema","formFileUploadPresets","registerFormsPlugin","plugins","getDependency","addDependency","defineUiFeatureBundle","bundleId","displayName","description","icon","path","components"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,mBAAmB,QAAQ,yBAAwB;AAC5D,YAAYC,oBAAoB,uBAAmB;AACnD,YAAYC,gBAAgB,mCAA+B;AAC3D,SAASC,SAAS,QAAQ,+BAA2B;AAErD;;;;;;;CAOC,GACD,OAAO,MAAMC,eAA2C;IACtD;QACEC,WAAWJ,eAAeK,IAAI;QAC9BC,QAAQN,eAAeO,UAAU;QACjCC,SAASR,eAAeS,WAAW;IACrC;IACA;QACEL,WAAWJ,eAAeU,SAAS;QACnCJ,QAAQN,eAAeW,eAAe;QACtC,0EAA0E;QAC1E,yEAAyE;QACzE,oCAAoC;QACpCH,SAASR,eAAeY,gBAAgB;IAC1C;IACA;QACE,mEAAmE;QACnE,uEAAuE;QACvER,WAAWH,WAAWY,cAAc;QACpCP,QAAQL,WAAWa,oBAAoB;QACvCN,SAASP,WAAWc,qBAAqB;IAC3C;CACD,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,SAASC;IACd,2EAA2E;IAC3E,2EAA2E;IAC3E,yEAAyE;IACzE,IAAIlB,MAAMmB,OAAO,CAACC,aAAa,CAAChB,YAAY;IAC5CJ,MAAMmB,OAAO,CAACE,aAAa,CACzBrB,MAAMsB,qBAAqB,CACzB;QACEC,UAAUnB;QACVoB,aAAa;QACbC,aAAa;QACbC,MAAM;YAAEC,MAAM1B,oBAAoB0B,IAAI;QAAC;QACvCC,YAAYvB;IACd,GACAL,MAAM4B,UAAU;AAGtB"}
|