@teleporthq/teleport-plugin-next-workflows 0.43.46 → 0.43.47

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 (103) hide show
  1. package/__tests__/auth-env-secret-preservation.test.ts +35 -0
  2. package/__tests__/auth-nextauth-url.test.ts +28 -0
  3. package/__tests__/auth-session-cost.test.ts +614 -0
  4. package/__tests__/custom-js-params-env-invariance.test.ts +134 -0
  5. package/__tests__/data-node-not-awaited.test.ts +644 -0
  6. package/__tests__/element-trigger-static-attr-replace.test.ts +99 -0
  7. package/__tests__/element-visible-trigger-scoping.test.ts +296 -0
  8. package/__tests__/payment-charge-user-handler-serialization.test.ts +7 -5
  9. package/__tests__/payment-redirect-and-order-notification.test.ts +6 -4
  10. package/__tests__/raw-sql-param-binding.test.ts +82 -0
  11. package/__tests__/reserved-word-state-binding.test.ts +112 -0
  12. package/__tests__/strip-event-handler-attrs.test.ts +59 -0
  13. package/__tests__/workflow-auth-guard.test.ts +277 -0
  14. package/dist/cjs/api-route-generator.d.ts +3 -3
  15. package/dist/cjs/api-route-generator.d.ts.map +1 -1
  16. package/dist/cjs/api-route-generator.js +136 -11
  17. package/dist/cjs/api-route-generator.js.map +1 -1
  18. package/dist/cjs/auth-generator.d.ts +67 -1
  19. package/dist/cjs/auth-generator.d.ts.map +1 -1
  20. package/dist/cjs/auth-generator.js +458 -20
  21. package/dist/cjs/auth-generator.js.map +1 -1
  22. package/dist/cjs/await-result.d.ts +31 -0
  23. package/dist/cjs/await-result.d.ts.map +1 -0
  24. package/dist/cjs/await-result.js +50 -0
  25. package/dist/cjs/await-result.js.map +1 -0
  26. package/dist/cjs/executor-generator.d.ts.map +1 -1
  27. package/dist/cjs/executor-generator.js +150 -1
  28. package/dist/cjs/executor-generator.js.map +1 -1
  29. package/dist/cjs/nodes/account/account-get-current.d.ts.map +1 -1
  30. package/dist/cjs/nodes/account/account-get-current.js +44 -11
  31. package/dist/cjs/nodes/account/account-get-current.js.map +1 -1
  32. package/dist/cjs/nodes/account/account-login.d.ts.map +1 -1
  33. package/dist/cjs/nodes/account/account-login.js +10 -1
  34. package/dist/cjs/nodes/account/account-login.js.map +1 -1
  35. package/dist/cjs/raw-sql-param-binding.d.ts.map +1 -1
  36. package/dist/cjs/raw-sql-param-binding.js +32 -0
  37. package/dist/cjs/raw-sql-param-binding.js.map +1 -1
  38. package/dist/cjs/segment-splitter.d.ts.map +1 -1
  39. package/dist/cjs/segment-splitter.js +15 -7
  40. package/dist/cjs/segment-splitter.js.map +1 -1
  41. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  42. package/dist/cjs/workflow-auth-generator.d.ts +26 -0
  43. package/dist/cjs/workflow-auth-generator.d.ts.map +1 -0
  44. package/dist/cjs/workflow-auth-generator.js +166 -0
  45. package/dist/cjs/workflow-auth-generator.js.map +1 -0
  46. package/dist/cjs/workflow-component-plugin.d.ts.map +1 -1
  47. package/dist/cjs/workflow-component-plugin.js +107 -16
  48. package/dist/cjs/workflow-component-plugin.js.map +1 -1
  49. package/dist/cjs/workflow-project-plugin.d.ts +2 -1
  50. package/dist/cjs/workflow-project-plugin.d.ts.map +1 -1
  51. package/dist/cjs/workflow-project-plugin.js +170 -20
  52. package/dist/cjs/workflow-project-plugin.js.map +1 -1
  53. package/dist/esm/api-route-generator.d.ts +3 -3
  54. package/dist/esm/api-route-generator.d.ts.map +1 -1
  55. package/dist/esm/api-route-generator.js +136 -11
  56. package/dist/esm/api-route-generator.js.map +1 -1
  57. package/dist/esm/auth-generator.d.ts +67 -1
  58. package/dist/esm/auth-generator.d.ts.map +1 -1
  59. package/dist/esm/auth-generator.js +453 -19
  60. package/dist/esm/auth-generator.js.map +1 -1
  61. package/dist/esm/await-result.d.ts +31 -0
  62. package/dist/esm/await-result.d.ts.map +1 -0
  63. package/dist/esm/await-result.js +45 -0
  64. package/dist/esm/await-result.js.map +1 -0
  65. package/dist/esm/executor-generator.d.ts.map +1 -1
  66. package/dist/esm/executor-generator.js +150 -1
  67. package/dist/esm/executor-generator.js.map +1 -1
  68. package/dist/esm/nodes/account/account-get-current.d.ts.map +1 -1
  69. package/dist/esm/nodes/account/account-get-current.js +44 -11
  70. package/dist/esm/nodes/account/account-get-current.js.map +1 -1
  71. package/dist/esm/nodes/account/account-login.d.ts.map +1 -1
  72. package/dist/esm/nodes/account/account-login.js +10 -1
  73. package/dist/esm/nodes/account/account-login.js.map +1 -1
  74. package/dist/esm/raw-sql-param-binding.d.ts.map +1 -1
  75. package/dist/esm/raw-sql-param-binding.js +32 -0
  76. package/dist/esm/raw-sql-param-binding.js.map +1 -1
  77. package/dist/esm/segment-splitter.d.ts.map +1 -1
  78. package/dist/esm/segment-splitter.js +15 -7
  79. package/dist/esm/segment-splitter.js.map +1 -1
  80. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  81. package/dist/esm/workflow-auth-generator.d.ts +26 -0
  82. package/dist/esm/workflow-auth-generator.d.ts.map +1 -0
  83. package/dist/esm/workflow-auth-generator.js +161 -0
  84. package/dist/esm/workflow-auth-generator.js.map +1 -0
  85. package/dist/esm/workflow-component-plugin.d.ts.map +1 -1
  86. package/dist/esm/workflow-component-plugin.js +108 -17
  87. package/dist/esm/workflow-component-plugin.js.map +1 -1
  88. package/dist/esm/workflow-project-plugin.d.ts +2 -1
  89. package/dist/esm/workflow-project-plugin.d.ts.map +1 -1
  90. package/dist/esm/workflow-project-plugin.js +169 -20
  91. package/dist/esm/workflow-project-plugin.js.map +1 -1
  92. package/package.json +4 -4
  93. package/src/api-route-generator.ts +139 -11
  94. package/src/auth-generator.ts +471 -19
  95. package/src/await-result.ts +52 -0
  96. package/src/executor-generator.ts +150 -1
  97. package/src/nodes/account/account-get-current.ts +44 -9
  98. package/src/nodes/account/account-login.ts +12 -1
  99. package/src/raw-sql-param-binding.ts +33 -0
  100. package/src/segment-splitter.ts +15 -7
  101. package/src/workflow-auth-generator.ts +187 -0
  102. package/src/workflow-component-plugin.ts +129 -20
  103. package/src/workflow-project-plugin.ts +186 -19
@@ -12,12 +12,13 @@ import {
12
12
  UIDLCustomWorkflowNode,
13
13
  } from '@teleporthq/teleport-types'
14
14
  import * as types from '@babel/types'
15
- import { StringUtils } from '@teleporthq/teleport-shared'
15
+ import { JSIdentifiers, StringUtils } from '@teleporthq/teleport-shared'
16
16
  import {
17
17
  splitIntoSegments,
18
18
  resolveNodeExecutionEnv,
19
19
  redactServerNodeConfig,
20
20
  } from './segment-splitter'
21
+ import { isFireAndForgetSegment } from './await-result'
21
22
  import { WorkflowExecutionEnv } from './types'
22
23
  import { getAPIRouteFileName, hasStreamingAINode } from './api-route-generator'
23
24
  import { REALTIME_TRIGGER_TYPES, REALTIME_NODE_TYPES } from './graph-utils'
@@ -74,6 +75,25 @@ const DOM_TO_REACT_EVENT: Record<string, string> = {
74
75
  drag: 'onDrag',
75
76
  }
76
77
 
78
+ /**
79
+ * Trigger types that run as LIFECYCLE code (no React event prop) but are still
80
+ * bound to ONE element, so the workflow only belongs on the page that renders
81
+ * it. Returns the DOM id to prune against, or null when the trigger is not
82
+ * element-scoped.
83
+ *
84
+ * Same fallback chain as the element-trigger branch: the HTML id first, the
85
+ * project-document node id only as a last resort.
86
+ */
87
+ const resolveLifecycleTriggerElementId = (
88
+ triggerType: string,
89
+ config: Record<string, unknown>
90
+ ): string | null => {
91
+ if (triggerType !== 'event-element-visible') {
92
+ return null
93
+ }
94
+ return ((config.elementHtmlId || config.nodeId) as string) || null
95
+ }
96
+
77
97
  const getReactEventProp = (triggerType: string, config: Record<string, unknown>): string | null => {
78
98
  switch (triggerType) {
79
99
  case 'event-element-clicked':
@@ -219,6 +239,8 @@ export const createNextWorkflowPlugin: ComponentPluginFactory<WorkflowPluginConf
219
239
  // Classify triggers into element-bound vs lifecycle
220
240
  const elementTriggers: ElementTriggerInfo[] = []
221
241
  const lifecycleWorkflows: UIDLWorkflow[] = []
242
+ /** Lifecycle workflows bound to one element, for the per-page JSX prune. */
243
+ const lifecycleElementTargets: Array<{ workflowId: string; elementId: string }> = []
222
244
  const stateChangeWorkflows: UIDLWorkflow[] = []
223
245
  const globalStateChangeWorkflows: UIDLWorkflow[] = []
224
246
 
@@ -272,6 +294,17 @@ export const createNextWorkflowPlugin: ComponentPluginFactory<WorkflowPluginConf
272
294
  }
273
295
  } else {
274
296
  lifecycleWorkflows.push(wf)
297
+ // An element-scoped LIFECYCLE trigger (element-visible) has no React
298
+ // prop, so it lands here — and `lifecycleWorkflows` was activated
299
+ // unconditionally, bypassing the JSX-presence prune below that is the
300
+ // only thing scoping element workflows to one page. One cookie-consent
301
+ // check therefore shipped into EVERY generated file (17 per page in run
302
+ // a15472af, including 404.js and logo.js, which have no banner at all).
303
+ // Record its target so it is pruned like any other element trigger.
304
+ const lifecycleElementId = resolveLifecycleTriggerElementId(trigger.type, triggerConfig)
305
+ if (lifecycleElementId) {
306
+ lifecycleElementTargets.push({ workflowId: wf.id, elementId: lifecycleElementId })
307
+ }
275
308
  }
276
309
  }
277
310
 
@@ -291,8 +324,15 @@ export const createNextWorkflowPlugin: ComponentPluginFactory<WorkflowPluginConf
291
324
  const matchedElementTriggers: ElementTriggerInfo[] = []
292
325
  const unmatchedElementTriggers: ElementTriggerInfo[] = []
293
326
 
294
- if (returnStatement && returnStatement.argument && elementTriggers.length > 0) {
295
- const targetIds = new Set(elementTriggers.map((t) => t.elementId))
327
+ if (
328
+ returnStatement &&
329
+ returnStatement.argument &&
330
+ (elementTriggers.length > 0 || lifecycleElementTargets.length > 0)
331
+ ) {
332
+ const targetIds = new Set([
333
+ ...elementTriggers.map((t) => t.elementId),
334
+ ...lifecycleElementTargets.map((t) => t.elementId),
335
+ ])
296
336
  matchedElements = findJSXElementsById(returnStatement.argument, targetIds)
297
337
 
298
338
  for (const et of elementTriggers) {
@@ -315,6 +355,13 @@ export const createNextWorkflowPlugin: ComponentPluginFactory<WorkflowPluginConf
315
355
  activeWorkflowIds.add(et.workflow.id)
316
356
  }
317
357
  for (const wf of lifecycleWorkflows) {
358
+ // A lifecycle workflow bound to a specific element is only active on the
359
+ // page that actually renders that element. One with no element target
360
+ // (page-loaded, interval, …) stays unconditionally active.
361
+ const target = lifecycleElementTargets.find((t) => t.workflowId === wf.id)
362
+ if (target && !matchedElements.has(target.elementId)) {
363
+ continue
364
+ }
318
365
  activeWorkflowIds.add(wf.id)
319
366
  }
320
367
  for (const wf of stateChangeWorkflows) {
@@ -670,7 +717,15 @@ const defaultValueToLiteral = (val: unknown): types.Expression => {
670
717
  return types.nullLiteral()
671
718
  }
672
719
 
673
- const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
720
+ /**
721
+ * Object key for a state/global-state map that the workflow runtime looks up by
722
+ * the name written in the node config (`config.property`). The key therefore
723
+ * keeps the UIDL spelling ALWAYS — only the value beside it is a binding and
724
+ * gets sanitised. Reserved words are legal unquoted keys (`{ class: ... }`);
725
+ * anything that is not identifier syntax at all is quoted.
726
+ */
727
+ const stateMapKey = (name: string): types.Identifier | types.StringLiteral =>
728
+ JSIdentifiers.isValidPropertyKeyName(name) ? types.identifier(name) : types.stringLiteral(name)
674
729
 
675
730
  const resolveStateDefinitionKey = (
676
731
  rawName: string,
@@ -703,39 +758,56 @@ const injectWorkflowCode = (
703
758
 
704
759
  for (const [key, def] of Object.entries(stateDefinitions)) {
705
760
  const setterName = StringUtils.createStateStoringFunction(key)
706
- stateSetterProperties.push(
707
- types.objectProperty(types.identifier(key), types.identifier(setterName))
708
- )
761
+ // KEY: the name a workflow node's `config.property` is written against —
762
+ // never renamed. VALUE: the React binding declared by `createStateHookAST`,
763
+ // which is sanitised because a UIDL state may legally be called `class`.
764
+ stateSetterProperties.push(types.objectProperty(stateMapKey(key), types.identifier(setterName)))
709
765
  stateTypeProperties.push(
710
- types.objectProperty(types.identifier(key), types.stringLiteral(def.type || 'string'))
766
+ types.objectProperty(stateMapKey(key), types.stringLiteral(def.type || 'string'))
767
+ )
768
+ stateValueProperties.push(
769
+ types.objectProperty(
770
+ stateMapKey(key),
771
+ types.identifier(JSIdentifiers.createSafeJSIdentifier(key))
772
+ )
711
773
  )
712
- stateValueProperties.push(types.objectProperty(types.identifier(key), types.identifier(key)))
713
774
  }
714
775
 
715
776
  const globalStateStatements: types.Statement[] = []
716
777
  if (globalStateDefinitions && Object.keys(globalStateDefinitions).length > 0) {
717
778
  const destructuredProps: types.ObjectProperty[] = []
718
779
  for (const def of Object.values(globalStateDefinitions)) {
719
- const setterName = `set${capitalize(def.name)}`
780
+ // `GlobalStateProvider` exposes every entry under its DECLARED name, so
781
+ // the context keys stay raw and only the locals we bind are sanitised.
782
+ // The pattern then reads `{ class: class_ }` — shorthand only when the
783
+ // two coincide, which is the case for every ordinary name.
784
+ const setterKey = StringUtils.createGlobalStateSetterName(def.name)
785
+ const setterName = JSIdentifiers.createSafeJSIdentifier(setterKey)
786
+ const localName = JSIdentifiers.createSafeJSIdentifier(def.name)
720
787
  destructuredProps.push(
721
- types.objectProperty(types.identifier(def.name), types.identifier(def.name), false, true)
788
+ types.objectProperty(
789
+ stateMapKey(def.name),
790
+ types.identifier(localName),
791
+ false,
792
+ localName === def.name
793
+ )
722
794
  )
723
795
  destructuredProps.push(
724
796
  types.objectProperty(
725
- types.identifier(setterName),
797
+ stateMapKey(setterKey),
726
798
  types.identifier(setterName),
727
799
  false,
728
- true
800
+ setterName === setterKey
729
801
  )
730
802
  )
731
803
  stateSetterProperties.push(
732
- types.objectProperty(types.identifier(def.name), types.identifier(setterName))
804
+ types.objectProperty(stateMapKey(def.name), types.identifier(setterName))
733
805
  )
734
806
  stateTypeProperties.push(
735
- types.objectProperty(types.identifier(def.name), types.stringLiteral(def.type || 'string'))
807
+ types.objectProperty(stateMapKey(def.name), types.stringLiteral(def.type || 'string'))
736
808
  )
737
809
  stateValueProperties.push(
738
- types.objectProperty(types.identifier(def.name), types.identifier(def.name))
810
+ types.objectProperty(stateMapKey(def.name), types.identifier(localName))
739
811
  )
740
812
  }
741
813
 
@@ -1117,6 +1189,15 @@ const injectWorkflowCode = (
1117
1189
  ) {
1118
1190
  existingExpr = existingAttr.value.expression
1119
1191
  } else {
1192
+ // A non-expression event prop (e.g. a stray `onClick=""` authored as a
1193
+ // static attr) was never a callable listener — React throws
1194
+ // `func.apply is not a function` on dispatch. Replace it with the
1195
+ // workflow handler instead of skipping, which used to drop the
1196
+ // trigger wiring silently AND ship the crashing prop.
1197
+ openingElement.attributes[existingAttrIndex] = types.jSXAttribute(
1198
+ types.jSXIdentifier(reactProp),
1199
+ types.jSXExpressionContainer(wfHandlerExpr)
1200
+ )
1120
1201
  continue
1121
1202
  }
1122
1203
 
@@ -1303,6 +1384,9 @@ function __normalizeAdminFormRow(row, defaults) {
1303
1384
  id: s.id,
1304
1385
  env: s.env,
1305
1386
  hasStreamingAI: hasStreamingAINode(s),
1387
+ // Every node in this segment runs fire-and-forget, so the browser
1388
+ // dispatches it and carries on instead of waiting for the round trip.
1389
+ fireAndForget: isFireAndForgetSegment(s),
1306
1390
  nodes: s.nodes.map((n) => ({
1307
1391
  id: n.id,
1308
1392
  type: n.type,
@@ -1414,8 +1498,26 @@ function __normalizeAdminFormRow(row, defaults) {
1414
1498
  }
1415
1499
  }
1416
1500
 
1417
- // Lifecycle triggers
1501
+ // Lifecycle triggers.
1502
+ //
1503
+ // `allWorkflows` here is the already-pruned `activeWorkflows`: a lifecycle
1504
+ // element-visible trigger whose target element is NOT in this component's own
1505
+ // JSX was excluded from it (its `__wfConfig_*` was therefore never declared).
1506
+ // But `generateLifecycleTrigger` emits an IntersectionObserver that resolves
1507
+ // its target at runtime with `document.getElementById(target)` — a
1508
+ // DOCUMENT-WIDE lookup that happily matches an element ANOTHER component
1509
+ // rendered (e.g. the shared "Cookie Consent" banner, which is attached to
1510
+ // ~23 element-visible workflows and would otherwise ship into every product
1511
+ // card). When it fires it calls `__execWf(__wfConfig_<id>, …)` for a config
1512
+ // that was never emitted, throwing `ReferenceError: __wfConfig_… is not
1513
+ // defined` the moment the element scrolls into view. Pruning the handler in
1514
+ // lockstep with the config keeps the two in sync: the workflow still runs in
1515
+ // the component/page that actually renders its target element.
1516
+ const emittedConfigIds = new Set(allWorkflows.map((wf) => wf.id))
1418
1517
  for (const wf of lifecycleWorkflows) {
1518
+ if (!emittedConfigIds.has(wf.id)) {
1519
+ continue
1520
+ }
1419
1521
  const safeId = wf.id.replace(/[^a-zA-Z0-9]/g, '_')
1420
1522
  const code = generateLifecycleTrigger(wf, safeId)
1421
1523
  if (code) {
@@ -1999,17 +2101,24 @@ const generateLifecycleTrigger = (wf: UIDLWorkflow, safeId: string): string => {
1999
2101
  }
2000
2102
 
2001
2103
  case 'event-element-visible': {
2002
- const nodeId = config.nodeId as string
2104
+ // `config.nodeId` is the PROJECT-DOCUMENT node id (`TQ_…`); no element in
2105
+ // the generated app ever carries it. `elementHtmlId` is the real DOM id
2106
+ // (`thq_container_…`), already stamped by `ensure-element-ids` and mapped
2107
+ // into the trigger config — the same fallback chain every other element
2108
+ // trigger uses above. Reading `nodeId` made `getElementById` return null,
2109
+ // so the observer was never constructed and the cookie-consent banner
2110
+ // could never appear on any page (run a15472af: 408 dead lookups).
2111
+ const elementId = (config.elementHtmlId || config.nodeId) as string
2003
2112
  const threshold = (config.threshold as number) || 0
2004
2113
  const once = config.once as boolean
2005
2114
  return (
2006
2115
  ` // Element visible (${wf.name || wf.id})\n` +
2007
- ` const __visEl_${safeId} = document.getElementById('${nodeId}');\n` +
2116
+ ` const __visEl_${safeId} = document.getElementById('${elementId}');\n` +
2008
2117
  ` if (__visEl_${safeId}) {\n` +
2009
2118
  ` const __obs_${safeId} = new IntersectionObserver(function(entries) {\n` +
2010
2119
  ` entries.forEach(function(entry) {\n` +
2011
2120
  ` if (entry.isIntersecting) {\n` +
2012
- ` const triggerContext = { elementId: '${nodeId}', timestamp: Date.now(), intersectionRatio: entry.intersectionRatio };\n` +
2121
+ ` const triggerContext = { elementId: '${elementId}', timestamp: Date.now(), intersectionRatio: entry.intersectionRatio };\n` +
2013
2122
  ` ${execCall};\n` +
2014
2123
  (once ? ` __obs_${safeId}.disconnect();\n` : '') +
2015
2124
  ` }\n` +
@@ -6,11 +6,13 @@ import {
6
6
  FileType,
7
7
  UIDLAuthentication,
8
8
  } from '@teleporthq/teleport-types'
9
+ import { UIDLUtils } from '@teleporthq/teleport-shared'
9
10
  import {
10
11
  splitIntoSegments,
11
12
  resolveNodeExecutionEnv,
12
13
  redactServerNodeConfig,
13
14
  } from './segment-splitter'
15
+ import { isFireAndForgetSegment } from './await-result'
14
16
  import {
15
17
  generateServerSegmentAPIRoute,
16
18
  generateStreamingServerSegmentAPIRoute,
@@ -22,6 +24,7 @@ import {
22
24
  getWebhookRoutePath,
23
25
  hasStreamingAINode,
24
26
  } from './api-route-generator'
27
+ import { generateWorkflowAuthHelperFile } from './workflow-auth-generator'
25
28
  import { collectSecrets, collectSecretReferenceEnvNames } from './secret-collector'
26
29
  import {
27
30
  collectUsedNodeTypes,
@@ -47,12 +50,15 @@ import {
47
50
  generateRealtimeChannelsMembersRoute,
48
51
  } from './realtime-generator'
49
52
  import {
53
+ generateAuthDbHealthFile,
54
+ generateAuthErrorMessagesFile,
50
55
  generateAuthOptionsFile,
51
56
  generateHashPasswordFile,
52
57
  generateNextAuthRouteFile,
53
58
  generateSignupRouteFile,
54
59
  generateMiddlewareFile,
55
60
  generateSessionProviderWrapper,
61
+ generateNextAuthUrlGuardModule,
56
62
  getDatabaseDriverDependencies,
57
63
  } from './auth-generator'
58
64
  import { generateInvoiceFiles, resolveInvoiceDataSource } from './invoice'
@@ -157,6 +163,42 @@ const extractSecretEnvName = (value: unknown): string => {
157
163
  return ''
158
164
  }
159
165
 
166
+ const EVENT_HANDLER_ATTR_RE = /^on[A-Z]/
167
+
168
+ // UIDL `attrs` can only hold data, never functions, so an `on*`-named attr
169
+ // (e.g. a stray `onClick: ""` authored by the element generator) can never be a
170
+ // valid listener. Emitted verbatim it becomes `onClick=""` in JSX and React
171
+ // throws `func.apply is not a function` on the first click — and its presence
172
+ // used to block the workflow trigger from being wired onto the element.
173
+ // Behavior belongs in `events` and workflow triggers; strip these attrs before
174
+ // any component is emitted.
175
+ export const stripEventHandlerAttrs = (uidl: ProjectUIDL): void => {
176
+ const scrubComponent = (component: ProjectUIDL['root'] | undefined) => {
177
+ if (!component?.node) {
178
+ return
179
+ }
180
+ UIDLUtils.traverseElements(component.node, (element) => {
181
+ if (!element.attrs) {
182
+ return
183
+ }
184
+ for (const attrName of Object.keys(element.attrs)) {
185
+ if (EVENT_HANDLER_ATTR_RE.test(attrName)) {
186
+ console.warn(
187
+ `[event-attr] ${component.name || 'component'}: attr \`${attrName}\` on element ` +
188
+ `\`${
189
+ element.name || element.elementType
190
+ }\` is not a valid listener and was removed. ` +
191
+ 'Element behavior must use `events` or a workflow trigger.'
192
+ )
193
+ delete element.attrs[attrName]
194
+ }
195
+ }
196
+ })
197
+ }
198
+ scrubComponent(uidl.root)
199
+ Object.values(uidl.components || {}).forEach(scrubComponent)
200
+ }
201
+
160
202
  export class NextWorkflowProjectPlugin implements ProjectPlugin {
161
203
  private static INLINE_HANDLED_NODE_TYPES = new Set([
162
204
  'general-if-statement',
@@ -167,6 +209,8 @@ export class NextWorkflowProjectPlugin implements ProjectPlugin {
167
209
  async runBefore(structure: ProjectPluginStructure): Promise<ProjectPluginStructure> {
168
210
  const { uidl, strategy } = structure
169
211
 
212
+ stripEventHandlerAttrs(uidl)
213
+
170
214
  // SECURITY NET — parameterize raw-SQL interpolations before ANY config is
171
215
  // emitted. Rewrites each `{{ name }}` value token in a data-node's `query` /
172
216
  // `rawQueryUserPart` into a positional `$N` placeholder and moves the bound
@@ -331,6 +375,11 @@ export class NextWorkflowProjectPlugin implements ProjectPlugin {
331
375
  })
332
376
  }
333
377
 
378
+ // Set true the moment we emit ANY route that bakes an auth policy, so the
379
+ // shared guard file is emitted iff at least one route actually imports it.
380
+ const routeHasPolicy = (p: any): boolean => !!p && (p.requiresAuth || p.userScoped)
381
+ let anyGuardedRouteEmitted = false
382
+
334
383
  // Build server segment info for custom nodes so they can call server-side API routes
335
384
  const customNodeServerUrls: Record<string, Record<string, string>> = {}
336
385
  if (Object.keys(customNodes).length > 0) {
@@ -346,9 +395,12 @@ export class NextWorkflowProjectPlugin implements ProjectPlugin {
346
395
  customNodeServerUrls[cnId] = {}
347
396
  for (const seg of cnServerSegments) {
348
397
  const isStreaming = hasStreamingAINode(seg)
398
+ if (routeHasPolicy(cn.protection)) {
399
+ anyGuardedRouteEmitted = true
400
+ }
349
401
  const apiContent = isStreaming
350
- ? generateStreamingServerSegmentAPIRoute(seg, cn.name || cnId)
351
- : generateServerSegmentAPIRoute(seg, cn.name || cnId)
402
+ ? generateStreamingServerSegmentAPIRoute(seg, cn.name || cnId, cn.protection)
403
+ : generateServerSegmentAPIRoute(seg, cn.name || cnId, cn.protection)
352
404
  const fileName = getAPIRouteFileName(cnId, seg.id, cn.name || cnId)
353
405
  customNodeServerUrls[cnId][seg.id] = `/api/workflows/${fileName}`
354
406
  files.set(`workflow-api-cn-${cnId}-${seg.id}`, {
@@ -473,9 +525,12 @@ export class NextWorkflowProjectPlugin implements ProjectPlugin {
473
525
  for (const serverSeg of serverSegments) {
474
526
  hasServerSegments = true
475
527
  const isStreaming = hasStreamingAINode(serverSeg)
528
+ if (routeHasPolicy(workflow.protection)) {
529
+ anyGuardedRouteEmitted = true
530
+ }
476
531
  const apiContent = isStreaming
477
- ? generateStreamingServerSegmentAPIRoute(serverSeg, workflow.name)
478
- : generateServerSegmentAPIRoute(serverSeg, workflow.name)
532
+ ? generateStreamingServerSegmentAPIRoute(serverSeg, workflow.name, workflow.protection)
533
+ : generateServerSegmentAPIRoute(serverSeg, workflow.name, workflow.protection)
479
534
  const fileName = getAPIRouteFileName(workflow.id, serverSeg.id, workflow.name)
480
535
 
481
536
  files.set(`workflow-api-${workflow.id}-${serverSeg.id}`, {
@@ -503,6 +558,23 @@ export class NextWorkflowProjectPlugin implements ProjectPlugin {
503
558
  ],
504
559
  })
505
560
 
561
+ // Shared stateless auth guard, emitted only when at least one emitted
562
+ // route actually bakes a protection policy (so the file is never orphaned).
563
+ // Enforcement is baked per-route as `const __WF_AUTH`; this file is the one
564
+ // runtime that reads the session cookie via getToken.
565
+ if (anyGuardedRouteEmitted) {
566
+ files.set('workflow-auth-guard', {
567
+ path: ['utils', 'workflows'],
568
+ files: [
569
+ {
570
+ name: 'workflow-auth',
571
+ fileType: FileType.JS,
572
+ content: generateWorkflowAuthHelperFile(),
573
+ },
574
+ ],
575
+ })
576
+ }
577
+
506
578
  const serverHandlerCode = this.generateNodeHandlerFile(usedNodeTypes, 'server')
507
579
  if (serverHandlerCode) {
508
580
  files.set('workflow-server-handlers', {
@@ -1213,6 +1285,9 @@ ${entries}
1213
1285
  id: s.id,
1214
1286
  env: s.env,
1215
1287
  hasStreamingAI: hasStreamingAINode(s),
1288
+ // Every node in this segment runs fire-and-forget — dispatch it and
1289
+ // carry on instead of waiting for the database round trip.
1290
+ fireAndForget: isFireAndForgetSegment(s),
1216
1291
  nodes: s.nodes.map((n) => ({
1217
1292
  id: n.id,
1218
1293
  type: n.type,
@@ -1290,6 +1365,27 @@ async function customNode_${safeId}(outerContext, parameters, nodeHandlers) {
1290
1365
  }
1291
1366
  var segUrl = serverUrls[seg.id];
1292
1367
  if (segUrl) {
1368
+ if (seg.fireAndForget) {
1369
+ // Nothing downstream can read this segment's output, so the visitor
1370
+ // never waits for it. The route still awaits each query before it
1371
+ // responds; we just ignore the response. A failure is logged and
1372
+ // cannot reach the custom node's error chain — the workflow has
1373
+ // already moved past this point.
1374
+ __utils.registerPendingNodePromise(
1375
+ context,
1376
+ __runtime.callServerSegment(segUrl, context).catch(function(__ffErr) {
1377
+ console.error('[workflow] Segment "' + seg.id + '" failed (not awaited):', __ffErr);
1378
+ })
1379
+ );
1380
+ for (var __ffi = 0; __ffi < seg.nodes.length; __ffi++) {
1381
+ // A node on a branch that was not taken must stay absent from the
1382
+ // context, exactly as it would if the segment had been awaited.
1383
+ if (context.__skippedNodes && context.__skippedNodes[seg.nodes[__ffi].id]) continue;
1384
+ context[seg.nodes[__ffi].id] = null;
1385
+ }
1386
+ context.__previousNodeResult = null;
1387
+ continue;
1388
+ }
1293
1389
  if (seg.hasStreamingAI) {
1294
1390
  var streamHandled = await __runtime.callStreamingServerSegment(segUrl, context, streamingInfo, nodes, edges, nodeHandlers, wfConfig, executionId);
1295
1391
  Object.assign(handledNodeIds, streamHandled);
@@ -1356,10 +1452,16 @@ async function customNode_${safeId}(outerContext, parameters, nodeHandlers) {
1356
1452
  }
1357
1453
  }
1358
1454
 
1359
- var sortedNodeIds = nodes.slice().sort(function(a, b) { return a.stepNumber - b.stepNumber; }).map(function(n) { return n.id; });
1455
+ // The custom node returns its last executed node's output. A fire-and-forget
1456
+ // node is excluded: it always stores \`null\`, so if it happens to be last it
1457
+ // would turn the whole custom node's result into null for every caller.
1458
+ var __returnableNodes = nodes
1459
+ .slice()
1460
+ .sort(function(a, b) { return a.stepNumber - b.stepNumber; })
1461
+ .filter(function(n) { return !__utils.isFireAndForgetNode(n); });
1360
1462
  var lastNodeId = null;
1361
- for (var __ri = sortedNodeIds.length - 1; __ri >= 0; __ri--) {
1362
- if (context[sortedNodeIds[__ri]] !== undefined) { lastNodeId = sortedNodeIds[__ri]; break; }
1463
+ for (var __ri = __returnableNodes.length - 1; __ri >= 0; __ri--) {
1464
+ if (context[__returnableNodes[__ri].id] !== undefined) { lastNodeId = __returnableNodes[__ri].id; break; }
1363
1465
  }
1364
1466
  return lastNodeId ? context[lastNodeId] : {};
1365
1467
  }`)
@@ -1416,10 +1518,16 @@ async function customNode_${safeId}(outerContext, parameters, nodeHandlers) {
1416
1518
  }
1417
1519
  }
1418
1520
 
1419
- var sortedNodeIds = nodes.slice().sort(function(a, b) { return a.stepNumber - b.stepNumber; }).map(function(n) { return n.id; });
1521
+ // The custom node returns its last executed node's output. A fire-and-forget
1522
+ // node is excluded: it always stores \`null\`, so if it happens to be last it
1523
+ // would turn the whole custom node's result into null for every caller.
1524
+ var __returnableNodes = nodes
1525
+ .slice()
1526
+ .sort(function(a, b) { return a.stepNumber - b.stepNumber; })
1527
+ .filter(function(n) { return !__utils.isFireAndForgetNode(n); });
1420
1528
  var lastNodeId = null;
1421
- for (var __ri = sortedNodeIds.length - 1; __ri >= 0; __ri--) {
1422
- if (context[sortedNodeIds[__ri]] !== undefined) { lastNodeId = sortedNodeIds[__ri]; break; }
1529
+ for (var __ri = __returnableNodes.length - 1; __ri >= 0; __ri--) {
1530
+ if (context[__returnableNodes[__ri].id] !== undefined) { lastNodeId = __returnableNodes[__ri].id; break; }
1423
1531
  }
1424
1532
  return lastNodeId ? context[lastNodeId] : {};
1425
1533
  }`)
@@ -1463,6 +1571,30 @@ module.exports = __customNodeRegistry;
1463
1571
  ],
1464
1572
  })
1465
1573
 
1574
+ // Shared by the NextAuth route (which uses it to reject an unresolved
1575
+ // NEXTAUTH_URL placeholder) and, when credentials are on, by `authorize`.
1576
+ // Emitted unconditionally because the route always exists.
1577
+ files.set('auth-db-health', {
1578
+ path: ['utils', 'auth'],
1579
+ files: [
1580
+ {
1581
+ name: 'db-health',
1582
+ fileType: FileType.JS,
1583
+ content: generateAuthDbHealthFile(),
1584
+ },
1585
+ ],
1586
+ })
1587
+ files.set('auth-error-messages', {
1588
+ path: ['utils', 'auth'],
1589
+ files: [
1590
+ {
1591
+ name: 'auth-error-messages',
1592
+ fileType: FileType.JS,
1593
+ content: generateAuthErrorMessagesFile(),
1594
+ },
1595
+ ],
1596
+ })
1597
+
1466
1598
  if (auth.passwordAuthEnabled) {
1467
1599
  const hashPasswordCode = generateHashPasswordFile()
1468
1600
  files.set('auth-hash-password', {
@@ -1546,6 +1678,22 @@ module.exports = __customNodeRegistry;
1546
1678
  })
1547
1679
  }
1548
1680
 
1681
+ // Emitted BEFORE session-provider so its file lands next to it. session-provider
1682
+ // imports it first (`import './nextauth-url-guard'`) to strip an empty
1683
+ // NEXTAUTH_URL out of process.env before next-auth/react's module-load
1684
+ // `parseUrl('')` throws "Invalid URL" and crashes SSR. See
1685
+ // generateNextAuthUrlGuardModule.
1686
+ files.set('auth-nextauth-url-guard', {
1687
+ path: ['utils', 'auth'],
1688
+ files: [
1689
+ {
1690
+ name: 'nextauth-url-guard',
1691
+ fileType: FileType.JS,
1692
+ content: generateNextAuthUrlGuardModule(),
1693
+ },
1694
+ ],
1695
+ })
1696
+
1549
1697
  const sessionProviderCode = generateSessionProviderWrapper()
1550
1698
  files.set('auth-session-provider', {
1551
1699
  path: ['utils', 'auth'],
@@ -1895,15 +2043,34 @@ export function resolveAuthEnvValue(
1895
2043
  value: string,
1896
2044
  preserveKeys?: Set<string>
1897
2045
  ): string {
1898
- if (value.startsWith('teleporthq.secrets.')) {
1899
- // NEXTAUTH_URL / NEXTAUTH_SECRET get a local default (the worker does not
1900
- // manage them). OAuth provider credential refs are PRESERVED so the deploy
1901
- // worker resolves them from the project secret store — emptying them (the
1902
- // old behavior) left the deployed env var blank, so NextAuth could not build
1903
- // the provider's authorization URL (error=OAuthSignin / "nothing happens").
1904
- if (Object.prototype.hasOwnProperty.call(AUTH_ENV_DEFAULTS, key)) {
1905
- return AUTH_ENV_DEFAULTS[key]
1906
- }
2046
+ const isSecretPlaceholder = typeof value === 'string' && value.startsWith('teleporthq.secrets.')
2047
+ const isBlank = typeof value !== 'string' || value.trim() === ''
2048
+
2049
+ // NEXTAUTH_URL / NEXTAUTH_SECRET must never reach the generated `.env` as an
2050
+ // EMPTY assignment. next-auth v4's `react/index.js` runs
2051
+ // `parseUrl(process.env.NEXTAUTH_URL)` at MODULE LOAD, and `new URL('')`
2052
+ // throws "Invalid URL" — which crashes server-side rendering for every page
2053
+ // that mounts SessionProvider through `_app` (an UNSET var is fine, because
2054
+ // parseUrl defaults it, but `createEnvFiles` writes every key, so a blank
2055
+ // value serializes as the crashing `NEXTAUTH_URL=`). The blank case is real
2056
+ // and self-perpetuating: once an older generation left `NEXTAUTH_URL=` on
2057
+ // disk, the standalone harness's `preserveExistingEnv` re-injects that empty
2058
+ // string, and this resolver used to pass it straight through. Healing a blank
2059
+ // (or still-unresolved placeholder) auth key to its local default keeps the
2060
+ // value a valid origin; the deploy worker and the runtime request-derivation
2061
+ // (`absolutizeNextAuthUrl`) override it with the real one in production.
2062
+ if (
2063
+ Object.prototype.hasOwnProperty.call(AUTH_ENV_DEFAULTS, key) &&
2064
+ (isSecretPlaceholder || isBlank)
2065
+ ) {
2066
+ return AUTH_ENV_DEFAULTS[key]
2067
+ }
2068
+
2069
+ if (isSecretPlaceholder) {
2070
+ // OAuth provider credential refs are PRESERVED so the deploy worker resolves
2071
+ // them from the project secret store — emptying them (the old behavior) left
2072
+ // the deployed env var blank, so NextAuth could not build the provider's
2073
+ // authorization URL (error=OAuthSignin / "nothing happens").
1907
2074
  if (ALWAYS_PRESERVE_SECRET_ENV_KEYS.has(key)) {
1908
2075
  return value
1909
2076
  }