@nextlyhq/plugin-form-builder 0.0.2-alpha.6 → 0.0.2-alpha.60

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 (38) hide show
  1. package/README.md +12 -5
  2. package/dist/admin/index.d.ts +123 -331
  3. package/dist/admin/index.js +3780 -3392
  4. package/dist/admin/index.js.map +1 -1
  5. package/dist/chunk-XCICDELK.js +559 -0
  6. package/dist/chunk-XCICDELK.js.map +1 -0
  7. package/dist/index.d.ts +12 -11
  8. package/dist/index.js +603 -665
  9. package/dist/index.js.map +1 -1
  10. package/dist/{index-C0kBvYjm.d.ts → types-DuEFdLNU.d.ts} +147 -128
  11. package/package.json +33 -31
  12. package/dist/CheckboxFieldEditor-K4T6QX52.js +0 -121
  13. package/dist/CheckboxFieldEditor-K4T6QX52.js.map +0 -1
  14. package/dist/DateFieldEditor-JFJFAVOH.js +0 -187
  15. package/dist/DateFieldEditor-JFJFAVOH.js.map +0 -1
  16. package/dist/EmailFieldEditor-MMOXXL7P.js +0 -138
  17. package/dist/EmailFieldEditor-MMOXXL7P.js.map +0 -1
  18. package/dist/NumberFieldEditor-UISAYR6Z.js +0 -175
  19. package/dist/NumberFieldEditor-UISAYR6Z.js.map +0 -1
  20. package/dist/RadioFieldEditor-6UQFH4WT.js +0 -165
  21. package/dist/RadioFieldEditor-6UQFH4WT.js.map +0 -1
  22. package/dist/SelectFieldEditor-PSO4KHV4.js +0 -213
  23. package/dist/SelectFieldEditor-PSO4KHV4.js.map +0 -1
  24. package/dist/TextFieldEditor-5EU64EA5.js +0 -187
  25. package/dist/TextFieldEditor-5EU64EA5.js.map +0 -1
  26. package/dist/TextareaFieldEditor-773G3LNM.js +0 -190
  27. package/dist/TextareaFieldEditor-773G3LNM.js.map +0 -1
  28. package/dist/admin/index.css +0 -934
  29. package/dist/admin/index.css.map +0 -1
  30. package/dist/chunk-ABNZFTQK.js +0 -586
  31. package/dist/chunk-ABNZFTQK.js.map +0 -1
  32. package/dist/chunk-XTCEPJ7B.js +0 -256
  33. package/dist/chunk-XTCEPJ7B.js.map +0 -1
  34. package/dist/components/index.d.ts +0 -3
  35. package/dist/components/index.js +0 -9
  36. package/dist/components/index.js.map +0 -1
  37. package/dist/styles/form-builder.css +0 -1150
  38. package/dist/styles/submissions-filter.css +0 -75
package/dist/index.js CHANGED
@@ -1,7 +1,39 @@
1
+ import {
2
+ BUILT_IN_FORM_FIELD_TYPES,
3
+ DEFAULT_FORM_SETTINGS,
4
+ DEFAULT_NOTIFICATION_SETTINGS,
5
+ applyFieldDefaults,
6
+ applyFormDefaults,
7
+ createFormConfig,
8
+ downloadFile,
9
+ evaluateConditions,
10
+ evaluateSingleCondition,
11
+ exportAndDownload,
12
+ exportToCSV,
13
+ exportToJSON,
14
+ formatExportValue,
15
+ generateExportFilename,
16
+ getSupportedComparisonOperators,
17
+ isCheckboxFormField,
18
+ isEmailFormField,
19
+ isFileFormField,
20
+ isFormField,
21
+ isFormFieldType,
22
+ isKnownFormField,
23
+ isSelectFormField,
24
+ isTextFormField,
25
+ isValidComparisonOperator,
26
+ normalizeFormSettings,
27
+ pluralize,
28
+ toTitleCase
29
+ } from "./chunk-XCICDELK.js";
30
+
1
31
  // src/plugin.ts
2
- import { getCollectionsHandler } from "nextly/runtime";
32
+ import { createRequire } from "module";
33
+ import { definePlugin } from "@nextlyhq/plugin-sdk";
3
34
 
4
35
  // src/collections/forms.ts
36
+ import { NextlyError } from "@nextlyhq/plugin-sdk";
5
37
  import {
6
38
  text,
7
39
  textarea,
@@ -90,12 +122,18 @@ function formsCollection(pluginConfig) {
90
122
  description: "Allow the same user/IP to submit this form multiple times"
91
123
  }
92
124
  }),
125
+ checkbox({
126
+ name: "honeypotEnabled",
127
+ label: "Honeypot",
128
+ admin: {
129
+ description: "Per-form honeypot override; unset inherits the plugin default"
130
+ }
131
+ }),
93
132
  checkbox({
94
133
  name: "captchaEnabled",
95
134
  label: "Enable reCAPTCHA",
96
- defaultValue: false,
97
135
  admin: {
98
- description: "Protect this form with Google reCAPTCHA v3"
136
+ description: "Per-form reCAPTCHA override; unset inherits the plugin default"
99
137
  }
100
138
  }),
101
139
  text({
@@ -163,10 +201,10 @@ function formsCollection(pluginConfig) {
163
201
  // ============================================================
164
202
  json({
165
203
  name: "notifications",
166
- label: "Email Integrations",
204
+ label: "Notifications",
167
205
  defaultValue: [],
168
206
  admin: {
169
- description: "Email notification integrations. Managed by the Form Builder UI."
207
+ description: "Email notification rules. Managed by the Form Builder UI."
170
208
  }
171
209
  }),
172
210
  // ============================================================
@@ -247,18 +285,17 @@ function formsCollection(pluginConfig) {
247
285
  if (operation === "create" && data && !data.slug && data.name) {
248
286
  data.slug = String(data.name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
249
287
  }
250
- if (data && (data.fields === void 0 || Array.isArray(data.fields) && data.fields.length === 0)) {
251
- throw new Error("Form must have at least one field.");
252
- }
253
- return data;
254
- }
255
- ],
256
- // Add virtual submission count field
257
- afterRead: [
258
- (context) => {
259
- const { data } = context;
260
- if (data) {
261
- data.submissionCount = 0;
288
+ const setsFields = operation === "create" || data?.fields !== void 0;
289
+ if (data && setsFields && (data.fields === void 0 || Array.isArray(data.fields) && data.fields.length === 0)) {
290
+ throw NextlyError.validation({
291
+ errors: [
292
+ {
293
+ path: "fields",
294
+ code: "REQUIRED",
295
+ message: "Form must have at least one field."
296
+ }
297
+ ]
298
+ });
262
299
  }
263
300
  return data;
264
301
  }
@@ -317,12 +354,23 @@ function submissionsCollection(pluginConfig) {
317
354
  options: [
318
355
  { label: "New", value: "new" },
319
356
  { label: "Read", value: "read" },
320
- { label: "Archived", value: "archived" }
357
+ { label: "Archived", value: "archived" },
358
+ // Spam is stored and flagged, never silently dropped: a false
359
+ // positive stays reviewable and recoverable ("Not spam" = back to new).
360
+ { label: "Spam", value: "spam" }
321
361
  ],
322
362
  admin: {
323
363
  description: "Track whether this submission has been reviewed"
324
364
  }
325
365
  }),
366
+ text2({
367
+ name: "spamReason",
368
+ label: "Spam Reason",
369
+ admin: {
370
+ readOnly: true,
371
+ description: "Which spam check flagged this submission (empty for clean submissions)"
372
+ }
373
+ }),
326
374
  // ============================================================
327
375
  // Internal Notes
328
376
  // ============================================================
@@ -360,6 +408,24 @@ function submissionsCollection(pluginConfig) {
360
408
  readOnly: true,
361
409
  description: "When the form was submitted"
362
410
  }
411
+ }),
412
+ // Honesty stamps for admin edits of submitted data: a corrected
413
+ // submission must never be indistinguishable from what the visitor sent.
414
+ date({
415
+ name: "editedAt",
416
+ label: "Edited At",
417
+ admin: {
418
+ readOnly: true,
419
+ description: "When an admin last edited the submitted data"
420
+ }
421
+ }),
422
+ text2({
423
+ name: "editedBy",
424
+ label: "Edited By",
425
+ admin: {
426
+ readOnly: true,
427
+ description: "ID of the admin who last edited the submitted data"
428
+ }
363
429
  })
364
430
  ];
365
431
  let finalFields;
@@ -375,16 +441,35 @@ function submissionsCollection(pluginConfig) {
375
441
  labels,
376
442
  fields: finalFields,
377
443
  timestamps: true,
444
+ // Submissions carry visitor-entered answers plus ipAddress/userAgent, so the
445
+ // default `entry.*` events stay suppressed — otherwise every submission would
446
+ // be delivered to any endpoint subscribed to `entry.created` or `*`. Instead
447
+ // emit a curated `form.submission.created` carrying ONLY safe metadata (which
448
+ // form, when, and the status) — never the answers, IP, or user agent.
449
+ webhooks: {
450
+ record: false,
451
+ emit: {
452
+ event: "form.submission.created",
453
+ fields: ["form", "submittedAt", "status"]
454
+ }
455
+ },
378
456
  admin: {
379
457
  isPlugin: true,
380
458
  group: "Forms",
381
459
  order: 51,
382
460
  useAsTitle: "id",
383
461
  description: "View and manage form submissions",
384
- // Custom components for submissions list
462
+ // Submissions are created by visitors submitting forms — a hand-typed
463
+ // "New Submission" would be fiction, so the admin never offers one.
464
+ disableCreate: true,
385
465
  components: {
386
- // Filter dropdown to filter submissions by form
387
- BeforeListTable: "@nextlyhq/plugin-form-builder/admin#SubmissionsFilter"
466
+ // The full submissions experience (per-form columns, status tabs,
467
+ // drawer detail, export) replaces the generic list.
468
+ views: {
469
+ List: {
470
+ Component: "@nextlyhq/plugin-form-builder/admin#SubmissionsView"
471
+ }
472
+ }
388
473
  },
389
474
  ...overrides.admin
390
475
  },
@@ -401,7 +486,9 @@ function submissionsCollection(pluginConfig) {
401
486
  delete: accessOverrides?.delete ?? (({ roles }) => roles.includes("admin") || roles.includes("super-admin"))
402
487
  },
403
488
  hooks: {
404
- // Auto-set submittedAt timestamp on creation
489
+ // Auto-set submittedAt timestamp on creation. (The edit stamp for
490
+ // updates is registered in plugin.ts init — direct registry hooks are
491
+ // the path that runs for every API surface.)
405
492
  beforeValidate: [
406
493
  (context) => {
407
494
  const { data, operation } = context;
@@ -423,10 +510,24 @@ function submissionsCollection(pluginConfig) {
423
510
  };
424
511
  }
425
512
 
513
+ // src/document-shapes.ts
514
+ function asSubmissionDocument(row) {
515
+ return row;
516
+ }
517
+ function asSubmissionDocuments(rows) {
518
+ return rows;
519
+ }
520
+ function asFormDocument(row) {
521
+ return row;
522
+ }
523
+
426
524
  // src/plugin.ts
525
+ var { version: PLUGIN_VERSION } = createRequire(import.meta.url)(
526
+ "../package.json"
527
+ );
427
528
  function resolveConfig(options) {
428
- const formOverrides = options.formOverrides || options.collections?.forms || {};
429
- const submissionOverrides = options.formSubmissionOverrides || options.collections?.submissions || {};
529
+ const formOverrides = options.formOverrides || {};
530
+ const submissionOverrides = options.formSubmissionOverrides || {};
430
531
  return {
431
532
  formOverrides: {
432
533
  ...formOverrides,
@@ -495,41 +596,206 @@ function formBuilder(options = {}) {
495
596
  const resolvedConfig = resolveConfig(options);
496
597
  const formsCol = formsCollection(resolvedConfig);
497
598
  const submissionsCol = submissionsCollection(resolvedConfig);
498
- const plugin = {
599
+ const plugin = definePlugin({
499
600
  name: "@nextlyhq/plugin-form-builder",
500
- version: "0.0.8",
501
- collections: [formsCol, submissionsCol],
601
+ version: PLUGIN_VERSION,
602
+ nextly: ">=0.0.2-alpha.21",
603
+ // Identity metadata for the admin plugins page, mirroring package.json.
604
+ author: "Nextly",
605
+ homepage: "https://nextlyhq.com",
606
+ repository: "https://github.com/nextlyhq/nextly",
607
+ license: "MIT",
608
+ category: "forms",
609
+ tags: ["forms", "submissions", "email-notifications"],
610
+ // Declarative schema: the merged pipeline folds these into the
611
+ // app schema — no manual `setup()` append needed. Just register the plugin.
612
+ contributes: {
613
+ collections: [formsCol, submissionsCol],
614
+ // Custom permission — gates submission export beyond CRUD. The
615
+ // canonical example third-party plugin authors copy.
616
+ permissions: [
617
+ {
618
+ action: "export",
619
+ resource: "submissions",
620
+ label: "Export Submissions",
621
+ description: "Export form submissions as CSV/JSON",
622
+ // No `group`: the admin already files this under the plugin that
623
+ // declared it, so naming the plugin again would nest it inside
624
+ // itself. `group` is for a plugin with enough permissions to sort
625
+ // its own into headings, which one is not.
626
+ //
627
+ // `danger` because the point of the permission is to take
628
+ // submissions — names, emails, whatever a form asked for — out of
629
+ // the site in a file.
630
+ danger: true
631
+ }
632
+ ],
633
+ // HTTP route — exported at
634
+ // /api/plugins/@nextlyhq/plugin-form-builder/submissions/export. Secure by
635
+ // default: gated by the custom `export-submissions` permission. Reads
636
+ // via the secure-by-default service path as the authed user and
637
+ // resolves its OWN slug through `ctx.self`. The canonical
638
+ // contributes.routes example for third-party authors.
639
+ routes: [
640
+ {
641
+ method: "GET",
642
+ path: "/submissions/export",
643
+ requiredPermission: "export-submissions",
644
+ handler: async (req, ctx) => {
645
+ const declaredSlug = resolvedConfig.formSubmissionOverrides.slug;
646
+ const slug = ctx.self.collections[declaredSlug] ?? declaredSlug;
647
+ const url2 = new URL(req.url);
648
+ const format = url2.searchParams.get("format") ?? "json";
649
+ const formId = url2.searchParams.get("form");
650
+ const status = url2.searchParams.get("status");
651
+ const where = {};
652
+ if (formId) where.form = { equals: formId };
653
+ if (status) where.status = { equals: status };
654
+ else where.status = { not_equals: "spam" };
655
+ const opts = { as: "user", user: ctx.user ?? void 0 };
656
+ let form;
657
+ if (format === "csv") {
658
+ if (!formId) {
659
+ return Response.json(
660
+ {
661
+ error: {
662
+ code: "VALIDATION_ERROR",
663
+ message: "CSV export requires a form parameter."
664
+ }
665
+ },
666
+ { status: 400 }
667
+ );
668
+ }
669
+ const formsSlugDeclared = resolvedConfig.formOverrides.slug;
670
+ const formsSlug = ctx.self.collections[formsSlugDeclared] ?? formsSlugDeclared;
671
+ const formResult = await ctx.services.collections.listEntries(
672
+ formsSlug,
673
+ { where: { id: { equals: formId } } },
674
+ opts
675
+ );
676
+ form = formResult.data[0];
677
+ if (!form) {
678
+ return Response.json(
679
+ { error: { code: "NOT_FOUND", message: "Form not found." } },
680
+ { status: 404 }
681
+ );
682
+ }
683
+ }
684
+ const MAX_EXPORT_ROWS = 5e4;
685
+ const items = [];
686
+ const pageSize = 200;
687
+ let truncated = false;
688
+ for (let page = 1; ; page += 1) {
689
+ const result = await ctx.services.collections.listEntries(
690
+ slug,
691
+ { where, pagination: { limit: pageSize, page } },
692
+ opts
693
+ );
694
+ items.push(...result.data);
695
+ const pageWasFull = result.data.length === pageSize;
696
+ if (items.length >= MAX_EXPORT_ROWS) {
697
+ truncated = pageWasFull || items.length > MAX_EXPORT_ROWS;
698
+ items.length = MAX_EXPORT_ROWS;
699
+ break;
700
+ }
701
+ if (!pageWasFull) break;
702
+ }
703
+ const truncationHeaders = truncated ? { "X-Export-Truncated": "true" } : {};
704
+ if (format !== "csv" || !form) {
705
+ return Response.json({ items }, { headers: truncationHeaders });
706
+ }
707
+ const csv = exportToCSV(
708
+ asSubmissionDocuments(items),
709
+ asFormDocument(form)
710
+ );
711
+ const filename = generateExportFilename(
712
+ typeof form.slug === "string" ? form.slug : "form",
713
+ "csv"
714
+ );
715
+ return new Response(csv, {
716
+ headers: {
717
+ "Content-Type": "text/csv; charset=utf-8",
718
+ "Content-Disposition": `attachment; filename="${filename}"`,
719
+ ...truncationHeaders
720
+ }
721
+ });
722
+ }
723
+ },
724
+ {
725
+ // The builder UI reads the host's resolved field enable/disable map
726
+ // from here, so the plugin option actually gates the type picker.
727
+ // Options resolve server-side only; this is the one channel the
728
+ // admin client has to them.
729
+ method: "GET",
730
+ path: "/builder-config",
731
+ // Derived from the forms slug like the menu entry: with an
732
+ // overridden slug, users hold read-<slug>, not read-forms.
733
+ requiredPermission: `read-${resolvedConfig.formOverrides.slug}`,
734
+ handler: (_req, ctx) => Promise.resolve(
735
+ Response.json({
736
+ fields: resolvedConfig.fields,
737
+ // Notification defaults the builder surfaces: defaultToEmail
738
+ // seeds a new form's first rule, defaultFrom renders as the
739
+ // inherited sender placeholder.
740
+ notifications: {
741
+ defaultFrom: resolvedConfig.notifications.defaultFrom,
742
+ defaultToEmail: resolvedConfig.notifications.defaultToEmail
743
+ },
744
+ // Spam defaults the Settings tab surfaces, so per-form
745
+ // override selects can show what "inherit" resolves to.
746
+ spamProtection: {
747
+ honeypot: resolvedConfig.spamProtection.honeypot,
748
+ recaptchaEnabled: resolvedConfig.spamProtection.recaptcha?.enabled ?? false
749
+ },
750
+ // Runtime-resolved collection slugs (through ctx.self, so a
751
+ // framework .rename() is honored too) — admin components
752
+ // never hardcode "forms"/"form-submissions".
753
+ slugs: {
754
+ forms: ctx.self.collections[resolvedConfig.formOverrides.slug] ?? resolvedConfig.formOverrides.slug,
755
+ submissions: ctx.self.collections[resolvedConfig.formSubmissionOverrides.slug] ?? resolvedConfig.formSubmissionOverrides.slug
756
+ }
757
+ })
758
+ )
759
+ }
760
+ ]
761
+ },
762
+ // Forms is a first-class destination, not a plugin detail: standalone
763
+ // placement gives it its own main-rail icon after Media, and its
764
+ // sub-sidebar lists the plugin's collections (Forms, Submissions) —
765
+ // no separate menu contribution, so "Forms" exists exactly once.
766
+ // Hosts preferring the Plugins section override placement in config.
767
+ // (The old admin.settings.component that rendered a second full builder
768
+ // at /admin/plugins/<slug> is gone; the collection Edit-view override
769
+ // is the single FormBuilderView mount.)
502
770
  admin: {
771
+ placement: "standalone",
772
+ after: "media",
503
773
  order: 50,
774
+ appearance: { icon: "FileText", label: "Forms" },
504
775
  description: "Create and manage forms with submission tracking"
505
776
  },
506
- // -- Config transformer --------------------------------------------------
507
- // Automatically adds plugin collections so users don't have to spread them.
508
- config(config) {
509
- const existing = config.collections || [];
510
- const formsSlug = resolvedConfig.formOverrides.slug;
511
- const submissionsSlug = resolvedConfig.formSubmissionOverrides.slug;
512
- const toAdd = [];
513
- if (!existing.some((c) => c.slug === formsSlug))
514
- toAdd.push(formsCol);
515
- if (!existing.some((c) => c.slug === submissionsSlug))
516
- toAdd.push(submissionsCol);
517
- return { ...config, collections: [...existing, ...toAdd] };
518
- },
519
777
  // -- Init ----------------------------------------------------------------
520
778
  // Registers an afterCreate hook on submissions to send email notifications.
521
779
  init(nextly) {
522
- const submissionSlug = resolvedConfig.formSubmissionOverrides.slug;
523
- const guardKey = `__formBuilder_afterCreate_${submissionSlug}`;
524
- const g = globalThis;
525
- if (g[guardKey]) return;
526
- g[guardKey] = true;
527
- nextly.infra.logger.info("Form Builder plugin initialized", {
780
+ const declaredSubmissionsSlug = resolvedConfig.formSubmissionOverrides.slug;
781
+ const submissionSlug = nextly.self.collections[declaredSubmissionsSlug] ?? declaredSubmissionsSlug;
782
+ nextly.logger.info("Form Builder plugin initialized", {
528
783
  formsCollection: resolvedConfig.formOverrides.slug,
529
784
  submissionsCollection: submissionSlug,
530
785
  enabledFields: Object.entries(resolvedConfig.fields).filter(([, on]) => on).map(([name]) => name)
531
786
  });
532
787
  nextly.__formBuilderConfig = resolvedConfig;
788
+ if (resolvedConfig.beforeEmail) {
789
+ nextly.filters.add(
790
+ "form-builder.beforeEmail",
791
+ (emails, ctx) => resolvedConfig.beforeEmail({
792
+ emails,
793
+ // Boundary: loose runtime documents → the user's typed contract.
794
+ form: asFormDocument(ctx.form),
795
+ submission: asSubmissionDocument(ctx.submission)
796
+ })
797
+ );
798
+ }
533
799
  nextly.hooks.on(
534
800
  "afterCreate",
535
801
  submissionSlug,
@@ -537,8 +803,42 @@ function formBuilder(options = {}) {
537
803
  await handleSubmissionCreated(context, resolvedConfig, nextly);
538
804
  }
539
805
  );
806
+ nextly.hooks.on("beforeUpdate", submissionSlug, (context) => {
807
+ const ctx = context;
808
+ if (ctx.data && ctx.data.data !== void 0) {
809
+ ctx.data.editedAt = /* @__PURE__ */ new Date();
810
+ ctx.data.editedBy = ctx.user?.id ?? null;
811
+ }
812
+ return ctx.data;
813
+ });
814
+ const declaredFormsSlug = resolvedConfig.formOverrides.slug;
815
+ const formsSlug = nextly.self.collections[declaredFormsSlug] ?? declaredFormsSlug;
816
+ nextly.hooks.on("afterRead", formsSlug, async (context) => {
817
+ const data = context.data;
818
+ const records = Array.isArray(data) ? data : data ? [data] : [];
819
+ await Promise.all(
820
+ records.map(async (record) => {
821
+ const form = record;
822
+ if (typeof form.id !== "string") return;
823
+ try {
824
+ form.submissionCount = await nextly.services.collections.count(
825
+ submissionSlug,
826
+ {
827
+ where: {
828
+ form: { equals: form.id },
829
+ status: { not_equals: "spam" }
830
+ }
831
+ },
832
+ { as: "system" }
833
+ );
834
+ } catch {
835
+ form.submissionCount = 0;
836
+ }
837
+ })
838
+ );
839
+ });
540
840
  }
541
- };
841
+ });
542
842
  return {
543
843
  plugin,
544
844
  collections: [formsCol, submissionsCol],
@@ -574,9 +874,78 @@ function collectAttachmentInputs(fields, submittedData) {
574
874
  }
575
875
  return attachments;
576
876
  }
877
+ function parseJsonColumn(value) {
878
+ if (typeof value === "string") {
879
+ try {
880
+ const parsed = JSON.parse(value);
881
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
882
+ } catch {
883
+ return {};
884
+ }
885
+ }
886
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
887
+ }
888
+ function normalizeAddressList(addresses) {
889
+ if (!Array.isArray(addresses)) return void 0;
890
+ const cleaned = addresses.map((address) => typeof address === "string" ? address.trim() : "").filter(Boolean);
891
+ return cleaned.length > 0 ? cleaned : void 0;
892
+ }
893
+ function buildNotificationEmails(input) {
894
+ const { notifications, submittedData, formName, submissionId, defaultFrom } = input;
895
+ const seen = /* @__PURE__ */ new Set();
896
+ const emails = [];
897
+ const skipped = [];
898
+ for (const notification of notifications) {
899
+ if (!notification.enabled) continue;
900
+ if (!notification.templateSlug) {
901
+ skipped.push({ notificationId: notification.id, reason: "no-template" });
902
+ continue;
903
+ }
904
+ const key = notification.id || JSON.stringify(notification);
905
+ if (seen.has(key)) continue;
906
+ seen.add(key);
907
+ if (notification.condition && !evaluateSingleCondition(notification.condition, submittedData)) {
908
+ skipped.push({
909
+ notificationId: notification.id,
910
+ reason: "condition-unmet"
911
+ });
912
+ continue;
913
+ }
914
+ const to = (notification.recipientType === "field" ? resolveFieldRef(notification.to, submittedData) : notification.to).trim();
915
+ if (!to) {
916
+ skipped.push({
917
+ notificationId: notification.id,
918
+ reason: "empty-recipient"
919
+ });
920
+ continue;
921
+ }
922
+ const cc = normalizeAddressList(notification.cc);
923
+ const bcc = normalizeAddressList(notification.bcc);
924
+ const from = notification.senderEmail?.trim() || defaultFrom?.trim() || void 0;
925
+ const replyTo = notification.replyTo ? resolveFieldRef(notification.replyTo, submittedData).trim() || void 0 : void 0;
926
+ emails.push({
927
+ to,
928
+ templateSlug: notification.templateSlug,
929
+ variables: {
930
+ ...submittedData,
931
+ formName,
932
+ submissionId
933
+ },
934
+ providerId: notification.providerId,
935
+ from,
936
+ replyTo,
937
+ cc,
938
+ bcc,
939
+ notificationId: notification.id
940
+ });
941
+ }
942
+ return { emails, skipped };
943
+ }
577
944
  async function handleSubmissionCreated(context, config, nextly) {
945
+ if (!config.notifications.enabled) return;
578
946
  const submission = context.data;
579
947
  if (!submission) return;
948
+ if (submission.status === "spam") return;
580
949
  const rawFormId = submission.form;
581
950
  let formId = null;
582
951
  if (typeof rawFormId === "string") {
@@ -592,46 +961,59 @@ async function handleSubmissionCreated(context, config, nextly) {
592
961
  if (notifications.length === 0) return;
593
962
  const emailService = nextly.services.email;
594
963
  if (!emailService) return;
595
- const submittedData = submission.data ?? {};
964
+ const submittedData = parseJsonColumn(submission.data);
596
965
  const formFields = Array.isArray(form.fields) ? form.fields : [];
597
966
  const fileAttachments = collectAttachmentInputs(formFields, submittedData);
598
- const seen = /* @__PURE__ */ new Set();
599
- for (const notification of notifications) {
600
- if (!notification.enabled || !notification.templateSlug) continue;
601
- const key = notification.id || `${notification.to}::${notification.templateSlug}`;
602
- if (seen.has(key)) continue;
603
- seen.add(key);
967
+ const { emails, skipped } = buildNotificationEmails({
968
+ notifications,
969
+ submittedData,
970
+ formName: form.name,
971
+ submissionId: submission.id,
972
+ defaultFrom: config.notifications.defaultFrom
973
+ });
974
+ for (const skip of skipped) {
975
+ if (skip.reason === "empty-recipient") {
976
+ nextly.logger.warn?.(
977
+ "Form Builder: empty recipient, skipping notification",
978
+ { notificationId: skip.notificationId, formSlug: form.slug }
979
+ );
980
+ } else {
981
+ nextly.logger.debug?.("Form Builder: notification skipped", {
982
+ notificationId: skip.notificationId,
983
+ formSlug: form.slug,
984
+ reason: skip.reason
985
+ });
986
+ }
987
+ }
988
+ if (emails.length === 0) return;
989
+ const finalEmails = await nextly.filters.apply("form-builder.beforeEmail", emails, { form, submission });
990
+ for (const email2 of finalEmails) {
604
991
  try {
605
- const to = notification.recipientType === "field" ? resolveFieldRef(notification.to, submittedData) : notification.to;
606
- if (!to) {
607
- nextly.infra.logger.warn?.(
608
- "Form Builder: empty recipient, skipping notification",
609
- { notificationId: notification.id, formSlug: form.slug }
610
- );
611
- continue;
612
- }
613
- const cc = Array.isArray(notification.cc) && notification.cc.length ? notification.cc : void 0;
614
- const bcc = Array.isArray(notification.bcc) && notification.bcc.length ? notification.bcc : void 0;
615
992
  await emailService.sendWithTemplate(
616
- notification.templateSlug,
617
- to,
618
- { ...submittedData, formName: form.name, submissionId: submission.id },
993
+ email2.templateSlug,
994
+ email2.to,
995
+ email2.variables,
619
996
  {
620
- providerId: notification.providerId,
621
- cc,
622
- bcc,
997
+ providerId: email2.providerId,
998
+ from: email2.from,
999
+ replyTo: email2.replyTo,
1000
+ cc: email2.cc,
1001
+ bcc: email2.bcc,
623
1002
  attachments: fileAttachments.length > 0 ? fileAttachments : void 0
624
1003
  }
625
1004
  );
626
- nextly.infra.logger.info?.("Form Builder: notification sent", {
1005
+ nextly.logger.info?.("Form Builder: notification sent", {
627
1006
  formSlug: form.slug,
628
- to,
629
- templateSlug: notification.templateSlug,
1007
+ to: email2.to,
1008
+ templateSlug: email2.templateSlug,
1009
+ notificationId: email2.notificationId,
630
1010
  attachmentCount: fileAttachments.length
631
1011
  });
632
1012
  } catch (err) {
633
- nextly.infra.logger.error?.("Form Builder: notification failed", {
634
- notificationId: notification.id,
1013
+ nextly.logger.error?.("Form Builder: notification failed", {
1014
+ to: email2.to,
1015
+ templateSlug: email2.templateSlug,
1016
+ notificationId: email2.notificationId,
635
1017
  error: err instanceof Error ? err.message : String(err)
636
1018
  });
637
1019
  }
@@ -639,27 +1021,14 @@ async function handleSubmissionCreated(context, config, nextly) {
639
1021
  }
640
1022
  async function fetchParentForm(config, formId, nextly) {
641
1023
  try {
642
- const handler = getCollectionsHandler();
643
- if (!handler) {
644
- nextly.infra.logger.warn?.(
645
- "Form Builder: CollectionsHandler unavailable, skipping notifications"
646
- );
647
- return null;
648
- }
649
- const result = await handler.getEntry({
650
- collectionName: config.formOverrides.slug,
651
- entryId: formId,
652
- overrideAccess: true
653
- });
654
- const fromData = result?.data;
655
- if (fromData) return fromData;
656
- const fromDoc = result?.doc;
657
- if (fromDoc && typeof fromDoc === "object") {
658
- return fromDoc;
659
- }
660
- return null;
1024
+ const form = await nextly.services.collections.findEntryById(
1025
+ config.formOverrides.slug,
1026
+ formId,
1027
+ { as: "system" }
1028
+ );
1029
+ return form;
661
1030
  } catch (err) {
662
- nextly.infra.logger.error?.("Form Builder: failed to fetch form", {
1031
+ nextly.logger.error?.("Form Builder: failed to fetch form", {
663
1032
  formId,
664
1033
  error: err instanceof Error ? err.message : String(err)
665
1034
  });
@@ -667,30 +1036,8 @@ async function fetchParentForm(config, formId, nextly) {
667
1036
  }
668
1037
  }
669
1038
 
670
- // src/types.ts
671
- function isFormField(value) {
672
- return typeof value === "object" && value !== null && "type" in value && "name" in value && "label" in value;
673
- }
674
- function isFormFieldType(field, type) {
675
- return field.type === type;
676
- }
677
- function isTextFormField(field) {
678
- return field.type === "text";
679
- }
680
- function isEmailFormField(field) {
681
- return field.type === "email";
682
- }
683
- function isSelectFormField(field) {
684
- return field.type === "select";
685
- }
686
- function isCheckboxFormField(field) {
687
- return field.type === "checkbox";
688
- }
689
- function isFileFormField(field) {
690
- return field.type === "file";
691
- }
692
-
693
1039
  // src/config/validate-form.ts
1040
+ import { isPluginFieldTypeOnSurface } from "nextly";
694
1041
  var RESERVED_FORM_SLUGS = [
695
1042
  // API routes
696
1043
  "api",
@@ -707,21 +1054,7 @@ var RESERVED_FORM_SLUGS = [
707
1054
  var RESERVED_SLUGS_SET = new Set(RESERVED_FORM_SLUGS);
708
1055
  var SLUG_PATTERN = /^[a-z][a-z0-9_-]*$/;
709
1056
  var FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;
710
- var VALID_FIELD_TYPES = [
711
- "text",
712
- "email",
713
- "number",
714
- "phone",
715
- "url",
716
- "textarea",
717
- "select",
718
- "checkbox",
719
- "radio",
720
- "file",
721
- "date",
722
- "time",
723
- "hidden"
724
- ];
1057
+ var VALID_FIELD_TYPES = BUILT_IN_FORM_FIELD_TYPES;
725
1058
  var VALID_FIELD_TYPES_SET = new Set(VALID_FIELD_TYPES);
726
1059
  function isReservedSlug(slug) {
727
1060
  return RESERVED_SLUGS_SET.has(slug.toLowerCase());
@@ -937,7 +1270,8 @@ function validateField(field, path, errors, seenNames) {
937
1270
  });
938
1271
  return;
939
1272
  }
940
- if (typeof fieldType !== "string" || !VALID_FIELD_TYPES_SET.has(fieldType)) {
1273
+ const isValidType = typeof fieldType === "string" && (VALID_FIELD_TYPES_SET.has(fieldType) || isPluginFieldTypeOnSurface(fieldType, "forms"));
1274
+ if (!isValidType) {
941
1275
  let fieldTypeRepr;
942
1276
  if (typeof fieldType === "object" && fieldType !== null) {
943
1277
  fieldTypeRepr = JSON.stringify(fieldType);
@@ -1065,82 +1399,6 @@ ${errorMessages}`
1065
1399
  }
1066
1400
  }
1067
1401
 
1068
- // src/config/defaults.ts
1069
- var DEFAULT_FORM_SETTINGS = {
1070
- submitButtonText: "Submit",
1071
- confirmationType: "message",
1072
- successMessage: "Thank you for your submission!",
1073
- allowMultipleSubmissions: true
1074
- };
1075
- var DEFAULT_NOTIFICATION_SETTINGS = {
1076
- enabled: true,
1077
- replyTo: true
1078
- };
1079
- function toTitleCase(str) {
1080
- return str.replace(/[-_]/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
1081
- }
1082
- function pluralize(singular) {
1083
- if (singular.endsWith("y") && !/[aeiou]y$/i.test(singular)) {
1084
- return singular.slice(0, -1) + "ies";
1085
- }
1086
- if (singular.endsWith("s") || singular.endsWith("x") || singular.endsWith("z") || singular.endsWith("ch") || singular.endsWith("sh")) {
1087
- return singular + "es";
1088
- }
1089
- return singular + "s";
1090
- }
1091
- function applyFormDefaults(config) {
1092
- const singularLabel = config.labels?.singular || toTitleCase(config.slug);
1093
- return {
1094
- ...config,
1095
- // Generate labels from slug if not provided
1096
- labels: {
1097
- singular: singularLabel,
1098
- plural: config.labels?.plural || pluralize(singularLabel)
1099
- },
1100
- // Apply settings defaults
1101
- settings: {
1102
- submitButtonText: config.settings?.submitButtonText || DEFAULT_FORM_SETTINGS.submitButtonText,
1103
- confirmationType: config.settings?.confirmationType || DEFAULT_FORM_SETTINGS.confirmationType,
1104
- successMessage: config.settings?.successMessage || DEFAULT_FORM_SETTINGS.successMessage,
1105
- allowMultipleSubmissions: config.settings?.allowMultipleSubmissions ?? DEFAULT_FORM_SETTINGS.allowMultipleSubmissions,
1106
- // Preserve other settings that don't have defaults
1107
- redirectUrl: config.settings?.redirectUrl,
1108
- redirectRelation: config.settings?.redirectRelation,
1109
- captcha: config.settings?.captcha
1110
- },
1111
- // Apply notification defaults if notifications are configured
1112
- notifications: config.notifications ? {
1113
- enabled: config.notifications.enabled ?? DEFAULT_NOTIFICATION_SETTINGS.enabled,
1114
- recipients: config.notifications.recipients || [],
1115
- subject: config.notifications.subject || `New submission for ${singularLabel}`,
1116
- replyTo: config.notifications.replyTo ?? DEFAULT_NOTIFICATION_SETTINGS.replyTo,
1117
- template: config.notifications.template
1118
- } : void 0,
1119
- // Apply access defaults
1120
- access: {
1121
- // Default: anyone can submit the form
1122
- submit: config.access?.submit || (() => true),
1123
- // Default: only authenticated users can view submissions
1124
- read: config.access?.read || (({ req }) => !!req.user)
1125
- }
1126
- };
1127
- }
1128
- function applyFieldDefaults(field) {
1129
- const label = field.label || (field.name ? toTitleCase(field.name.replace(/([A-Z])/g, " $1").trim()) : "");
1130
- return {
1131
- ...field,
1132
- label,
1133
- required: field.required ?? false
1134
- };
1135
- }
1136
- function createFormConfig(slug, fields, options) {
1137
- return applyFormDefaults({
1138
- slug,
1139
- fields,
1140
- ...options
1141
- });
1142
- }
1143
-
1144
1402
  // src/config/field-helpers.ts
1145
1403
  var option = (label, value) => ({
1146
1404
  label,
@@ -1199,189 +1457,18 @@ var hidden = (config) => ({
1199
1457
  type: "hidden"
1200
1458
  });
1201
1459
 
1202
- // src/utils/evaluate-conditions.ts
1203
- function isEmptyValue(value) {
1204
- if (value === void 0 || value === null) {
1205
- return true;
1206
- }
1207
- if (typeof value === "string" && value.trim() === "") {
1208
- return true;
1209
- }
1210
- if (Array.isArray(value) && value.length === 0) {
1211
- return true;
1212
- }
1213
- return false;
1214
- }
1215
- function toNumber(value) {
1216
- if (typeof value === "number") {
1217
- return value;
1218
- }
1219
- if (typeof value === "string") {
1220
- const trimmed = value.trim();
1221
- if (trimmed === "") {
1222
- return NaN;
1223
- }
1224
- return Number(trimmed);
1225
- }
1226
- return NaN;
1227
- }
1228
- function toString(value) {
1229
- if (value === void 0 || value === null) {
1230
- return "";
1231
- }
1232
- if (typeof value === "string") {
1233
- return value;
1234
- }
1235
- if (Array.isArray(value)) {
1236
- return value.join(", ");
1237
- }
1238
- if (typeof value === "object") {
1239
- return JSON.stringify(value);
1240
- }
1241
- return String(value);
1242
- }
1243
- function compareValues(operator, fieldValue, conditionValue) {
1244
- switch (operator) {
1245
- case "equals": {
1246
- if (Array.isArray(fieldValue)) {
1247
- if (Array.isArray(conditionValue)) {
1248
- if (fieldValue.length !== conditionValue.length) {
1249
- return false;
1250
- }
1251
- return fieldValue.every((v, i) => v === conditionValue[i]);
1252
- }
1253
- return fieldValue.includes(conditionValue);
1254
- }
1255
- return toString(fieldValue) === toString(conditionValue);
1256
- }
1257
- case "notEquals": {
1258
- if (Array.isArray(fieldValue)) {
1259
- if (Array.isArray(conditionValue)) {
1260
- if (fieldValue.length !== conditionValue.length) {
1261
- return true;
1262
- }
1263
- return !fieldValue.every((v, i) => v === conditionValue[i]);
1264
- }
1265
- return !fieldValue.includes(conditionValue);
1266
- }
1267
- return toString(fieldValue) !== toString(conditionValue);
1268
- }
1269
- case "contains": {
1270
- const fieldStr = toString(fieldValue).toLowerCase();
1271
- const conditionStr = toString(conditionValue).toLowerCase();
1272
- if (Array.isArray(fieldValue)) {
1273
- return fieldValue.some(
1274
- (v) => toString(v).toLowerCase().includes(conditionStr)
1275
- );
1276
- }
1277
- return fieldStr.includes(conditionStr);
1278
- }
1279
- case "isEmpty": {
1280
- return isEmptyValue(fieldValue);
1281
- }
1282
- case "isNotEmpty": {
1283
- return !isEmptyValue(fieldValue);
1284
- }
1285
- case "greaterThan": {
1286
- const fieldNum = toNumber(fieldValue);
1287
- const conditionNum = toNumber(conditionValue);
1288
- if (!Number.isNaN(fieldNum) && !Number.isNaN(conditionNum)) {
1289
- return fieldNum > conditionNum;
1290
- }
1291
- return toString(fieldValue) > toString(conditionValue);
1292
- }
1293
- case "lessThan": {
1294
- const fieldNum = toNumber(fieldValue);
1295
- const conditionNum = toNumber(conditionValue);
1296
- if (!Number.isNaN(fieldNum) && !Number.isNaN(conditionNum)) {
1297
- return fieldNum < conditionNum;
1298
- }
1299
- return toString(fieldValue) < toString(conditionValue);
1300
- }
1301
- default: {
1302
- console.warn(
1303
- `[evaluateConditions] Unknown comparison operator: ${String(operator)}`
1304
- );
1305
- return false;
1306
- }
1307
- }
1308
- }
1309
- function evaluateSingleCondition(condition, formData) {
1310
- const { field, comparison, value: conditionValue } = condition;
1311
- const fieldValue = getNestedValue(formData, field);
1312
- return compareValues(comparison, fieldValue, conditionValue);
1313
- }
1314
- function getNestedValue(obj, path) {
1315
- if (!path) {
1316
- return void 0;
1317
- }
1318
- if (!path.includes(".")) {
1319
- return obj[path];
1320
- }
1321
- const parts = path.split(".");
1322
- let current = obj;
1323
- for (const part of parts) {
1324
- if (current === void 0 || current === null) {
1325
- return void 0;
1326
- }
1327
- if (typeof current !== "object") {
1328
- return void 0;
1329
- }
1330
- current = current[part];
1331
- }
1332
- return current;
1333
- }
1334
- function evaluateConditions(logic, formData) {
1335
- if (!logic || !logic.enabled) {
1336
- return true;
1337
- }
1338
- const { action, operator, conditions } = logic;
1339
- if (!conditions || conditions.length === 0) {
1340
- return true;
1341
- }
1342
- const results = conditions.map(
1343
- (condition) => evaluateSingleCondition(condition, formData)
1344
- );
1345
- let conditionsMet;
1346
- if (operator === "OR") {
1347
- conditionsMet = results.some((result) => result);
1348
- } else {
1349
- conditionsMet = results.every((result) => result);
1350
- }
1351
- if (action === "hide") {
1352
- return !conditionsMet;
1353
- }
1354
- return conditionsMet;
1355
- }
1356
- function isValidComparisonOperator(operator) {
1357
- const validOperators = [
1358
- "equals",
1359
- "notEquals",
1360
- "contains",
1361
- "isEmpty",
1362
- "isNotEmpty",
1363
- "greaterThan",
1364
- "lessThan"
1365
- ];
1366
- return validOperators.includes(operator);
1367
- }
1368
- function getSupportedComparisonOperators() {
1369
- return [
1370
- "equals",
1371
- "notEquals",
1372
- "contains",
1373
- "isEmpty",
1374
- "isNotEmpty",
1375
- "greaterThan",
1376
- "lessThan"
1377
- ];
1378
- }
1379
-
1380
1460
  // src/utils/generate-schema.ts
1381
1461
  import { z } from "zod";
1382
1462
  function generateZodSchema(fields) {
1383
1463
  const schemaShape = {};
1384
1464
  for (const field of fields) {
1465
+ if (!isKnownFormField(field)) {
1466
+ schemaShape[field.name] = field.required ? z.unknown().refine(
1467
+ (value) => value !== void 0 && value !== null && value !== "",
1468
+ { message: `${field.label || field.name} is required` }
1469
+ ) : z.unknown();
1470
+ continue;
1471
+ }
1385
1472
  if (field.type === "hidden" && !field.required) {
1386
1473
  schemaShape[field.name] = z.string().optional();
1387
1474
  continue;
@@ -1459,8 +1546,7 @@ function generateEmailSchema(field) {
1459
1546
  }
1460
1547
  function generateNumberSchema(field) {
1461
1548
  let schema = z.number({
1462
- required_error: field.validation?.errorMessage || "This field is required",
1463
- invalid_type_error: "Must be a number"
1549
+ error: (issue) => issue.input === void 0 ? field.validation?.errorMessage || "This field is required" : "Must be a number"
1464
1550
  });
1465
1551
  if (field.validation?.min !== void 0) {
1466
1552
  schema = schema.min(
@@ -1533,9 +1619,7 @@ function generateSelectSchema(field) {
1533
1619
  return schema2.optional();
1534
1620
  }
1535
1621
  const schema = z.enum(validValues, {
1536
- errorMap: () => ({
1537
- message: field.validation?.errorMessage || "Please select a valid option"
1538
- })
1622
+ error: () => field.validation?.errorMessage || "Please select a valid option"
1539
1623
  });
1540
1624
  if (field.required) {
1541
1625
  return schema;
@@ -1554,9 +1638,7 @@ function generateCheckboxSchema(field) {
1554
1638
  function generateRadioSchema(field) {
1555
1639
  const validValues = field.options.map((opt) => opt.value);
1556
1640
  const schema = z.enum(validValues, {
1557
- errorMap: () => ({
1558
- message: field.validation?.errorMessage || "Please select an option"
1559
- })
1641
+ error: () => field.validation?.errorMessage || "Please select an option"
1560
1642
  });
1561
1643
  if (field.required) {
1562
1644
  return schema;
@@ -1633,7 +1715,7 @@ function transformFormData(data, fields) {
1633
1715
  if (value === void 0) {
1634
1716
  continue;
1635
1717
  }
1636
- transformed[field.name] = transformFieldValue(value, field);
1718
+ transformed[field.name] = isKnownFormField(field) ? transformFieldValue(value, field) : value;
1637
1719
  }
1638
1720
  return transformed;
1639
1721
  }
@@ -1684,7 +1766,7 @@ function getValidationErrors(result) {
1684
1766
  return {};
1685
1767
  }
1686
1768
  const errors = {};
1687
- for (const error of result.error.errors) {
1769
+ for (const error of result.error.issues) {
1688
1770
  const path = error.path.join(".");
1689
1771
  if (!errors[path]) {
1690
1772
  errors[path] = error.message;
@@ -1693,203 +1775,6 @@ function getValidationErrors(result) {
1693
1775
  return errors;
1694
1776
  }
1695
1777
 
1696
- // src/utils/export-formats.ts
1697
- var UTF8_BOM = "\uFEFF";
1698
- function safeString(value) {
1699
- if (typeof value === "object" && value !== null) {
1700
- return JSON.stringify(value);
1701
- }
1702
- return String(value);
1703
- }
1704
- function formatExportValue(value, field) {
1705
- if (value === null || value === void 0) {
1706
- return "";
1707
- }
1708
- if (field) {
1709
- switch (field.type) {
1710
- case "checkbox":
1711
- return value ? "Yes" : "No";
1712
- case "select":
1713
- if (Array.isArray(value)) {
1714
- return value.join(", ");
1715
- }
1716
- return safeString(value);
1717
- case "file":
1718
- if (Array.isArray(value)) {
1719
- return value.map((v) => safeString(v)).join(", ");
1720
- }
1721
- return safeString(value);
1722
- case "date":
1723
- if (value instanceof Date) {
1724
- return value.toISOString().split("T")[0];
1725
- }
1726
- if (typeof value === "string") {
1727
- const parsed = new Date(value);
1728
- if (!isNaN(parsed.getTime())) {
1729
- return parsed.toISOString().split("T")[0];
1730
- }
1731
- }
1732
- return safeString(value);
1733
- case "time":
1734
- return safeString(value);
1735
- case "hidden":
1736
- return safeString(value);
1737
- default:
1738
- break;
1739
- }
1740
- }
1741
- if (Array.isArray(value)) {
1742
- return value.join(", ");
1743
- }
1744
- if (typeof value === "boolean") {
1745
- return value ? "Yes" : "No";
1746
- }
1747
- if (value instanceof Date) {
1748
- return value.toISOString();
1749
- }
1750
- return safeString(value);
1751
- }
1752
- function formatDate(date3, format = "iso") {
1753
- if (!date3) return "";
1754
- const d = typeof date3 === "string" ? new Date(date3) : date3;
1755
- if (isNaN(d.getTime())) {
1756
- return "";
1757
- }
1758
- return format === "iso" ? d.toISOString() : d.toLocaleString();
1759
- }
1760
- function escapeCSVValue(value, delimiter = ",") {
1761
- const needsQuoting = value.includes(delimiter) || value.includes('"') || value.includes("\n") || value.includes("\r");
1762
- if (!needsQuoting) {
1763
- return value;
1764
- }
1765
- const escaped = value.replace(/"/g, '""');
1766
- return `"${escaped}"`;
1767
- }
1768
- function exportToCSV(submissions, form, options = {}) {
1769
- const {
1770
- includeMetadata = true,
1771
- delimiter = ",",
1772
- includeBOM = true,
1773
- dateFormat = "iso"
1774
- } = options;
1775
- const exportableFields = form.fields;
1776
- const headers = [];
1777
- for (const field of exportableFields) {
1778
- headers.push(field.label);
1779
- }
1780
- if (includeMetadata) {
1781
- headers.push("ID", "Status", "Submitted At", "IP Address", "User Agent");
1782
- }
1783
- const rows = [];
1784
- for (const submission of submissions) {
1785
- const row = [];
1786
- const data = submission.data;
1787
- for (const field of exportableFields) {
1788
- const value = data[field.name];
1789
- const formatted = formatExportValue(value, field);
1790
- row.push(escapeCSVValue(formatted, delimiter));
1791
- }
1792
- if (includeMetadata) {
1793
- row.push(escapeCSVValue(submission.id, delimiter));
1794
- row.push(escapeCSVValue(submission.status, delimiter));
1795
- row.push(
1796
- escapeCSVValue(
1797
- formatDate(submission.submittedAt, dateFormat),
1798
- delimiter
1799
- )
1800
- );
1801
- row.push(escapeCSVValue(submission.ipAddress || "", delimiter));
1802
- row.push(escapeCSVValue(submission.userAgent || "", delimiter));
1803
- }
1804
- rows.push(row);
1805
- }
1806
- const escapedHeaders = headers.map((h) => escapeCSVValue(h, delimiter));
1807
- const lines = [
1808
- escapedHeaders.join(delimiter),
1809
- ...rows.map((row) => row.join(delimiter))
1810
- ];
1811
- const csvContent = lines.join("\r\n");
1812
- return includeBOM ? UTF8_BOM + csvContent : csvContent;
1813
- }
1814
- function exportToJSON(submissions, form, options = {}) {
1815
- const {
1816
- includeMetadata = true,
1817
- includeFormDefinition = true,
1818
- indent = 2
1819
- } = options;
1820
- const exportableFields = form.fields;
1821
- const formDefinition = includeFormDefinition ? {
1822
- id: form.id,
1823
- name: form.name,
1824
- slug: form.slug,
1825
- fields: exportableFields.map((f) => ({
1826
- name: f.name,
1827
- label: f.label,
1828
- type: f.type
1829
- }))
1830
- } : void 0;
1831
- const exportedSubmissions = submissions.map((submission) => {
1832
- const data = submission.data;
1833
- const fieldData = {};
1834
- for (const field of exportableFields) {
1835
- const value = data[field.name];
1836
- fieldData[field.name] = value;
1837
- }
1838
- if (includeMetadata) {
1839
- return {
1840
- ...fieldData,
1841
- _metadata: {
1842
- id: submission.id,
1843
- status: submission.status,
1844
- submittedAt: submission.submittedAt,
1845
- ipAddress: submission.ipAddress || null,
1846
- userAgent: submission.userAgent || null,
1847
- createdAt: submission.createdAt,
1848
- updatedAt: submission.updatedAt
1849
- }
1850
- };
1851
- }
1852
- return fieldData;
1853
- });
1854
- const exportData = {
1855
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1856
- totalSubmissions: submissions.length,
1857
- submissions: exportedSubmissions
1858
- };
1859
- if (formDefinition) {
1860
- exportData.form = formDefinition;
1861
- }
1862
- return JSON.stringify(exportData, null, indent);
1863
- }
1864
- function downloadFile(content, filename, mimeType) {
1865
- if (typeof window === "undefined" || typeof document === "undefined") {
1866
- throw new Error("downloadFile is only available in browser environments");
1867
- }
1868
- const blob = new Blob([content], { type: mimeType });
1869
- const url2 = URL.createObjectURL(blob);
1870
- const link = document.createElement("a");
1871
- link.href = url2;
1872
- link.download = filename;
1873
- document.body.appendChild(link);
1874
- link.click();
1875
- document.body.removeChild(link);
1876
- URL.revokeObjectURL(url2);
1877
- }
1878
- function generateExportFilename(formSlug, format) {
1879
- const date3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1880
- return `${formSlug}-submissions-${date3}.${format}`;
1881
- }
1882
- function exportAndDownload(submissions, form, format, options) {
1883
- const filename = generateExportFilename(form.slug, format);
1884
- if (format === "csv") {
1885
- const content = exportToCSV(submissions, form, options);
1886
- downloadFile(content, filename, "text/csv;charset=utf-8");
1887
- } else {
1888
- const content = exportToJSON(submissions, form, options);
1889
- downloadFile(content, filename, "application/json");
1890
- }
1891
- }
1892
-
1893
1778
  // src/handlers/spam-detection.ts
1894
1779
  var rateLimitStore = /* @__PURE__ */ new Map();
1895
1780
  async function checkSpam(options) {
@@ -2007,7 +1892,7 @@ async function submitForm(options, context) {
2007
1892
  const { formSlug, data, metadata } = options;
2008
1893
  const { pluginContext, pluginConfig } = context;
2009
1894
  const { collections } = pluginContext.services;
2010
- const { logger } = pluginContext.infra;
1895
+ const { logger } = pluginContext;
2011
1896
  try {
2012
1897
  const form = await fetchFormBySlug(formSlug, pluginConfig, pluginContext);
2013
1898
  if (!form) {
@@ -2029,46 +1914,95 @@ async function submitForm(options, context) {
2029
1914
  error: "This form is not currently accepting submissions"
2030
1915
  };
2031
1916
  }
2032
- const transformedData = transformFormData(data, form.fields);
2033
- const schema = generateZodSchema(form.fields);
2034
- const validationResult = schema.safeParse(transformedData);
2035
- if (!validationResult.success) {
2036
- const validationErrors = getValidationErrors(validationResult);
2037
- logger.debug?.("Form validation failed", {
2038
- formSlug,
2039
- errors: validationErrors
2040
- });
2041
- return {
2042
- success: false,
2043
- error: "Validation failed",
2044
- validationErrors
2045
- };
1917
+ const settings = normalizeFormSettings(form.settings);
1918
+ if (settings.allowMultipleSubmissions === false && !metadata?.ipAddress) {
1919
+ logger.warn?.(
1920
+ "Single-submission form received a submission without an IP \u2014 the restriction cannot apply",
1921
+ { formSlug }
1922
+ );
1923
+ }
1924
+ if (settings.allowMultipleSubmissions === false && metadata?.ipAddress) {
1925
+ const existing = await collections.count(
1926
+ pluginConfig.formSubmissionOverrides.slug,
1927
+ {
1928
+ where: {
1929
+ form: { equals: form.id },
1930
+ ipAddress: { equals: metadata.ipAddress },
1931
+ status: { not_equals: "spam" }
1932
+ }
1933
+ },
1934
+ { as: "system" }
1935
+ );
1936
+ if (existing > 0) {
1937
+ logger.info?.("Repeat submission rejected (single-submission form)", {
1938
+ formSlug,
1939
+ ipAddress: metadata.ipAddress
1940
+ });
1941
+ return {
1942
+ success: false,
1943
+ error: "You have already submitted this form."
1944
+ };
1945
+ }
2046
1946
  }
2047
- sanitizeSubmissionData(validationResult.data, form.fields);
1947
+ const declaredFieldNames = new Set(form.fields.map((field) => field.name));
1948
+ const undeclaredData = Object.fromEntries(
1949
+ Object.entries(data).filter(([key]) => !declaredFieldNames.has(key))
1950
+ );
2048
1951
  const spamResult = await checkSpam({
2049
- data: transformedData,
1952
+ data: undeclaredData,
2050
1953
  ipAddress: metadata?.ipAddress,
2051
1954
  formSlug,
2052
1955
  config: {
2053
- honeypot: pluginConfig.spamProtection.honeypot,
1956
+ // Per-form overrides win where set; blank inherits the plugin config.
1957
+ honeypot: settings.honeypotEnabled ?? pluginConfig.spamProtection.honeypot,
2054
1958
  rateLimit: pluginConfig.spamProtection.rateLimit,
2055
- recaptcha: pluginConfig.spamProtection.recaptcha
1959
+ recaptcha: {
1960
+ ...pluginConfig.spamProtection.recaptcha,
1961
+ enabled: settings.captchaEnabled ?? pluginConfig.spamProtection.recaptcha?.enabled ?? false
1962
+ }
2056
1963
  }
2057
1964
  });
2058
- if (spamResult.isSpam) {
2059
- logger.info?.("Spam submission detected and rejected", {
1965
+ if (spamResult.isSpam && spamResult.reason === "rate_limit") {
1966
+ logger.info?.("Spam submission rejected (rate limit)", {
1967
+ formSlug,
1968
+ ipAddress: metadata?.ipAddress
1969
+ });
1970
+ return { success: true };
1971
+ }
1972
+ const isContentSpam = spamResult.isSpam;
1973
+ const transformedData = transformFormData(data, form.fields);
1974
+ let storedData;
1975
+ if (isContentSpam) {
1976
+ logger.info?.("Spam submission detected \u2014 storing flagged", {
2060
1977
  formSlug,
2061
1978
  reason: spamResult.reason,
2062
1979
  ipAddress: metadata?.ipAddress
2063
1980
  });
2064
- return {
2065
- success: true
2066
- };
1981
+ sanitizeSubmissionData(transformedData, form.fields);
1982
+ storedData = transformedData;
1983
+ } else {
1984
+ const schema = generateZodSchema(form.fields);
1985
+ const validationResult = schema.safeParse(transformedData);
1986
+ if (!validationResult.success) {
1987
+ const validationErrors = getValidationErrors(validationResult);
1988
+ logger.debug?.("Form validation failed", {
1989
+ formSlug,
1990
+ errors: validationErrors
1991
+ });
1992
+ return {
1993
+ success: false,
1994
+ error: "Validation failed",
1995
+ validationErrors
1996
+ };
1997
+ }
1998
+ sanitizeSubmissionData(validationResult.data, form.fields);
1999
+ storedData = validationResult.data;
2067
2000
  }
2068
2001
  const submissionData = {
2069
2002
  form: form.id,
2070
- data: validationResult.data,
2071
- status: "new",
2003
+ data: storedData,
2004
+ status: isContentSpam ? "spam" : "new",
2005
+ spamReason: isContentSpam ? spamResult.reason ?? null : null,
2072
2006
  ipAddress: metadata?.ipAddress || null,
2073
2007
  userAgent: metadata?.userAgent || null,
2074
2008
  submittedAt: /* @__PURE__ */ new Date()
@@ -2076,17 +2010,33 @@ async function submitForm(options, context) {
2076
2010
  const submission = await collections.createEntry(
2077
2011
  pluginConfig.formSubmissionOverrides.slug,
2078
2012
  submissionData,
2079
- {}
2080
- // Empty context - submission creation is public
2013
+ // Public form submission — create as system. No ambient user; an
2014
+ // empty context already resolves to system, but be explicit.
2015
+ { as: "system" }
2081
2016
  );
2082
2017
  logger.info?.("Form submission created successfully", {
2083
2018
  formSlug,
2084
- submissionId: submission.id
2019
+ submissionId: submission.item.id,
2020
+ flaggedAsSpam: isContentSpam
2085
2021
  });
2022
+ if (submission.warnings) {
2023
+ logger.warn?.("Form submission side effects failed", {
2024
+ formSlug,
2025
+ submissionId: submission.item.id,
2026
+ warnings: submission.warnings
2027
+ });
2028
+ }
2086
2029
  const redirect = determineRedirectUrl(form);
2030
+ if (isContentSpam) {
2031
+ return { success: true, redirect };
2032
+ }
2087
2033
  return {
2088
2034
  success: true,
2089
- submission,
2035
+ // The created ROW, not the envelope around it. Through the shared
2036
+ // conversion, which is where the unchecked step lives and says so; the
2037
+ // integration test reads `submission.id` off the result because nothing
2038
+ // at compile time will.
2039
+ submission: asSubmissionDocument(submission.item),
2090
2040
  redirect
2091
2041
  };
2092
2042
  } catch (error) {
@@ -2105,20 +2055,11 @@ async function fetchFormBySlug(slug, pluginConfig, pluginContext) {
2105
2055
  const { collections } = pluginContext.services;
2106
2056
  const result = await collections.listEntries(
2107
2057
  pluginConfig.formOverrides.slug,
2108
- {
2109
- pagination: { limit: 100 }
2110
- // Fetch enough to find the form
2111
- },
2112
- {}
2113
- // Empty context for public access
2114
- );
2115
- if (!result.data || result.data.length === 0) {
2116
- return null;
2117
- }
2118
- const form = result.data.find(
2119
- (entry) => entry.slug === slug
2058
+ { where: { slug: { equals: slug } }, pagination: { limit: 1 } },
2059
+ { as: "system" }
2120
2060
  );
2121
- return form ? form : null;
2061
+ const form = result.data?.[0];
2062
+ return form ? asFormDocument(form) : null;
2122
2063
  } catch {
2123
2064
  return null;
2124
2065
  }
@@ -2191,33 +2132,28 @@ async function getFormSubmissionStats(formSlug, context) {
2191
2132
  return null;
2192
2133
  }
2193
2134
  try {
2194
- const result = await collections.listEntries(
2195
- pluginConfig.formSubmissionOverrides.slug,
2196
- {
2197
- pagination: { limit: 1e3 }
2198
- // Reasonable limit for stats
2199
- },
2200
- {}
2201
- );
2202
- if (!result.data) {
2203
- return { total: 0, new: 0, read: 0, archived: 0 };
2204
- }
2205
- const submissions = result.data.filter(
2206
- (entry) => entry.form === form.id
2207
- );
2208
- const stats = {
2209
- total: submissions.length,
2210
- new: 0,
2211
- read: 0,
2212
- archived: 0
2213
- };
2214
- for (const sub of submissions) {
2215
- const status = sub.status;
2216
- if (status === "new") stats.new++;
2217
- else if (status === "read") stats.read++;
2218
- else if (status === "archived") stats.archived++;
2219
- }
2220
- return stats;
2135
+ const submissionsSlug = pluginConfig.formSubmissionOverrides.slug;
2136
+ const sys = { as: "system" };
2137
+ const base = { form: { equals: form.id } };
2138
+ const [total, newCount, read, archived] = await Promise.all([
2139
+ collections.count(submissionsSlug, { where: base }, sys),
2140
+ collections.count(
2141
+ submissionsSlug,
2142
+ { where: { ...base, status: { equals: "new" } } },
2143
+ sys
2144
+ ),
2145
+ collections.count(
2146
+ submissionsSlug,
2147
+ { where: { ...base, status: { equals: "read" } } },
2148
+ sys
2149
+ ),
2150
+ collections.count(
2151
+ submissionsSlug,
2152
+ { where: { ...base, status: { equals: "archived" } } },
2153
+ sys
2154
+ )
2155
+ ]);
2156
+ return { total, new: newCount, read, archived };
2221
2157
  } catch {
2222
2158
  return null;
2223
2159
  }
@@ -2404,6 +2340,7 @@ function getSupportedWebhookEvents() {
2404
2340
  // src/index.ts
2405
2341
  var formBuilderPlugin = formBuilder().plugin;
2406
2342
  export {
2343
+ BUILT_IN_FORM_FIELD_TYPES,
2407
2344
  DEFAULT_FORM_SETTINGS,
2408
2345
  DEFAULT_NOTIFICATION_SETTINGS,
2409
2346
  RESERVED_FORM_SLUGS,
@@ -2443,6 +2380,7 @@ export {
2443
2380
  isFormAcceptingSubmissions,
2444
2381
  isFormField,
2445
2382
  isFormFieldType,
2383
+ isKnownFormField,
2446
2384
  isRateLimited,
2447
2385
  isSelectFormField,
2448
2386
  isTextFormField,