processfocus 0.1.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +28 -0
- package/README.md +14 -0
- package/dist/auth-FmXptohB.mjs +275 -0
- package/dist/auth-config/src/lib/authentication-config.d.ts +146 -0
- package/dist/auth-config/src/lib/custom-entities-config.d.ts +47 -0
- package/dist/auth-config/src/lib/policies-config.d.ts +52 -0
- package/dist/auth-config/src/lib/provider-types.d.ts +194 -0
- package/dist/auth.d.ts +4 -0
- package/dist/auth.mjs +2 -0
- package/dist/business-calendar/src/index.d.ts +10 -0
- package/dist/business-calendar/src/lib/calendar-config.d.ts +163 -0
- package/dist/business-calendar/src/lib/calendar-period.d.ts +88 -0
- package/dist/business-calendar/src/lib/calendar-service-impl.d.ts +19 -0
- package/dist/business-calendar/src/lib/calendar-service.d.ts +215 -0
- package/dist/business-calendar/src/lib/datetime-utils.d.ts +30 -0
- package/dist/business-calendar/src/lib/duration-calculator.d.ts +49 -0
- package/dist/business-calendar/src/lib/errors.d.ts +69 -0
- package/dist/business-calendar/src/lib/holiday-calculator.d.ts +61 -0
- package/dist/business-calendar/src/lib/holidays.d.ts +141 -0
- package/dist/business-calendar/src/lib/types.d.ts +110 -0
- package/dist/calendar.d.ts +1 -0
- package/dist/calendar.mjs +1204 -0
- package/dist/form-client-representation/src/index.d.ts +6 -0
- package/dist/form-client-representation/src/lib/as-client-representation.d.ts +31 -0
- package/dist/form-client-representation/src/lib/client-form-definition.d.ts +17 -0
- package/dist/form-client-representation/src/lib/extract-annotations.d.ts +20 -0
- package/dist/form-client-representation/src/lib/plugin-registry.d.ts +6 -0
- package/dist/form-client-representation/src/lib/types.d.ts +239 -0
- package/dist/form-client-representation/src/lib/walker.d.ts +68 -0
- package/dist/form-rule/src/index.d.ts +3 -0
- package/dist/form-rule/src/lib/evaluator.d.ts +2 -0
- package/dist/form-rule/src/lib/paths.d.ts +9 -0
- package/dist/form-rule/src/lib/types.d.ts +89 -0
- package/dist/form-schema/src/index.d.ts +8 -0
- package/dist/form-schema/src/lib/annotation-helpers.d.ts +8 -0
- package/dist/form-schema/src/lib/deferred-value.d.ts +10 -0
- package/dist/form-schema/src/lib/email.d.ts +23 -0
- package/dist/form-schema/src/lib/field-count.d.ts +32 -0
- package/dist/form-schema/src/lib/form-annotations.d.ts +25 -0
- package/dist/form-schema/src/lib/form-schema.d.ts +459 -0
- package/dist/form-schema/src/lib/phone.d.ts +4 -0
- package/dist/form-schema/src/lib/property-signature.d.ts +3 -0
- package/dist/form-submission-schema/src/index.d.ts +2 -0
- package/dist/form-submission-schema/src/lib/form-submission-schema.d.ts +49 -0
- package/dist/form-submission-schema/src/lib/schema-defaults.d.ts +16 -0
- package/dist/forms.d.ts +1 -0
- package/dist/forms.mjs +2 -0
- package/dist/frontend-manifest/src/index.d.ts +2 -0
- package/dist/frontend-manifest/src/lib/browser-plugin-artifact.d.ts +25 -0
- package/dist/frontend-manifest/src/lib/frontend-manifest.d.ts +83 -0
- package/dist/frontend-plugin-host/src/index.d.ts +2 -0
- package/dist/frontend-plugin-host/src/lib/frontend-plugin-host.d.ts +124 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.mjs +3780 -0
- package/dist/manifest.d.ts +2 -0
- package/dist/manifest.mjs +5 -0
- package/dist/paths-BkzLn-rG.mjs +282 -0
- package/dist/plugin.d.ts +3 -0
- package/dist/plugin.mjs +84 -0
- package/dist/process/src/lib/app-icons.d.ts +52 -0
- package/dist/process/src/lib/brands.d.ts +20 -0
- package/dist/process/src/lib/document-store.d.ts +30 -0
- package/dist/process/src/lib/execution-failure-notifications.d.ts +14 -0
- package/dist/process/src/lib/flow-context.d.ts +181 -0
- package/dist/process/src/lib/flow-path.d.ts +123 -0
- package/dist/process/src/lib/form-authoring.d.ts +19 -0
- package/dist/process/src/lib/form-decoration.d.ts +13 -0
- package/dist/process/src/lib/form-defaults.d.ts +5 -0
- package/dist/process/src/lib/form.d.ts +557 -0
- package/dist/process/src/lib/invitation.d.ts +35 -0
- package/dist/process/src/lib/list.d.ts +447 -0
- package/dist/process/src/lib/lookup-accessor.d.ts +68 -0
- package/dist/process/src/lib/node_step.d.ts +68 -0
- package/dist/process/src/lib/org-unit.d.ts +53 -0
- package/dist/process/src/lib/org-utils.d.ts +56 -0
- package/dist/process/src/lib/organisation-frontend-plugin-manifest.d.ts +33 -0
- package/dist/process/src/lib/organisation.d.ts +166 -0
- package/dist/process/src/lib/phase.d.ts +16 -0
- package/dist/process/src/lib/process.d.ts +196 -0
- package/dist/process/src/lib/public-form-branding.d.ts +27 -0
- package/dist/process/src/lib/role.d.ts +29 -0
- package/dist/process/src/lib/schedule.d.ts +239 -0
- package/dist/process/src/lib/sla.d.ts +84 -0
- package/dist/process/src/lib/stats-view.d.ts +68 -0
- package/dist/process/src/lib/step.d.ts +130 -0
- package/dist/process/src/lib/system-step-executor.d.ts +130 -0
- package/dist/process/src/lib/system-step.d.ts +248 -0
- package/dist/sdk/src/auth.d.ts +4 -0
- package/dist/sdk/src/calendar.d.ts +1 -0
- package/dist/sdk/src/forms.d.ts +1 -0
- package/dist/sdk/src/index.d.ts +26 -0
- package/dist/sdk/src/manifest.d.ts +2 -0
- package/dist/sdk/src/plugin.d.ts +3 -0
- package/dist/sdk/src/testing.d.ts +9 -0
- package/dist/src-C-909PVQ.mjs +498 -0
- package/dist/testing.d.ts +9 -0
- package/dist/testing.mjs +5 -0
- package/package.json +67 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,3780 @@
|
|
|
1
|
+
import { A as LINK_URL_SYMBOL, C as FLATTEN_SYMBOL, Ct as FormRequired, D as LINK_COLOR_SYMBOL, Dt as FormTextAreaInput, Et as FormTableInput, F as METRIC_BREAKDOWN_SYMBOL, H as STRUCTURAL_ONLY_SYMBOL, K as TEXTBLOCK_CONTENT_SYMBOL, O as LINK_DISPLAY_SYMBOL, St as FormReadOnly, Tt as FormSuggestionInput, U as STRUCTURAL_TYPE_SYMBOL, X as TextBlock, _t as FormNumberInput, at as FormAutoComplete, bt as FormProviderUserInput, ct as FormDateInput, d as isDeferredValue, dt as FormEmailInput, f as fieldAnnotation, ft as FormFileInput, g as isReadOnlyField, gt as FormMessage, h as hasStructuralOnlyAnnotation, ht as FormLookupInput, it as isMetricBreakdownOptions, k as LINK_TEXT_SYMBOL, l as DeferredValueTypeId, lt as FormDefault, m as hasFlattenAnnotation, mt as FormListInput, ot as FormCalendarSlotInput, p as fieldInputAst, pt as FormLabel, q as TEXTBLOCK_DYNAMIC_CONTENT_SYMBOL, rt as isListFieldMetadata, t as mapFormPropertySignature, tt as isFieldPermissionMetadata, u as FormDeferredContent, ut as FormDescription, vt as FormPermission, wt as FormStaticText, xt as FormRadioInput, y as CurrentProviderUser, yt as FormPhoneInput } from "./src-C-909PVQ.mjs";
|
|
2
|
+
import { r as evaluateFormRules, t as formRuleConditionPaths } from "./paths-BkzLn-rG.mjs";
|
|
3
|
+
import { _ as AuthenticationConfig, a as KeycloakOAuthProviderConfigSchema, c as OAuthProviderConfigSchema, d as SecretClientConfigSchema, f as SlackOAuthProviderConfigSchema, g as isCustomEntitiesConfig, h as CustomEntitiesConfig, i as GoogleOAuthProviderConfigSchema, l as OAuthProviderNameSchema, m as isPoliciesConfig, n as CognitoOAuthProviderConfigSchema, o as MicrosoftOAuthProviderConfigSchema, p as PoliciesConfig, r as DEFAULT_OAUTH_PROVIDER_SCOPES, s as OAUTH_PROVIDER_NAMES, t as AppleOAuthProviderConfigSchema, u as PasskeyProviderConfigSchema, v as isAuthenticationConfig } from "./auth-FmXptohB.mjs";
|
|
4
|
+
import { Construct } from "constructs";
|
|
5
|
+
import { Context, Data, Duration, Effect, Either, JSONSchema, Match, Option, Schema, SchemaAST, String as String$1 } from "effect";
|
|
6
|
+
import * as AST from "effect/SchemaAST";
|
|
7
|
+
import { TitleAnnotationId } from "effect/SchemaAST";
|
|
8
|
+
import { getMatchingPlugin } from "@processfocus/runtime";
|
|
9
|
+
import DirectedGraph from "graphology";
|
|
10
|
+
//#region ../process/src/lib/app-icons.ts
|
|
11
|
+
const VALID_MANIFEST_ICON_PURPOSES = /* @__PURE__ */ new Set([
|
|
12
|
+
"any",
|
|
13
|
+
"maskable",
|
|
14
|
+
"monochrome"
|
|
15
|
+
]);
|
|
16
|
+
var AppIcons = class extends Construct {
|
|
17
|
+
isAppIcons = true;
|
|
18
|
+
metadata;
|
|
19
|
+
manifest;
|
|
20
|
+
constructor(scope, id, props) {
|
|
21
|
+
super(scope, id);
|
|
22
|
+
if ((props.metadata?.length ?? 0) + (props.manifest?.length ?? 0) === 0) throw new Error(`AppIcons "${id}" must declare at least one icon`);
|
|
23
|
+
for (const icon of props.manifest ?? []) {
|
|
24
|
+
if (icon.sizes.trim().length === 0) throw new Error(`AppIcons "${id}" manifest icons must declare sizes`);
|
|
25
|
+
const purposeTokens = icon.purpose?.split(" ").filter((token) => token.length > 0);
|
|
26
|
+
if (purposeTokens && (purposeTokens.length === 0 || purposeTokens.some((token) => !VALID_MANIFEST_ICON_PURPOSES.has(token)))) throw new Error(`AppIcons "${id}" manifest icon purpose must use any, maskable, or monochrome`);
|
|
27
|
+
}
|
|
28
|
+
this.metadata = props.metadata ?? [];
|
|
29
|
+
this.manifest = props.manifest ?? [];
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region ../process/src/lib/brands.ts
|
|
34
|
+
const hasBrand = (value, brand) => typeof value === "object" && value !== null && brand in value && value[brand] === true;
|
|
35
|
+
const isDocumentStore = (value) => hasBrand(value, "isDocumentStore");
|
|
36
|
+
const isForm = (value) => hasBrand(value, "isForm");
|
|
37
|
+
const isInvitation = (value) => hasBrand(value, "isInvitation");
|
|
38
|
+
const isList = (value) => hasBrand(value, "isList");
|
|
39
|
+
const isOrgUnit = (value) => hasBrand(value, "isOrgUnit");
|
|
40
|
+
const isOrganisation = (value) => hasBrand(value, "isOrganisation");
|
|
41
|
+
const isProcess = (value) => hasBrand(value, "isProcess");
|
|
42
|
+
const isRole = (value) => hasBrand(value, "isRole");
|
|
43
|
+
const isStatsView = (value) => hasBrand(value, "isStatsView");
|
|
44
|
+
const isStep = (value) => hasBrand(value, "isStep");
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region ../process/src/lib/document-store.ts
|
|
47
|
+
const DEFAULT_MAX_FILE_SIZE = 104857600;
|
|
48
|
+
/**
|
|
49
|
+
* A document store for file uploads and downloads.
|
|
50
|
+
*
|
|
51
|
+
* Attach this to an Organisation to enable presigned URL-based file
|
|
52
|
+
* operations. The runtime provides the actual storage implementation
|
|
53
|
+
* (local filesystem or S3).
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```typescript
|
|
57
|
+
* new DocumentStore(org, "document-store", {
|
|
58
|
+
* acceptedTypes: ["application/zip"],
|
|
59
|
+
* maxFileSize: 50 * 1024 * 1024, // 50MB
|
|
60
|
+
* expirationDays: 3, // Delete files after 3 days
|
|
61
|
+
* })
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
var DocumentStore = class extends Construct {
|
|
65
|
+
acceptedTypes;
|
|
66
|
+
maxFileSize;
|
|
67
|
+
expirationDays;
|
|
68
|
+
isDocumentStore = true;
|
|
69
|
+
constructor(scope, id, props) {
|
|
70
|
+
super(scope, id);
|
|
71
|
+
this.acceptedTypes = props?.acceptedTypes ?? [];
|
|
72
|
+
this.maxFileSize = props?.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
|
|
73
|
+
this.expirationDays = props?.expirationDays;
|
|
74
|
+
if (this.expirationDays !== void 0 && this.expirationDays < 1) throw new Error(`DocumentStore "${id}": expirationDays must be >= 1`);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region ../process/src/lib/execution-failure-notifications.ts
|
|
79
|
+
/**
|
|
80
|
+
* Org-wide configuration for fatal execution failure notifications.
|
|
81
|
+
*/
|
|
82
|
+
var ExecutionFailureNotifications = class extends Construct {
|
|
83
|
+
isExecutionFailureNotifications = true;
|
|
84
|
+
roles;
|
|
85
|
+
constructor(scope, props = {}) {
|
|
86
|
+
super(scope, "ExecutionFailureNotifications");
|
|
87
|
+
this.roles = props.roles ?? [];
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
//#endregion
|
|
91
|
+
//#region ../process/src/lib/flow-path.ts
|
|
92
|
+
function assertSameProcess(step, process) {
|
|
93
|
+
if (step.process !== process) throw new Error(`Step "${step.node.path}" belongs to a different process than "${process.node.path}"`);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Wraps a step in a FlowPath without adding an edge.
|
|
97
|
+
* Used by Process.start() which handles edge creation separately.
|
|
98
|
+
*/
|
|
99
|
+
function wrapInFlowPath(step, process) {
|
|
100
|
+
assertSameProcess(step, process);
|
|
101
|
+
return new FlowPath(step, process);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Creates a FlowPath by connecting two steps with an edge.
|
|
105
|
+
* This is the core implementation used by both Step.next() and FlowPath.next().
|
|
106
|
+
*
|
|
107
|
+
* Note: The type assertion on toStep is safe because TState is a phantom type
|
|
108
|
+
* (Step.__scopeState is never populated at runtime). We're reinterpreting the
|
|
109
|
+
* Step's type-level state to include accumulated state from the flow.
|
|
110
|
+
*
|
|
111
|
+
* @typeParam TIsForm - Whether the target step is a Form (determines meta type)
|
|
112
|
+
* @typeParam TIsForEach - Whether the target step is a forEach step (array state)
|
|
113
|
+
*/
|
|
114
|
+
function createFlowPath(fromStep, toStep, process, options) {
|
|
115
|
+
assertSameProcess(fromStep, process);
|
|
116
|
+
assertSameProcess(toStep, process);
|
|
117
|
+
process.addEdge(fromStep, toStep, {
|
|
118
|
+
condition: options?.condition?.fn,
|
|
119
|
+
conditionText: options?.condition?.text,
|
|
120
|
+
schedule: options?.schedule?.fn,
|
|
121
|
+
scheduleText: options?.schedule?.text
|
|
122
|
+
});
|
|
123
|
+
return new FlowPath(toStep, process);
|
|
124
|
+
}
|
|
125
|
+
function createOnErrorFlowPath(fromStep, toStep, process, options) {
|
|
126
|
+
assertSameProcess(fromStep, process);
|
|
127
|
+
assertSameProcess(toStep, process);
|
|
128
|
+
process.addEdge(fromStep, toStep, {
|
|
129
|
+
isOnError: true,
|
|
130
|
+
...options?.taggedErrors !== void 0 && { taggedErrors: options.taggedErrors }
|
|
131
|
+
});
|
|
132
|
+
return new FlowPath(toStep, process);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* FlowPath represents a position in a process flow with accumulated state and step metadata.
|
|
136
|
+
*
|
|
137
|
+
* @typeParam TState - Accumulated state type from completed steps
|
|
138
|
+
* @typeParam TOutput - Output schema of the current step
|
|
139
|
+
* @typeParam TSteps - Record of completed step metadata, keyed by camelCase step ID
|
|
140
|
+
*/
|
|
141
|
+
var FlowPath = class {
|
|
142
|
+
step;
|
|
143
|
+
process;
|
|
144
|
+
/** Phantom type field to carry accumulated state for type inference */
|
|
145
|
+
__scopeState;
|
|
146
|
+
/** Phantom type field to carry completed steps for type inference */
|
|
147
|
+
__scopeSteps;
|
|
148
|
+
constructor(step, process) {
|
|
149
|
+
this.step = step;
|
|
150
|
+
this.process = process;
|
|
151
|
+
}
|
|
152
|
+
end(step, options) {
|
|
153
|
+
if (step) {
|
|
154
|
+
assertSameProcess(step, this.process);
|
|
155
|
+
this.step.process.addEdge(this.step, step, {
|
|
156
|
+
condition: options?.condition?.fn,
|
|
157
|
+
conditionText: options?.condition?.text,
|
|
158
|
+
schedule: options?.schedule?.fn,
|
|
159
|
+
scheduleText: options?.schedule?.text
|
|
160
|
+
});
|
|
161
|
+
this.process.addEndEdge(step);
|
|
162
|
+
return step;
|
|
163
|
+
}
|
|
164
|
+
this.process.addEndEdge(this.step);
|
|
165
|
+
return this.step;
|
|
166
|
+
}
|
|
167
|
+
next(target, options) {
|
|
168
|
+
return createFlowPath(this.step, target, this.process, options);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Returns an ElseBranch that can be used to define the else edge.
|
|
172
|
+
* The else edge is followed ONLY if NO conditional edges match.
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* flow.next(stepApproved, (s) => s.approved)
|
|
176
|
+
* flow.else().next(stepRejected).end()
|
|
177
|
+
*/
|
|
178
|
+
else() {
|
|
179
|
+
return new ElseBranch(this.step, this.process);
|
|
180
|
+
}
|
|
181
|
+
elseEnd(step, options) {
|
|
182
|
+
if (step) return this.else().end(step, options);
|
|
183
|
+
return this.else().end();
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Shorthand for .else().next(target) - creates an else edge to target step.
|
|
187
|
+
*/
|
|
188
|
+
elseNext(target, options) {
|
|
189
|
+
return this.else().next(target, options);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
/**
|
|
193
|
+
* Represents an else branch from a flow path.
|
|
194
|
+
* The else edge is followed ONLY if NO conditional edges from the source step match.
|
|
195
|
+
*/
|
|
196
|
+
var ElseBranch = class {
|
|
197
|
+
step;
|
|
198
|
+
process;
|
|
199
|
+
constructor(step, process) {
|
|
200
|
+
this.step = step;
|
|
201
|
+
this.process = process;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Create an else edge to the next step.
|
|
205
|
+
*/
|
|
206
|
+
next(target, options) {
|
|
207
|
+
assertSameProcess(target, this.process);
|
|
208
|
+
this.process.addEdge(this.step, target, {
|
|
209
|
+
isElse: true,
|
|
210
|
+
conditionText: options?.text
|
|
211
|
+
});
|
|
212
|
+
return new FlowPath(target, this.process);
|
|
213
|
+
}
|
|
214
|
+
end(step, options) {
|
|
215
|
+
if (step) {
|
|
216
|
+
assertSameProcess(step, this.process);
|
|
217
|
+
this.process.addEdge(this.step, step, {
|
|
218
|
+
isElse: true,
|
|
219
|
+
conditionText: options?.text
|
|
220
|
+
});
|
|
221
|
+
this.process.addEndEdge(step);
|
|
222
|
+
return step;
|
|
223
|
+
}
|
|
224
|
+
this.process.addElseEndEdge(this.step);
|
|
225
|
+
return this.step;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
//#endregion
|
|
229
|
+
//#region ../form-client-representation/src/lib/extract-annotations.ts
|
|
230
|
+
const toFullPath = (path) => path.startsWith("/") ? path : `/${path}`;
|
|
231
|
+
const defaultSchemaTitles = /* @__PURE__ */ new Set([
|
|
232
|
+
"any",
|
|
233
|
+
"bigint",
|
|
234
|
+
"string",
|
|
235
|
+
"number",
|
|
236
|
+
"boolean",
|
|
237
|
+
"null",
|
|
238
|
+
"never",
|
|
239
|
+
"object",
|
|
240
|
+
"symbol",
|
|
241
|
+
"undefined",
|
|
242
|
+
"unknown",
|
|
243
|
+
"void"
|
|
244
|
+
]);
|
|
245
|
+
const isGeneratedSchemaTitle = (value) => defaultSchemaTitles.has(value) || /^[a-z]+\(.*\)$/i.test(value);
|
|
246
|
+
const humanizeFieldName = (fieldName) => {
|
|
247
|
+
const spaced = fieldName.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").trim();
|
|
248
|
+
if (spaced.length === 0) return fieldName;
|
|
249
|
+
return `${spaced.charAt(0).toUpperCase()}${spaced.slice(1).toLowerCase()}`;
|
|
250
|
+
};
|
|
251
|
+
/**
|
|
252
|
+
* Extract FormLabel, FormDescription, and FormReadOnly annotations from AST.
|
|
253
|
+
* Note: FormDefault is handled separately at runtime when process state is available.
|
|
254
|
+
*/
|
|
255
|
+
const extractAnnotations = (annotations, fieldName) => {
|
|
256
|
+
const labelValue = annotations[FormLabel];
|
|
257
|
+
const titleValue = annotations[TitleAnnotationId];
|
|
258
|
+
const title = typeof titleValue === "string" && !isGeneratedSchemaTitle(titleValue) ? titleValue : void 0;
|
|
259
|
+
const result = { label: typeof labelValue === "string" && labelValue.length > 0 ? labelValue : title ?? humanizeFieldName(fieldName) };
|
|
260
|
+
const descValue = annotations[FormDescription];
|
|
261
|
+
if (typeof descValue === "string") result.description = descValue;
|
|
262
|
+
const autoCompleteValue = annotations[FormAutoComplete];
|
|
263
|
+
if (typeof autoCompleteValue === "string") result.autoComplete = autoCompleteValue;
|
|
264
|
+
const readOnlyValue = annotations[FormReadOnly];
|
|
265
|
+
if (typeof readOnlyValue === "boolean") result.readonly = readOnlyValue;
|
|
266
|
+
const permissionValue = annotations[FormPermission];
|
|
267
|
+
if (isFieldPermissionMetadata(permissionValue)) result.permission = { modify: toFullPath(permissionValue.modify.node.path) };
|
|
268
|
+
const requiredValue = annotations[FormRequired];
|
|
269
|
+
if (typeof requiredValue === "boolean") result.required = requiredValue;
|
|
270
|
+
const staticTextValue = annotations[FormStaticText];
|
|
271
|
+
if (typeof staticTextValue === "string") result.content = staticTextValue;
|
|
272
|
+
return result;
|
|
273
|
+
};
|
|
274
|
+
//#endregion
|
|
275
|
+
//#region ../form-client-representation/src/lib/walker.ts
|
|
276
|
+
/**
|
|
277
|
+
* Error types for walker failures
|
|
278
|
+
*/
|
|
279
|
+
var UnknownSchemaFieldTypeError = class extends Data.TaggedError("UnknownSchemaFieldTypeError") {
|
|
280
|
+
get message() {
|
|
281
|
+
return `Cannot create form field "${this.fieldName}": schema type "${this.schemaType}" is not supported`;
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
var IndexSignaturesNotSupportedError = class extends Data.TaggedError("IndexSignaturesNotSupportedError") {
|
|
285
|
+
get message() {
|
|
286
|
+
return "Index signatures are not supported in schemas";
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
var UnrecognizedASTNodeError = class extends Data.TaggedError("UnrecognizedASTNodeError") {
|
|
290
|
+
get message() {
|
|
291
|
+
return `AST node type "${this.nodeTag}" is not recognized`;
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
var InvalidPropertyKeyError = class extends Data.TaggedError("InvalidPropertyKeyError") {
|
|
295
|
+
get message() {
|
|
296
|
+
return `Property keys must be strings or numbers, got: ${String(this.propertyKey)}`;
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
var InvalidFieldPermissionError = class extends Data.TaggedError("InvalidFieldPermissionError") {
|
|
300
|
+
get message() {
|
|
301
|
+
return `Cannot apply field permission to "${this.fieldName}": ${this.reason}`;
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
var InvalidStaticLinkError = class extends Data.TaggedError("InvalidStaticLinkError") {
|
|
305
|
+
get message() {
|
|
306
|
+
return `Cannot create link field "${this.fieldName}": url must use http, https, or mailto and text must be a string`;
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
/**
|
|
310
|
+
* Validates that a property key is not a symbol
|
|
311
|
+
* Returns an Effect that fails if the key is a symbol
|
|
312
|
+
*/
|
|
313
|
+
const validatePropertyKey = (propertyKey) => {
|
|
314
|
+
if (typeof propertyKey === "symbol") return Effect.fail(new InvalidPropertyKeyError({ propertyKey }));
|
|
315
|
+
return Effect.succeed(String(propertyKey));
|
|
316
|
+
};
|
|
317
|
+
/**
|
|
318
|
+
* Main walker function that processes Effect Schema AST and emits form structure
|
|
319
|
+
*
|
|
320
|
+
* @param ast - The Effect Schema AST to walk
|
|
321
|
+
* @param parentPath - Current path prefix for building field paths
|
|
322
|
+
*/
|
|
323
|
+
const walkAST = (ast, parentPath = "", nestingDepth = 0) => Match.type().pipe(Match.tag("Transformation", (transformation) => walkAST(transformation.from, parentPath, nestingDepth)), Match.tag("TypeLiteral", (typeLiteral) => Effect.gen(function* () {
|
|
324
|
+
const result = {};
|
|
325
|
+
for (const prop of typeLiteral.propertySignatures) {
|
|
326
|
+
const fieldName = yield* validatePropertyKey(prop.name);
|
|
327
|
+
result[fieldName] = yield* processProperty(prop, parentPath, nestingDepth);
|
|
328
|
+
}
|
|
329
|
+
if (typeLiteral.indexSignatures.length > 0) return yield* new IndexSignaturesNotSupportedError();
|
|
330
|
+
return result;
|
|
331
|
+
})), Match.orElse((node) => Effect.fail(new UnrecognizedASTNodeError({ nodeTag: node._tag }))))(ast);
|
|
332
|
+
/**
|
|
333
|
+
* Process a single property signature from the schema
|
|
334
|
+
*/
|
|
335
|
+
const processProperty = (prop, parentPath, nestingDepth) => Effect.gen(function* () {
|
|
336
|
+
const fieldName = yield* validatePropertyKey(prop.name);
|
|
337
|
+
const fieldPath = {
|
|
338
|
+
...prop.type.annotations,
|
|
339
|
+
...prop.annotations
|
|
340
|
+
}[FLATTEN_SYMBOL] ? parentPath : parentPath ? `${parentPath}.${fieldName}` : fieldName;
|
|
341
|
+
return yield* processType(prop.type, prop.annotations, fieldName, fieldPath, prop.isOptional, nestingDepth);
|
|
342
|
+
});
|
|
343
|
+
const hasModifyPermission = (annotations) => {
|
|
344
|
+
return isFieldPermissionMetadata(annotations[FormPermission]);
|
|
345
|
+
};
|
|
346
|
+
const hasDefault = (annotations) => annotations[FormDefault] !== void 0;
|
|
347
|
+
const validatePermissionPlacement = (annotations, fieldName, isOptional, nestingDepth) => {
|
|
348
|
+
if (!hasModifyPermission(annotations)) return Effect.void;
|
|
349
|
+
if (nestingDepth > 0) return Effect.fail(new InvalidFieldPermissionError({
|
|
350
|
+
fieldName,
|
|
351
|
+
reason: "permissions are only supported on top-level submitted fields"
|
|
352
|
+
}));
|
|
353
|
+
if (annotations[FormReadOnly] === true) return Effect.fail(new InvalidFieldPermissionError({
|
|
354
|
+
fieldName,
|
|
355
|
+
reason: "read-only fields cannot declare modify permissions"
|
|
356
|
+
}));
|
|
357
|
+
if (!isOptional && !hasDefault(annotations)) return Effect.fail(new InvalidFieldPermissionError({
|
|
358
|
+
fieldName,
|
|
359
|
+
reason: "restricted required fields must either be optional or declare a default value"
|
|
360
|
+
}));
|
|
361
|
+
return Effect.void;
|
|
362
|
+
};
|
|
363
|
+
const rejectPermission = (annotations, fieldName, reason) => hasModifyPermission(annotations) ? Effect.fail(new InvalidFieldPermissionError({
|
|
364
|
+
fieldName,
|
|
365
|
+
reason
|
|
366
|
+
})) : Effect.void;
|
|
367
|
+
/**
|
|
368
|
+
* Process an AST type node and return the corresponding form component
|
|
369
|
+
*/
|
|
370
|
+
const processType = (type, annotations, fieldName, fieldPath, isOptional, nestingDepth) => {
|
|
371
|
+
const mergedAnnotations = {
|
|
372
|
+
...type.annotations,
|
|
373
|
+
...annotations
|
|
374
|
+
};
|
|
375
|
+
const metadata = extractAnnotations(mergedAnnotations, fieldName);
|
|
376
|
+
if (mergedAnnotations[FormRadioInput]) {
|
|
377
|
+
const radioMeta = mergedAnnotations[FormRadioInput];
|
|
378
|
+
return validatePermissionPlacement(mergedAnnotations, fieldName, isOptional, nestingDepth).pipe(Effect.as({
|
|
379
|
+
field: fieldPath,
|
|
380
|
+
_tag: "radio",
|
|
381
|
+
...metadata,
|
|
382
|
+
options: radioMeta.options
|
|
383
|
+
}));
|
|
384
|
+
}
|
|
385
|
+
const matchedPlugin = getMatchingPlugin(mergedAnnotations);
|
|
386
|
+
if (matchedPlugin) return rejectPermission(mergedAnnotations, fieldName, "plugin field permissions are not supported").pipe(Effect.andThen(Effect.succeed({
|
|
387
|
+
field: fieldPath,
|
|
388
|
+
_tag: "plugin",
|
|
389
|
+
pluginType: matchedPlugin.type,
|
|
390
|
+
pluginData: matchedPlugin.extractData?.(mergedAnnotations),
|
|
391
|
+
...matchedPlugin.scripts !== void 0 && { scripts: matchedPlugin.scripts },
|
|
392
|
+
...metadata
|
|
393
|
+
})));
|
|
394
|
+
return Match.type().pipe(Match.tag("StringKeyword", () => {
|
|
395
|
+
if (typeof mergedAnnotations[FormStaticText] === "string") return rejectPermission(mergedAnnotations, fieldName, "static fields cannot declare permissions").pipe(Effect.andThen(Effect.succeed({
|
|
396
|
+
field: fieldPath,
|
|
397
|
+
_tag: "static",
|
|
398
|
+
...metadata
|
|
399
|
+
})));
|
|
400
|
+
const validPermission = validatePermissionPlacement(mergedAnnotations, fieldName, isOptional, nestingDepth);
|
|
401
|
+
if (mergedAnnotations[FormProviderUserInput]) return validPermission.pipe(Effect.andThen(Effect.succeed({
|
|
402
|
+
field: fieldPath,
|
|
403
|
+
_tag: "provider-user",
|
|
404
|
+
...metadata
|
|
405
|
+
})));
|
|
406
|
+
if (mergedAnnotations[FormLookupInput]) return validPermission.pipe(Effect.andThen(Effect.succeed({
|
|
407
|
+
field: fieldPath,
|
|
408
|
+
_tag: "lookup",
|
|
409
|
+
...metadata,
|
|
410
|
+
...mergedAnnotations[FormSuggestionInput] === true && { allowFreeText: true }
|
|
411
|
+
})));
|
|
412
|
+
if (mergedAnnotations[FormCalendarSlotInput]) {
|
|
413
|
+
const slotMeta = mergedAnnotations[FormCalendarSlotInput];
|
|
414
|
+
return validPermission.pipe(Effect.andThen(Effect.succeed({
|
|
415
|
+
field: fieldPath,
|
|
416
|
+
_tag: "calendar-slot",
|
|
417
|
+
...metadata,
|
|
418
|
+
timeZone: slotMeta.timeZone,
|
|
419
|
+
locale: slotMeta.locale,
|
|
420
|
+
...slotMeta.calendar != null && { calendar: slotMeta.calendar },
|
|
421
|
+
...slotMeta.emptyMessageHtml != null && { emptyMessageHtml: slotMeta.emptyMessageHtml },
|
|
422
|
+
...slotMeta.loadErrorMessageHtml != null && { loadErrorMessageHtml: slotMeta.loadErrorMessageHtml }
|
|
423
|
+
})));
|
|
424
|
+
}
|
|
425
|
+
if (mergedAnnotations[FormFileInput]) {
|
|
426
|
+
const fileMeta = mergedAnnotations[FormFileInput];
|
|
427
|
+
return validPermission.pipe(Effect.andThen(Effect.succeed({
|
|
428
|
+
field: fieldPath,
|
|
429
|
+
_tag: "file",
|
|
430
|
+
...metadata,
|
|
431
|
+
documentStore: fileMeta.documentStore,
|
|
432
|
+
...fileMeta.accept != null && { accept: fileMeta.accept },
|
|
433
|
+
...fileMeta.maxSize != null && { maxSize: fileMeta.maxSize }
|
|
434
|
+
})));
|
|
435
|
+
}
|
|
436
|
+
let fieldType;
|
|
437
|
+
if (mergedAnnotations[FormTextAreaInput]) fieldType = "textarea";
|
|
438
|
+
else if (mergedAnnotations[FormDateInput]) fieldType = "date";
|
|
439
|
+
else if (mergedAnnotations[FormEmailInput]) fieldType = "email";
|
|
440
|
+
else if (mergedAnnotations[FormPhoneInput]) fieldType = "phone";
|
|
441
|
+
else if (mergedAnnotations[FormNumberInput]) fieldType = "number";
|
|
442
|
+
else fieldType = "text";
|
|
443
|
+
return validPermission.pipe(Effect.andThen(Effect.succeed({
|
|
444
|
+
field: fieldPath,
|
|
445
|
+
_tag: fieldType,
|
|
446
|
+
...metadata
|
|
447
|
+
})));
|
|
448
|
+
}), Match.tag("NumberKeyword", () => validatePermissionPlacement(mergedAnnotations, fieldName, isOptional, nestingDepth).pipe(Effect.andThen(Effect.succeed({
|
|
449
|
+
field: fieldPath,
|
|
450
|
+
_tag: "number",
|
|
451
|
+
...metadata
|
|
452
|
+
})))), Match.tag("Literal", (literal) => {
|
|
453
|
+
if (typeof literal.literal !== "string") return Effect.fail(new UnknownSchemaFieldTypeError({
|
|
454
|
+
fieldName,
|
|
455
|
+
schemaType: type._tag
|
|
456
|
+
}));
|
|
457
|
+
return validatePermissionPlacement(mergedAnnotations, fieldName, isOptional, nestingDepth).pipe(Effect.as({
|
|
458
|
+
...metadata,
|
|
459
|
+
_tag: "select",
|
|
460
|
+
field: fieldPath,
|
|
461
|
+
options: [literal.literal],
|
|
462
|
+
...isOptional ? { emptyValue: "undefined" } : {}
|
|
463
|
+
}));
|
|
464
|
+
}), Match.tag("BooleanKeyword", () => validatePermissionPlacement(mergedAnnotations, fieldName, isOptional, nestingDepth).pipe(Effect.andThen(Effect.succeed({
|
|
465
|
+
field: fieldPath,
|
|
466
|
+
_tag: "boolean",
|
|
467
|
+
...metadata
|
|
468
|
+
})))), Match.tag("TypeLiteral", (typeLiteral) => rejectPermission(mergedAnnotations, fieldName, "wrapper-level and fieldset-level permissions are not supported").pipe(Effect.andThen(walkAST(typeLiteral, fieldPath, nestingDepth + 1).pipe(Effect.map((children) => ({
|
|
469
|
+
_tag: "fieldset",
|
|
470
|
+
...metadata,
|
|
471
|
+
children
|
|
472
|
+
})))))), Match.tag("TupleType", (tuple) => {
|
|
473
|
+
const restType = tuple.rest[0];
|
|
474
|
+
const listMetadata = mergedAnnotations[FormListInput];
|
|
475
|
+
if (!restType) return Effect.fail(new UnknownSchemaFieldTypeError({
|
|
476
|
+
fieldName,
|
|
477
|
+
schemaType: "TupleType (empty)"
|
|
478
|
+
}));
|
|
479
|
+
return rejectPermission(mergedAnnotations, fieldName, "list permissions are not supported").pipe(Effect.andThen(walkAST(restType.type, fieldPath, nestingDepth + 1).pipe(Effect.map((itemChildren) => ({
|
|
480
|
+
_tag: mergedAnnotations[FormTableInput] ? "table" : "list",
|
|
481
|
+
field: fieldPath,
|
|
482
|
+
...metadata,
|
|
483
|
+
...isListFieldMetadata(listMetadata) && listMetadata.addButtonLabel !== void 0 && { addButtonLabel: listMetadata.addButtonLabel },
|
|
484
|
+
itemChildren
|
|
485
|
+
})))));
|
|
486
|
+
}), Match.tag("Refinement", (refinement) => processType(refinement.from, {
|
|
487
|
+
...annotations,
|
|
488
|
+
...refinement.annotations
|
|
489
|
+
}, fieldName, fieldPath, isOptional, nestingDepth)), Match.tag("Transformation", (transformation) => processType(transformation.from, {
|
|
490
|
+
...annotations,
|
|
491
|
+
...transformation.annotations
|
|
492
|
+
}, fieldName, fieldPath, isOptional, nestingDepth)), Match.tag("Union", (union) => {
|
|
493
|
+
const nonNullMembers = union.types.filter((t) => !(t._tag === "Literal" && t.literal === null) && t._tag !== "UndefinedKeyword");
|
|
494
|
+
const emptyValue = union.types.some((member) => member._tag === "Literal" && member.literal === null) ? "null" : isOptional || union.types.some((member) => member._tag === "UndefinedKeyword") ? "undefined" : void 0;
|
|
495
|
+
if (nonNullMembers.length === 1 && nonNullMembers[0]) return processType(nonNullMembers[0], {
|
|
496
|
+
...annotations,
|
|
497
|
+
...union.annotations
|
|
498
|
+
}, fieldName, fieldPath, isOptional, nestingDepth).pipe(Effect.map((component) => component._tag === "select" && emptyValue !== void 0 ? {
|
|
499
|
+
...component,
|
|
500
|
+
emptyValue
|
|
501
|
+
} : component));
|
|
502
|
+
const options = nonNullMembers.flatMap((member) => member._tag === "Literal" && typeof member.literal === "string" ? [member.literal] : []);
|
|
503
|
+
if (options.length > 0 && options.length === nonNullMembers.length) return validatePermissionPlacement(mergedAnnotations, fieldName, isOptional, nestingDepth).pipe(Effect.as({
|
|
504
|
+
...metadata,
|
|
505
|
+
_tag: "select",
|
|
506
|
+
field: fieldPath,
|
|
507
|
+
options,
|
|
508
|
+
...emptyValue !== void 0 ? { emptyValue } : {}
|
|
509
|
+
}));
|
|
510
|
+
return Effect.fail(new UnknownSchemaFieldTypeError({
|
|
511
|
+
fieldName,
|
|
512
|
+
schemaType: type._tag
|
|
513
|
+
}));
|
|
514
|
+
}), Match.tag("UndefinedKeyword", () => {
|
|
515
|
+
const structuralAnnotation = AST.getAnnotation(type, STRUCTURAL_ONLY_SYMBOL);
|
|
516
|
+
if (Option.isSome(structuralAnnotation)) return rejectPermission(mergedAnnotations, fieldName, "structural-only fields cannot declare permissions").pipe(Effect.andThen(() => {
|
|
517
|
+
const structuralTypeAnnotation = AST.getAnnotation(type, STRUCTURAL_TYPE_SYMBOL);
|
|
518
|
+
const structuralType = Option.getOrUndefined(structuralTypeAnnotation);
|
|
519
|
+
if (structuralType === "metric-breakdown") {
|
|
520
|
+
const metricAnnotation = AST.getAnnotation(type, METRIC_BREAKDOWN_SYMBOL);
|
|
521
|
+
const options = Option.getOrUndefined(metricAnnotation);
|
|
522
|
+
if (isMetricBreakdownOptions(options)) return Effect.succeed({
|
|
523
|
+
field: fieldPath,
|
|
524
|
+
_tag: "metric-breakdown",
|
|
525
|
+
label: metadata.label,
|
|
526
|
+
readonly: true,
|
|
527
|
+
title: options.title,
|
|
528
|
+
buckets: options.buckets,
|
|
529
|
+
...options.badge !== void 0 && { badge: options.badge },
|
|
530
|
+
...options.currency !== void 0 && { currency: options.currency },
|
|
531
|
+
...options.fields !== void 0 && { fields: options.fields },
|
|
532
|
+
...options.controls !== void 0 && { controls: options.controls },
|
|
533
|
+
...options.contextFields !== void 0 && { contextFields: options.contextFields },
|
|
534
|
+
...options.dataSource !== void 0 && { dataSource: options.dataSource },
|
|
535
|
+
...options.rendererPluginType !== void 0 && { rendererPluginType: options.rendererPluginType },
|
|
536
|
+
...options.rendererPluginData !== void 0 && { rendererPluginData: options.rendererPluginData }
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
if (structuralType === "link") {
|
|
540
|
+
const url = mergedAnnotations[LINK_URL_SYMBOL];
|
|
541
|
+
const text = mergedAnnotations[LINK_TEXT_SYMBOL];
|
|
542
|
+
const display = mergedAnnotations[LINK_DISPLAY_SYMBOL];
|
|
543
|
+
const color = mergedAnnotations[LINK_COLOR_SYMBOL];
|
|
544
|
+
const isButtonLink = display === "button";
|
|
545
|
+
if (typeof url === "string" && /^(https?:|mailto:)/.test(url) && typeof text === "string") return Effect.succeed({
|
|
546
|
+
field: fieldPath,
|
|
547
|
+
_tag: "link",
|
|
548
|
+
readonly: true,
|
|
549
|
+
url,
|
|
550
|
+
text,
|
|
551
|
+
...isButtonLink ? { display } : { label: metadata.label },
|
|
552
|
+
...color === "blue" ? { color } : {}
|
|
553
|
+
});
|
|
554
|
+
return Effect.fail(new InvalidStaticLinkError({
|
|
555
|
+
fieldName: fieldPath,
|
|
556
|
+
url,
|
|
557
|
+
text
|
|
558
|
+
}));
|
|
559
|
+
}
|
|
560
|
+
const contentAnnotation = AST.getAnnotation(type, TEXTBLOCK_CONTENT_SYMBOL);
|
|
561
|
+
const content = Option.getOrUndefined(contentAnnotation);
|
|
562
|
+
return Effect.succeed({
|
|
563
|
+
field: fieldPath,
|
|
564
|
+
_tag: "static",
|
|
565
|
+
label: metadata.label,
|
|
566
|
+
description: metadata.description,
|
|
567
|
+
readonly: true,
|
|
568
|
+
content
|
|
569
|
+
});
|
|
570
|
+
}));
|
|
571
|
+
return Effect.fail(new UnknownSchemaFieldTypeError({
|
|
572
|
+
fieldName,
|
|
573
|
+
schemaType: type._tag
|
|
574
|
+
}));
|
|
575
|
+
}), Match.orElse(() => Effect.fail(new UnknownSchemaFieldTypeError({
|
|
576
|
+
fieldName,
|
|
577
|
+
schemaType: type._tag
|
|
578
|
+
}))))(type);
|
|
579
|
+
};
|
|
580
|
+
//#endregion
|
|
581
|
+
//#region ../form-client-representation/src/lib/as-client-representation.ts
|
|
582
|
+
/**
|
|
583
|
+
* Convert an Effect Schema.Struct to its client-side form representation
|
|
584
|
+
*
|
|
585
|
+
* This function walks the schema's AST and generates a typed structure
|
|
586
|
+
* that mirrors the schema's type shape, with each field mapped to its
|
|
587
|
+
* corresponding form component (TextField, NumberField, etc.).
|
|
588
|
+
*
|
|
589
|
+
* **IMPORTANT**: Only Schema.Struct is supported. The type system prevents
|
|
590
|
+
* passing any other schema type at compile time.
|
|
591
|
+
*
|
|
592
|
+
* @param schema - The Effect Schema.Struct to convert
|
|
593
|
+
* @returns An Effect that produces the client representation
|
|
594
|
+
*
|
|
595
|
+
* @example
|
|
596
|
+
* ```typescript
|
|
597
|
+
* const schema = Schema.Struct({
|
|
598
|
+
* username: Schema.String,
|
|
599
|
+
* age: Schema.NumberFromString,
|
|
600
|
+
* })
|
|
601
|
+
*
|
|
602
|
+
* const representation = await Effect.runPromise(asClientRepresentation(schema))
|
|
603
|
+
* // {
|
|
604
|
+
* // username: { field: "username", type: "text", label: "Username", ... },
|
|
605
|
+
* // age: { field: "age", _tag: "number", label: "Age", ... }
|
|
606
|
+
* // }
|
|
607
|
+
* ```
|
|
608
|
+
*/
|
|
609
|
+
const asClientRepresentation = (schema) => {
|
|
610
|
+
return walkAST(schema.ast);
|
|
611
|
+
};
|
|
612
|
+
//#endregion
|
|
613
|
+
//#region ../form-submission-schema/src/lib/form-submission-schema.ts
|
|
614
|
+
var FieldNameCollisionError = class extends Data.TaggedError("FieldNameCollisionError") {
|
|
615
|
+
get message() {
|
|
616
|
+
return `Field name collision: "${this.wrapperField}" is already present as "${this.fieldName}" in its parent struct`;
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
var InvalidFlattenAnnotationError = class extends Data.TaggedError("InvalidFlattenAnnotationError") {
|
|
620
|
+
get message() {
|
|
621
|
+
return `Invalid schema: field "${this.fieldName}" has flatten annotation but is not a struct (AST tag: ${this.astTag}). Only use Wrapper() with Schema.Struct().`;
|
|
622
|
+
}
|
|
623
|
+
};
|
|
624
|
+
const isFlattenableStruct = (field, fieldName) => Effect.gen(function* () {
|
|
625
|
+
const hasFlatten = hasFlattenAnnotation(field);
|
|
626
|
+
const isStructAst = field.ast._tag === "TypeLiteral";
|
|
627
|
+
if (hasFlatten && !isStructAst) return yield* new InvalidFlattenAnnotationError({
|
|
628
|
+
fieldName,
|
|
629
|
+
astTag: field.ast._tag
|
|
630
|
+
});
|
|
631
|
+
return hasFlatten && isStructAst;
|
|
632
|
+
});
|
|
633
|
+
const submissionSchema = (schema) => Effect.gen(function* () {
|
|
634
|
+
const flatFields = {};
|
|
635
|
+
for (const [key, field] of Object.entries(schema.fields)) {
|
|
636
|
+
const fieldAsAny = field;
|
|
637
|
+
if (hasStructuralOnlyAnnotation(fieldAsAny)) continue;
|
|
638
|
+
if (isReadOnlyField(fieldAsAny)) continue;
|
|
639
|
+
if (yield* isFlattenableStruct(fieldAsAny, String(key))) {
|
|
640
|
+
const recursivelyFlattened = yield* submissionSchema(fieldAsAny);
|
|
641
|
+
for (const [nestedKey, nestedValue] of Object.entries(recursivelyFlattened.fields)) {
|
|
642
|
+
if (nestedKey in flatFields) return yield* new FieldNameCollisionError({
|
|
643
|
+
fieldName: nestedKey,
|
|
644
|
+
wrapperField: `${key}...${nestedKey}`
|
|
645
|
+
});
|
|
646
|
+
flatFields[nestedKey] = nestedValue;
|
|
647
|
+
}
|
|
648
|
+
} else {
|
|
649
|
+
if (key in flatFields) return yield* new FieldNameCollisionError({
|
|
650
|
+
fieldName: key,
|
|
651
|
+
wrapperField: key
|
|
652
|
+
});
|
|
653
|
+
flatFields[key] = yield* projectField(field);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
yield* prepareExpansion(schema.ast);
|
|
657
|
+
return Schema.Struct(flatFields);
|
|
658
|
+
});
|
|
659
|
+
/** Rebuild signatures without losing intrinsic defaults, key mappings or codecs. */
|
|
660
|
+
const projectField = (field) => Effect.gen(function* () {
|
|
661
|
+
if (!Schema.isPropertySignature(field)) return Schema.make(yield* projectNested(field.ast));
|
|
662
|
+
const signature = field.ast;
|
|
663
|
+
const input = yield* projectNested(signature._tag === "PropertySignatureDeclaration" ? signature.type : signature.from.type);
|
|
664
|
+
const output = signature._tag === "PropertySignatureDeclaration" ? input : yield* projectNested(signature.to.type);
|
|
665
|
+
return mapFormPropertySignature(field, (_ast, side) => side === "input" ? input : output);
|
|
666
|
+
});
|
|
667
|
+
const projectNested = (ast) => Effect.gen(function* () {
|
|
668
|
+
if (ast._tag === "TypeLiteral") {
|
|
669
|
+
const properties = [];
|
|
670
|
+
const names = /* @__PURE__ */ new Set();
|
|
671
|
+
for (const property of ast.propertySignatures) {
|
|
672
|
+
const field = Schema.make(SchemaAST.annotations(property.type, property.annotations));
|
|
673
|
+
if (hasStructuralOnlyAnnotation(field) || isReadOnlyField(field)) continue;
|
|
674
|
+
const flatten = yield* isFlattenableStruct(field, String(property.name));
|
|
675
|
+
const projected = yield* projectNested(property.type);
|
|
676
|
+
const children = flatten && projected._tag === "TypeLiteral" ? projected.propertySignatures : [new SchemaAST.PropertySignature(property.name, projected, property.isOptional, property.isReadonly, property.annotations)];
|
|
677
|
+
for (const child of children) {
|
|
678
|
+
if (names.has(child.name)) return yield* new FieldNameCollisionError({
|
|
679
|
+
fieldName: String(child.name),
|
|
680
|
+
wrapperField: `${String(property.name)}...${String(child.name)}`
|
|
681
|
+
});
|
|
682
|
+
names.add(child.name);
|
|
683
|
+
properties.push(child);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
return new SchemaAST.TypeLiteral(properties, ast.indexSignatures, ast.annotations);
|
|
687
|
+
}
|
|
688
|
+
if (ast._tag === "Union") return SchemaAST.Union.make(yield* Effect.forEach(ast.types, projectNested), ast.annotations);
|
|
689
|
+
if (ast._tag === "Refinement") return new SchemaAST.Refinement(yield* projectNested(ast.from), ast.filter, ast.annotations);
|
|
690
|
+
if (ast._tag === "Transformation") {
|
|
691
|
+
const from = yield* projectNested(ast.from);
|
|
692
|
+
const to = yield* projectNested(ast.to);
|
|
693
|
+
const transformation = ast.transformation._tag === "TypeLiteralTransformation" && from._tag === "TypeLiteral" && to._tag === "TypeLiteral" ? new SchemaAST.TypeLiteralTransformation(ast.transformation.propertySignatureTransformations.filter((property) => from.propertySignatures.some((p) => p.name === property.from) && to.propertySignatures.some((p) => p.name === property.to))) : ast.transformation;
|
|
694
|
+
return new SchemaAST.Transformation(from, to, transformation, ast.annotations);
|
|
695
|
+
}
|
|
696
|
+
if (ast._tag === "TupleType") {
|
|
697
|
+
const elements = yield* Effect.forEach(ast.elements, (element) => projectNested(element.type).pipe(Effect.map((type) => new SchemaAST.OptionalType(type, element.isOptional, element.annotations))));
|
|
698
|
+
const rest = yield* Effect.forEach(ast.rest, (element) => projectNested(element.type).pipe(Effect.map((type) => new SchemaAST.Type(type, element.annotations))));
|
|
699
|
+
return new SchemaAST.TupleType(elements, rest, ast.isReadonly, ast.annotations);
|
|
700
|
+
}
|
|
701
|
+
return ast;
|
|
702
|
+
});
|
|
703
|
+
/**
|
|
704
|
+
* Synchronous boundary for model construction and other non-Effect call sites.
|
|
705
|
+
* Rethrows the original TaggedError on failure (not a FiberFailure wrapper).
|
|
706
|
+
*/
|
|
707
|
+
const submissionSchemaSync = (schema) => {
|
|
708
|
+
const result = Effect.runSync(Effect.either(submissionSchema(schema)));
|
|
709
|
+
if (Either.isLeft(result)) throw result.left;
|
|
710
|
+
return result.right;
|
|
711
|
+
};
|
|
712
|
+
const expansionCache = /* @__PURE__ */ new WeakMap();
|
|
713
|
+
const prepareExpansion = (source) => Effect.gen(function* () {
|
|
714
|
+
const cached = expansionCache.get(source);
|
|
715
|
+
if (cached) return cached;
|
|
716
|
+
const ast = source;
|
|
717
|
+
const members = /* @__PURE__ */ new Map();
|
|
718
|
+
const visit = (node) => Effect.gen(function* () {
|
|
719
|
+
if (node._tag === "Union") members.set(node, yield* Effect.forEach(node.types, (member) => Effect.gen(function* () {
|
|
720
|
+
const projected = yield* projectNested(member);
|
|
721
|
+
yield* visit(member);
|
|
722
|
+
return {
|
|
723
|
+
ast: member,
|
|
724
|
+
matches: Schema.is(Schema.encodedSchema(Schema.make(projected)))
|
|
725
|
+
};
|
|
726
|
+
})));
|
|
727
|
+
else if (node._tag === "TypeLiteral") yield* Effect.forEach(node.propertySignatures, (property) => {
|
|
728
|
+
const field = Schema.make(SchemaAST.annotations(property.type, property.annotations));
|
|
729
|
+
return hasStructuralOnlyAnnotation(field) || isReadOnlyField(field) ? Effect.void : visit(property.type);
|
|
730
|
+
});
|
|
731
|
+
else if (node._tag === "TupleType") yield* Effect.forEach([...node.elements, ...node.rest], (element) => visit(element.type));
|
|
732
|
+
else if (node._tag === "Refinement" || node._tag === "Transformation") yield* visit(node.from);
|
|
733
|
+
});
|
|
734
|
+
yield* visit(ast);
|
|
735
|
+
const prepared = {
|
|
736
|
+
ast,
|
|
737
|
+
members
|
|
738
|
+
};
|
|
739
|
+
expansionCache.set(source, prepared);
|
|
740
|
+
return prepared;
|
|
741
|
+
});
|
|
742
|
+
//#endregion
|
|
743
|
+
//#region ../form-submission-schema/src/lib/schema-defaults.ts
|
|
744
|
+
/**
|
|
745
|
+
* Generate type-compatible default values from Effect Schema fields.
|
|
746
|
+
*
|
|
747
|
+
* This creates empty/zero values to satisfy Tanstack Form's type requirements.
|
|
748
|
+
* Values are NOT validated - they're just type-compatible placeholders.
|
|
749
|
+
*
|
|
750
|
+
* Without this we have an uncontrolled input error.
|
|
751
|
+
*/
|
|
752
|
+
const getSchemaDefaults = (fields) => {
|
|
753
|
+
const result = {};
|
|
754
|
+
for (const [key, fieldSchema] of Object.entries(fields)) {
|
|
755
|
+
const schema = fieldSchema;
|
|
756
|
+
if (hasStructuralOnlyAnnotation(schema) || isReadOnlyField(schema)) continue;
|
|
757
|
+
if (hasFlattenAnnotation(schema) && schema.ast._tag === "TypeLiteral") {
|
|
758
|
+
Object.assign(result, getDefaultsForTypeLiteral(schema.ast));
|
|
759
|
+
continue;
|
|
760
|
+
}
|
|
761
|
+
const ast = fieldSchema.ast;
|
|
762
|
+
if (ast._tag === "PropertySignatureDeclaration") result[key] = getDefaultForSchema(ast.type, ast.isOptional);
|
|
763
|
+
else if (ast._tag === "PropertySignatureTransformation") result[key] = getDefaultForSchema(ast.from.type, ast.from.isOptional);
|
|
764
|
+
else result[key] = getDefaultForSchema(ast);
|
|
765
|
+
}
|
|
766
|
+
return result;
|
|
767
|
+
};
|
|
768
|
+
const getDefaultsForTypeLiteral = (typeLiteral) => {
|
|
769
|
+
const result = {};
|
|
770
|
+
for (const prop of typeLiteral.propertySignatures) {
|
|
771
|
+
const key = String(prop.name);
|
|
772
|
+
const fieldSchema = prop.type;
|
|
773
|
+
const fieldAsSchema = { ast: fieldSchema };
|
|
774
|
+
if (hasStructuralOnlyAnnotation(fieldAsSchema) || isReadOnlyField(fieldAsSchema)) continue;
|
|
775
|
+
if (fieldSchema._tag === "TypeLiteral") {
|
|
776
|
+
if (hasFlattenAnnotation(fieldAsSchema)) {
|
|
777
|
+
Object.assign(result, getDefaultsForTypeLiteral(fieldSchema));
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
result[key] = getDefaultForSchema(fieldSchema, prop.isOptional);
|
|
782
|
+
}
|
|
783
|
+
return result;
|
|
784
|
+
};
|
|
785
|
+
const unionMembers = (ast) => ast._tag === "Union" ? ast.types.flatMap(unionMembers) : [ast];
|
|
786
|
+
/**
|
|
787
|
+
* Get default value for a single schema AST node
|
|
788
|
+
*/
|
|
789
|
+
const getDefaultForSchema = (ast, isOptional = false) => {
|
|
790
|
+
return Match.type().pipe(Match.tag("StringKeyword", () => ""), Match.tag("NumberKeyword", () => 0), Match.tag("BooleanKeyword", () => false), Match.tag("Refinement", (refinement) => getDefaultForSchema(refinement.from, isOptional)), Match.tag("Transformation", (transformation) => getDefaultForSchema(transformation.from, isOptional)), Match.tag("Literal", (literal) => isOptional && typeof literal.literal === "string" ? void 0 : ""), Match.tag("Union", (union) => {
|
|
791
|
+
const members = unionMembers(union);
|
|
792
|
+
const choices = members.filter((member) => member._tag !== "UndefinedKeyword" && !(member._tag === "Literal" && member.literal === null));
|
|
793
|
+
if (choices.length > 0 && choices.every((member) => member._tag === "Literal" && typeof member.literal === "string")) {
|
|
794
|
+
if (members.some((member) => member._tag === "Literal" && member.literal === null)) return null;
|
|
795
|
+
if (isOptional || members.some((member) => member._tag === "UndefinedKeyword")) return;
|
|
796
|
+
}
|
|
797
|
+
return "";
|
|
798
|
+
}), Match.tag("TypeLiteral", (typeLiteral) => {
|
|
799
|
+
const nestedResult = {};
|
|
800
|
+
for (const prop of typeLiteral.propertySignatures) nestedResult[String(prop.name)] = getDefaultForSchema(prop.type, prop.isOptional);
|
|
801
|
+
return nestedResult;
|
|
802
|
+
}), Match.tag("TupleType", () => []), Match.orElse(() => ""))(ast);
|
|
803
|
+
};
|
|
804
|
+
//#endregion
|
|
805
|
+
//#region ../process/src/lib/form-decoration.ts
|
|
806
|
+
var FormDecorationError = class extends Data.TaggedError("FormDecorationError") {};
|
|
807
|
+
const fail$1 = (path, message) => {
|
|
808
|
+
throw new FormDecorationError({
|
|
809
|
+
path,
|
|
810
|
+
message: `${path}: ${message}`
|
|
811
|
+
});
|
|
812
|
+
};
|
|
813
|
+
const record = (value, path) => {
|
|
814
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return fail$1(path, "expected a decoration object");
|
|
815
|
+
if (Object.getOwnPropertySymbols(value).length) fail$1(path, "symbol operations are not supported");
|
|
816
|
+
return value;
|
|
817
|
+
};
|
|
818
|
+
const lookupResult = Schema.Array(Schema.Struct({
|
|
819
|
+
value: Schema.String,
|
|
820
|
+
label: Schema.String
|
|
821
|
+
}));
|
|
822
|
+
const calendarResult = Schema.Array(Schema.Struct({
|
|
823
|
+
value: Schema.String,
|
|
824
|
+
startsAt: Schema.String,
|
|
825
|
+
endsAt: Schema.String,
|
|
826
|
+
label: Schema.optional(Schema.String)
|
|
827
|
+
}));
|
|
828
|
+
const decorateAst = (original, value, path) => {
|
|
829
|
+
const operations = record(value, path);
|
|
830
|
+
const annotations = {};
|
|
831
|
+
for (const [key, operation] of Object.entries(operations)) {
|
|
832
|
+
if (![
|
|
833
|
+
"label",
|
|
834
|
+
"description",
|
|
835
|
+
"autoComplete",
|
|
836
|
+
"default",
|
|
837
|
+
"query"
|
|
838
|
+
].includes(key)) fail$1(path, `unsupported operation ${key}`);
|
|
839
|
+
if (operation === void 0) continue;
|
|
840
|
+
switch (key) {
|
|
841
|
+
case "label":
|
|
842
|
+
case "description":
|
|
843
|
+
case "autoComplete":
|
|
844
|
+
if (typeof operation !== "string") fail$1(path, `${key} must be text`);
|
|
845
|
+
annotations[key === "label" ? FormLabel : key === "description" ? FormDescription : FormAutoComplete] = operation;
|
|
846
|
+
break;
|
|
847
|
+
case "default": {
|
|
848
|
+
if (original.annotations[STRUCTURAL_ONLY_SYMBOL]) fail$1(path, "structural fields cannot have defaults");
|
|
849
|
+
const input = Schema.encodedSchema(Schema.make(original));
|
|
850
|
+
const checked = (candidate) => {
|
|
851
|
+
if (!(candidate === CurrentProviderUser && fieldAnnotation(original, FormProviderUserInput) === true) && !Schema.is(input)(candidate)) fail$1(path, "default does not match the declared input type");
|
|
852
|
+
return candidate;
|
|
853
|
+
};
|
|
854
|
+
annotations[FormDefault] = checked(typeof operation === "function" ? operation() : operation);
|
|
855
|
+
break;
|
|
856
|
+
}
|
|
857
|
+
case "query": {
|
|
858
|
+
if (typeof operation !== "function") fail$1(path, "query must be a function");
|
|
859
|
+
const query = operation;
|
|
860
|
+
const lookup = fieldAnnotation(original, FormLookupInput);
|
|
861
|
+
const calendar = fieldAnnotation(original, FormCalendarSlotInput);
|
|
862
|
+
if (!lookup && !calendar) fail$1(path, "query requires a declared lookup or calendar field");
|
|
863
|
+
const metadata = lookup ?? calendar;
|
|
864
|
+
if (typeof metadata !== "object" || metadata === null) fail$1(path, "invalid query declaration");
|
|
865
|
+
annotations[lookup ? FormLookupInput : FormCalendarSlotInput] = {
|
|
866
|
+
...metadata,
|
|
867
|
+
query: (...args) => Effect.suspend(() => {
|
|
868
|
+
const result = query(...args);
|
|
869
|
+
if (!Effect.isEffect(result)) return Effect.fail(new FormDecorationError({
|
|
870
|
+
path,
|
|
871
|
+
message: "query must return an Effect"
|
|
872
|
+
}));
|
|
873
|
+
return result.pipe(Effect.flatMap((items) => lookup ? Schema.decodeUnknown(lookupResult)(items) : Schema.decodeUnknown(calendarResult)(items)));
|
|
874
|
+
})
|
|
875
|
+
};
|
|
876
|
+
break;
|
|
877
|
+
}
|
|
878
|
+
default: fail$1(path, `unsupported operation ${key}`);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
return SchemaAST.annotations(original, annotations);
|
|
882
|
+
};
|
|
883
|
+
/** Preserve property transformations and exact field types during safe resolution. */
|
|
884
|
+
const mapFormFields = (fields, map, mapAnnotations = (annotations) => annotations, mapOutput = (ast) => ast) => {
|
|
885
|
+
return Object.fromEntries(Object.entries(fields).map(([name, original]) => {
|
|
886
|
+
if (Schema.isPropertySignature(original)) return [name, mapFormPropertySignature(original, (ast, side) => side === "input" ? map(ast, name) : mapOutput(ast, name), (annotations, input, side) => mapAnnotations(annotations, input, name, side))];
|
|
887
|
+
return [name, schemaFromAst(map(original.ast, name), original)];
|
|
888
|
+
}));
|
|
889
|
+
};
|
|
890
|
+
const sourceStructFields = (source) => {
|
|
891
|
+
if (!source || !("fields" in source)) return void 0;
|
|
892
|
+
const fields = source.fields;
|
|
893
|
+
if (typeof fields !== "object" || fields === null) return void 0;
|
|
894
|
+
const result = {};
|
|
895
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
896
|
+
if (!Schema.isSchema(field) && !Schema.isPropertySignature(field)) return void 0;
|
|
897
|
+
result[name] = field;
|
|
898
|
+
}
|
|
899
|
+
return result;
|
|
900
|
+
};
|
|
901
|
+
function schemaFromAst(ast, source) {
|
|
902
|
+
const sourceFields = sourceStructFields(source);
|
|
903
|
+
const struct = ast._tag === "TypeLiteral" ? {
|
|
904
|
+
input: ast,
|
|
905
|
+
output: ast
|
|
906
|
+
} : ast._tag === "Transformation" && ast.transformation._tag === "TypeLiteralTransformation" && ast.from._tag === "TypeLiteral" && ast.to._tag === "TypeLiteral" ? {
|
|
907
|
+
input: ast.from,
|
|
908
|
+
output: ast.to
|
|
909
|
+
} : void 0;
|
|
910
|
+
if (sourceFields && struct) {
|
|
911
|
+
const inputs = new Map(struct.input.propertySignatures.map((p) => [p.name, p]));
|
|
912
|
+
const outputs = new Map(struct.output.propertySignatures.map((p) => [p.name, p]));
|
|
913
|
+
const property = (name, side) => {
|
|
914
|
+
const original = sourceFields[name];
|
|
915
|
+
const inputKey = Schema.isPropertySignature(original) && original.ast._tag === "PropertySignatureTransformation" ? original.ast.from.fromKey ?? name : name;
|
|
916
|
+
const resolved = side === "input" ? inputs.get(inputKey) : outputs.get(name);
|
|
917
|
+
if (!resolved) return fail$1(`form.${name}`, "projected struct field is missing");
|
|
918
|
+
return resolved;
|
|
919
|
+
};
|
|
920
|
+
const fields = mapFormFields(sourceFields, (_ast, name) => property(name, "input").type, (annotations, _ast, name, side) => Object.fromEntries(Reflect.ownKeys(annotations).map((key) => [key, property(name, side).annotations[key]])), (_ast, name) => property(name, "output").type);
|
|
921
|
+
return Object.assign(Schema.make(ast), { fields });
|
|
922
|
+
}
|
|
923
|
+
if (ast._tag !== "TypeLiteral") return Schema.make(ast);
|
|
924
|
+
const fields = Object.fromEntries(ast.propertySignatures.map((property) => [property.name, property.isOptional ? Schema.optional(schemaFromAst(property.type)) : schemaFromAst(property.type)]));
|
|
925
|
+
return Object.assign(Schema.make(ast), { fields });
|
|
926
|
+
}
|
|
927
|
+
//#endregion
|
|
928
|
+
//#region ../process/src/lib/form-authoring.ts
|
|
929
|
+
const fail = (path, message) => {
|
|
930
|
+
throw new FormDecorationError({
|
|
931
|
+
path,
|
|
932
|
+
message: `${path}: ${message}`
|
|
933
|
+
});
|
|
934
|
+
};
|
|
935
|
+
const structuralAst = (content, path) => {
|
|
936
|
+
if (!Schema.isSchema(content) || content.ast._tag !== "UndefinedKeyword" || content.ast.annotations[STRUCTURAL_ONLY_SYMBOL] !== true || content.ast.annotations[FormDeferredContent] !== void 0) return fail(path, "content must be a structural leaf, not a value field or container");
|
|
937
|
+
return content.ast;
|
|
938
|
+
};
|
|
939
|
+
/** Never let deferred descriptors reach schema walkers or serialized metadata. */
|
|
940
|
+
const assertResolvedFormFields = (fields) => {
|
|
941
|
+
const seen = /* @__PURE__ */ new Set();
|
|
942
|
+
const visit = (value) => {
|
|
943
|
+
if (isDeferredValue(value)) fail("form", "unresolved deferred value: use a supported field option");
|
|
944
|
+
if (typeof value !== "object" || value === null || seen.has(value)) return;
|
|
945
|
+
seen.add(value);
|
|
946
|
+
for (const key of Reflect.ownKeys(value)) visit(Reflect.get(value, key));
|
|
947
|
+
};
|
|
948
|
+
visit(Schema.Struct(fields).ast);
|
|
949
|
+
};
|
|
950
|
+
const operations = /* @__PURE__ */ new Map([
|
|
951
|
+
[FormLabel, "label"],
|
|
952
|
+
[FormDescription, "description"],
|
|
953
|
+
[FormAutoComplete, "autoComplete"],
|
|
954
|
+
[FormDefault, "default"]
|
|
955
|
+
]);
|
|
956
|
+
/** Walk both sides of transformations without changing their decoding contract. */
|
|
957
|
+
const mapChildren = (ast, map, path, mapAnnotations) => {
|
|
958
|
+
switch (ast._tag) {
|
|
959
|
+
case "TypeLiteral": return new SchemaAST.TypeLiteral(ast.propertySignatures.map((property) => new SchemaAST.PropertySignature(property.name, map(property.type, `${path}.${String(property.name)}`), property.isOptional, property.isReadonly, mapAnnotations(property.annotations, property.type, `${path}.${String(property.name)}`))), ast.indexSignatures, ast.annotations);
|
|
960
|
+
case "TupleType": return new SchemaAST.TupleType(ast.elements.map((element, index) => new SchemaAST.OptionalType(map(element.type, `${path}[${index}]`), element.isOptional, element.annotations)), ast.rest.map((element) => new SchemaAST.Type(map(element.type, `${path}[]`), element.annotations)), ast.isReadonly, ast.annotations);
|
|
961
|
+
case "Union": return SchemaAST.Union.make(ast.types.map((type) => map(type, path)), ast.annotations);
|
|
962
|
+
case "Refinement": return new SchemaAST.Refinement(map(ast.from, path), ast.filter, ast.annotations);
|
|
963
|
+
case "Transformation": return new SchemaAST.Transformation(map(ast.from, path), map(ast.to, path), ast.transformation, ast.annotations);
|
|
964
|
+
case "Suspend": return fail(path, "suspended form schemas are not supported");
|
|
965
|
+
default: return ast;
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
const createFormAuthoring = () => {
|
|
969
|
+
const resolvers = /* @__PURE__ */ new WeakMap();
|
|
970
|
+
const value = (resolve, fallback) => {
|
|
971
|
+
const descriptor = Object.freeze({
|
|
972
|
+
[DeferredValueTypeId]: true,
|
|
973
|
+
fallback
|
|
974
|
+
});
|
|
975
|
+
resolvers.set(descriptor, resolve);
|
|
976
|
+
return descriptor;
|
|
977
|
+
};
|
|
978
|
+
const helpers = {
|
|
979
|
+
value,
|
|
980
|
+
query: value,
|
|
981
|
+
content: (resolve, fallback = TextBlock("")) => {
|
|
982
|
+
structuralAst(fallback, "content.fallback");
|
|
983
|
+
return fallback.annotations({ [FormDeferredContent]: value(resolve, fallback) });
|
|
984
|
+
}
|
|
985
|
+
};
|
|
986
|
+
const project = (fields, args) => {
|
|
987
|
+
const evaluated = /* @__PURE__ */ new Map();
|
|
988
|
+
const resolve = (descriptor, path) => {
|
|
989
|
+
const resolver = resolvers.get(descriptor);
|
|
990
|
+
if (!resolver) return fail(path, "deferred value belongs to another Form declaration");
|
|
991
|
+
if (!args) return descriptor.fallback;
|
|
992
|
+
if (!evaluated.has(descriptor)) evaluated.set(descriptor, resolver(...args));
|
|
993
|
+
const resolved = evaluated.get(descriptor);
|
|
994
|
+
return resolved === void 0 ? descriptor.fallback : resolved;
|
|
995
|
+
};
|
|
996
|
+
const visit = (original, path) => {
|
|
997
|
+
const content = original.annotations[FormDeferredContent];
|
|
998
|
+
if (content !== void 0) {
|
|
999
|
+
if (!isDeferredValue(content)) return fail(path, "invalid deferred content");
|
|
1000
|
+
const resolved = resolve(content, path);
|
|
1001
|
+
return structuralAst(resolved === void 0 ? content.fallback : resolved, path);
|
|
1002
|
+
}
|
|
1003
|
+
let ast = mapChildren(original, visit, path, visitAnnotations);
|
|
1004
|
+
for (const key of Object.getOwnPropertySymbols(original.annotations)) {
|
|
1005
|
+
const annotation = original.annotations[key];
|
|
1006
|
+
if (isDeferredValue(annotation)) {
|
|
1007
|
+
const operation = operations.get(key);
|
|
1008
|
+
if (!operation) return fail(path, "deferred value is not allowed in this schema annotation");
|
|
1009
|
+
ast = SchemaAST.annotations(ast, { [key]: void 0 });
|
|
1010
|
+
ast = decorateAst(ast, { [operation]: resolve(annotation, path) }, path);
|
|
1011
|
+
} else if (key === FormLookupInput || key === FormCalendarSlotInput) {
|
|
1012
|
+
if (typeof annotation !== "object" || annotation === null || !("query" in annotation)) continue;
|
|
1013
|
+
if (!isDeferredValue(annotation.query)) continue;
|
|
1014
|
+
const query = annotation.query;
|
|
1015
|
+
ast = SchemaAST.annotations(ast, { [key]: {
|
|
1016
|
+
...annotation,
|
|
1017
|
+
query: void 0
|
|
1018
|
+
} });
|
|
1019
|
+
if (args) ast = decorateAst(ast, { query: (...queryArgs) => {
|
|
1020
|
+
const bound = resolve(query, path);
|
|
1021
|
+
if (typeof bound !== "function") return fail(path, "query binding must return a function");
|
|
1022
|
+
return bound(...queryArgs);
|
|
1023
|
+
} }, path);
|
|
1024
|
+
else if (!resolvers.has(query)) return fail(path, "deferred query belongs to another Form declaration");
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
return ast;
|
|
1028
|
+
};
|
|
1029
|
+
const visitAnnotations = (annotations, ast, path) => {
|
|
1030
|
+
if (!Object.getOwnPropertySymbols(annotations).some((key) => isDeferredValue(annotations[key]))) return annotations;
|
|
1031
|
+
const resolved = visit(SchemaAST.annotations(ast, annotations), path).annotations;
|
|
1032
|
+
return Object.fromEntries(Reflect.ownKeys(annotations).map((key) => [key, resolved[key]]));
|
|
1033
|
+
};
|
|
1034
|
+
const resolved = mapFormFields(fields, (ast, name) => visit(ast, `form.${name}`), (annotations, ast, name) => visitAnnotations(annotations, ast, `form.${name}`), (ast, name) => visit(ast, `form.${name}`));
|
|
1035
|
+
assertResolvedFormFields(resolved);
|
|
1036
|
+
return resolved;
|
|
1037
|
+
};
|
|
1038
|
+
return {
|
|
1039
|
+
helpers: Object.freeze(helpers),
|
|
1040
|
+
project
|
|
1041
|
+
};
|
|
1042
|
+
};
|
|
1043
|
+
//#endregion
|
|
1044
|
+
//#region ../process/src/lib/form-defaults.ts
|
|
1045
|
+
const nestedAst = (ast) => {
|
|
1046
|
+
if (ast._tag === "TypeLiteral") return ast;
|
|
1047
|
+
if (ast._tag === "Transformation" || ast._tag === "Refinement") return nestedAst(ast.from);
|
|
1048
|
+
if (ast._tag === "Union") for (const type of ast.types) {
|
|
1049
|
+
const nested = nestedAst(type);
|
|
1050
|
+
if (nested) return nested;
|
|
1051
|
+
}
|
|
1052
|
+
};
|
|
1053
|
+
/** Authoritative annotated defaults only: never initialization placeholders. */
|
|
1054
|
+
const resolveFormFieldDefaults = (fields, currentProviderUser) => Effect.gen(function* () {
|
|
1055
|
+
const defaults = {};
|
|
1056
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
1057
|
+
const ast = fieldInputAst(field);
|
|
1058
|
+
if (fieldAnnotation(ast, STRUCTURAL_ONLY_SYMBOL)) continue;
|
|
1059
|
+
const value = fieldAnnotation(ast, FormDefault);
|
|
1060
|
+
if (value !== void 0) {
|
|
1061
|
+
const resolved = typeof value === "function" ? yield* Effect.try(() => value()).pipe(Effect.tapError((error) => Effect.logWarning(`Failed to resolve default for field "${name}"`, { error })), Effect.option) : Option.some(value);
|
|
1062
|
+
if (Option.isSome(resolved)) {
|
|
1063
|
+
const actual = resolved.value === CurrentProviderUser ? currentProviderUser : resolved.value;
|
|
1064
|
+
if (actual !== void 0) defaults[name] = actual;
|
|
1065
|
+
}
|
|
1066
|
+
continue;
|
|
1067
|
+
}
|
|
1068
|
+
const nested = nestedAst(ast);
|
|
1069
|
+
if (nested) {
|
|
1070
|
+
const children = yield* resolveFormFieldDefaults(Object.fromEntries(nested.propertySignatures.map((property) => [property.name, Schema.make(SchemaAST.annotations(property.type, property.annotations))])), currentProviderUser);
|
|
1071
|
+
if (fieldAnnotation(ast, FLATTEN_SYMBOL)) Object.assign(defaults, children);
|
|
1072
|
+
else if (Object.keys(children).length) defaults[name] = children;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
return defaults;
|
|
1076
|
+
});
|
|
1077
|
+
const isPlainRecord = (value) => typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
1078
|
+
/** Submitted edits win while omitted nested values retain authored defaults. */
|
|
1079
|
+
const mergeFormDefaults = (defaults, input) => {
|
|
1080
|
+
const merged = { ...defaults };
|
|
1081
|
+
for (const [key, value] of Object.entries(input)) {
|
|
1082
|
+
const previous = defaults[key];
|
|
1083
|
+
Object.defineProperty(merged, key, {
|
|
1084
|
+
value: isPlainRecord(previous) && isPlainRecord(value) ? mergeFormDefaults(previous, value) : value,
|
|
1085
|
+
writable: true,
|
|
1086
|
+
enumerable: true,
|
|
1087
|
+
configurable: true
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
return merged;
|
|
1091
|
+
};
|
|
1092
|
+
//#endregion
|
|
1093
|
+
//#region ../process/src/lib/lookup-accessor.ts
|
|
1094
|
+
/**
|
|
1095
|
+
* Typed accessor for a single lookup field on a Form.
|
|
1096
|
+
*
|
|
1097
|
+
* Call `.setQuery()` for independent lookups, or
|
|
1098
|
+
* `.dependsOn([...]).setQuery()` for dependent lookups.
|
|
1099
|
+
*/
|
|
1100
|
+
var LookupAccessor = class {
|
|
1101
|
+
fieldName;
|
|
1102
|
+
_store;
|
|
1103
|
+
constructor(store, fieldName) {
|
|
1104
|
+
this._store = store;
|
|
1105
|
+
this.fieldName = fieldName;
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Set the query for an independent lookup (no dependencies).
|
|
1109
|
+
*/
|
|
1110
|
+
setQuery(query) {
|
|
1111
|
+
this._store._setLookupOverride(this.fieldName, { query });
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Declare dependencies on other lookup fields, returning a builder
|
|
1115
|
+
* whose `setQuery` receives the dependency values as typed input.
|
|
1116
|
+
*/
|
|
1117
|
+
dependsOn(deps) {
|
|
1118
|
+
return new LookupBuilder(this._store, this.fieldName, deps);
|
|
1119
|
+
}
|
|
1120
|
+
};
|
|
1121
|
+
/**
|
|
1122
|
+
* Builder returned by `LookupAccessor.dependsOn()`.
|
|
1123
|
+
* Its `setQuery` callback receives `{ filter, ...depValues }`.
|
|
1124
|
+
*/
|
|
1125
|
+
var LookupBuilder = class {
|
|
1126
|
+
_store;
|
|
1127
|
+
_fieldName;
|
|
1128
|
+
_deps;
|
|
1129
|
+
constructor(store, fieldName, deps) {
|
|
1130
|
+
this._store = store;
|
|
1131
|
+
this._fieldName = fieldName;
|
|
1132
|
+
this._deps = deps;
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* Set the query for this dependent lookup.
|
|
1136
|
+
*/
|
|
1137
|
+
setQuery(query) {
|
|
1138
|
+
this._store._setLookupOverride(this._fieldName, {
|
|
1139
|
+
query,
|
|
1140
|
+
dependencies: this._deps.map((d) => d.fieldName)
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
//#endregion
|
|
1145
|
+
//#region ../process/src/lib/org-utils.ts
|
|
1146
|
+
/**
|
|
1147
|
+
* Normalizes a path for database storage by ensuring it starts with a forward slash.
|
|
1148
|
+
* Paths in constructs don't have a leading slash, but stored paths should have one
|
|
1149
|
+
* to clearly indicate they are paths.
|
|
1150
|
+
*
|
|
1151
|
+
* @param path - Path like "Demo/engineering/bug-fix" or "/Demo/engineering/bug-fix"
|
|
1152
|
+
* @returns Normalized path with leading slash like "/Demo/engineering/bug-fix"
|
|
1153
|
+
*
|
|
1154
|
+
* @example
|
|
1155
|
+
* ```ts
|
|
1156
|
+
* normalizePath("Demo/engineering/bug-fix")
|
|
1157
|
+
* // => "/Demo/engineering/bug-fix"
|
|
1158
|
+
*
|
|
1159
|
+
* normalizePath("/Demo/engineering/bug-fix")
|
|
1160
|
+
* // => "/Demo/engineering/bug-fix"
|
|
1161
|
+
* ```
|
|
1162
|
+
*/
|
|
1163
|
+
const normalizePath = (path) => {
|
|
1164
|
+
return path.startsWith("/") ? path : `/${path}`;
|
|
1165
|
+
};
|
|
1166
|
+
/**
|
|
1167
|
+
* Converts a construct path to a PascalCase name.
|
|
1168
|
+
* Used for generating GraphQL type names from step/process paths.
|
|
1169
|
+
* Path format: "orgUnit/processName/stepName" or "/orgUnit/processName/stepName"
|
|
1170
|
+
*
|
|
1171
|
+
* Handles optional leading slash for backward compatibility.
|
|
1172
|
+
*
|
|
1173
|
+
* @param path - Full construct path like "engineering/bug-report-fix/Report bug"
|
|
1174
|
+
* or "/engineering/bug-report-fix/Report bug"
|
|
1175
|
+
* @returns PascalCase name like "EngineeringBugReportFixReportBug"
|
|
1176
|
+
*
|
|
1177
|
+
* @example
|
|
1178
|
+
* ```ts
|
|
1179
|
+
* pathToPascalCase("engineering/bug-report-fix/Report bug")
|
|
1180
|
+
* // => "EngineeringBugReportFixReportBug"
|
|
1181
|
+
*
|
|
1182
|
+
* pathToPascalCase("/engineering/bug-report-fix/Report bug")
|
|
1183
|
+
* // => "EngineeringBugReportFixReportBug"
|
|
1184
|
+
* ```
|
|
1185
|
+
*/
|
|
1186
|
+
const pathToPascalCase = (path) => {
|
|
1187
|
+
return path.split("/").filter((segment) => segment.length > 0).map((segment) => {
|
|
1188
|
+
return segment.replace(/-/g, " ").split(/\s+/).filter((word) => word.length > 0).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
|
|
1189
|
+
}).join("");
|
|
1190
|
+
};
|
|
1191
|
+
//#endregion
|
|
1192
|
+
//#region ../process/src/lib/flow-context.ts
|
|
1193
|
+
/**
|
|
1194
|
+
* Convert a string to a valid camelCase JavaScript identifier.
|
|
1195
|
+
* Handles spaces, underscores, hyphens, and removes invalid characters.
|
|
1196
|
+
*
|
|
1197
|
+
* @example
|
|
1198
|
+
* toCamelCase("Submit time off request") // "submitTimeOffRequest"
|
|
1199
|
+
* toCamelCase("approve_request") // "approveRequest"
|
|
1200
|
+
* toCamelCase("my-step") // "myStep"
|
|
1201
|
+
* toCamelCase("123 invalid start") // "invalidStart" (removes leading digits)
|
|
1202
|
+
*/
|
|
1203
|
+
function toCamelCase(str) {
|
|
1204
|
+
const words = str.split(/[\s_-]+/).filter((w) => w.length > 0);
|
|
1205
|
+
if (words.length === 0) return "unnamed";
|
|
1206
|
+
let isFirstWord = true;
|
|
1207
|
+
const result = words.map((word) => {
|
|
1208
|
+
const cleaned = word.replace(/[^a-zA-Z0-9]/g, "");
|
|
1209
|
+
if (cleaned.length === 0) return "";
|
|
1210
|
+
if (isFirstWord) {
|
|
1211
|
+
const noLeadingDigits = cleaned.replace(/^[0-9]+/, "");
|
|
1212
|
+
if (noLeadingDigits.length > 0) {
|
|
1213
|
+
isFirstWord = false;
|
|
1214
|
+
return noLeadingDigits.toLowerCase();
|
|
1215
|
+
}
|
|
1216
|
+
return "";
|
|
1217
|
+
}
|
|
1218
|
+
return cleaned.charAt(0).toUpperCase() + cleaned.slice(1).toLowerCase();
|
|
1219
|
+
}).join("");
|
|
1220
|
+
if (result.length === 0 || /^[0-9]/.test(result)) return `_${result}`;
|
|
1221
|
+
return result;
|
|
1222
|
+
}
|
|
1223
|
+
//#endregion
|
|
1224
|
+
//#region ../process/src/lib/step.ts
|
|
1225
|
+
var Step = class extends Construct {
|
|
1226
|
+
props;
|
|
1227
|
+
_output;
|
|
1228
|
+
_outputSchema;
|
|
1229
|
+
process;
|
|
1230
|
+
__scopeState;
|
|
1231
|
+
/**
|
|
1232
|
+
* Phantom type to carry the step ID as a literal type.
|
|
1233
|
+
* Used for type-level step key computation.
|
|
1234
|
+
*/
|
|
1235
|
+
__stepId;
|
|
1236
|
+
/**
|
|
1237
|
+
* Phantom type to indicate if this step is a Form (completed by employee).
|
|
1238
|
+
* Forms set this to `true` while generic Steps leave it as `false`.
|
|
1239
|
+
*/
|
|
1240
|
+
__isForm;
|
|
1241
|
+
/**
|
|
1242
|
+
* Phantom type to indicate if this step uses forEach semantics.
|
|
1243
|
+
* When true, the step contributes an array of outputs to state
|
|
1244
|
+
* instead of a flat merge.
|
|
1245
|
+
*/
|
|
1246
|
+
__isForEach;
|
|
1247
|
+
/**
|
|
1248
|
+
* The step ID converted to a valid camelCase identifier.
|
|
1249
|
+
* Used as the key in ctx.step for this step.
|
|
1250
|
+
*/
|
|
1251
|
+
stepKey;
|
|
1252
|
+
/** Stable brand for steps loaded from separately bundled organisation code. */
|
|
1253
|
+
isStep = true;
|
|
1254
|
+
/**
|
|
1255
|
+
* Brand property to identify Form instances across bundle boundaries.
|
|
1256
|
+
* Overridden to `true` in Form. Check this instead of using instanceof,
|
|
1257
|
+
* which fails when org.js is compiled separately from the job worker.
|
|
1258
|
+
*/
|
|
1259
|
+
isForm = false;
|
|
1260
|
+
/**
|
|
1261
|
+
* Brand property to identify SystemStep instances across bundle boundaries.
|
|
1262
|
+
* Overridden to `true` in SystemStep. Check this instead of using instanceof,
|
|
1263
|
+
* which fails when org.js is compiled separately from the job worker.
|
|
1264
|
+
*/
|
|
1265
|
+
isSystemStep = false;
|
|
1266
|
+
/**
|
|
1267
|
+
* The output validation schema for this step.
|
|
1268
|
+
* Lazily builds Schema.Struct from output fields on first access.
|
|
1269
|
+
* Form overrides this to include struct-level validation refinements.
|
|
1270
|
+
*/
|
|
1271
|
+
get outputSchema() {
|
|
1272
|
+
if (!this._outputSchema && this._output) this._outputSchema = Schema.Struct(this._output);
|
|
1273
|
+
return this._outputSchema;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* The flat submission validation schema for this step.
|
|
1277
|
+
* Returns `undefined` for non-Form steps. Form overrides this to return
|
|
1278
|
+
* the flattened submission schema (wrapper fields removed, read-only/
|
|
1279
|
+
* structural-only excluded), optionally with a filterEffect refinement.
|
|
1280
|
+
*
|
|
1281
|
+
* Used by start/complete resolvers for server-side validation.
|
|
1282
|
+
*/
|
|
1283
|
+
get submissionEffectSchema() {}
|
|
1284
|
+
/**
|
|
1285
|
+
* Brand property to identify forEach steps across bundle boundaries.
|
|
1286
|
+
* Overridden to `true` in SystemStep/Form when forEach is configured.
|
|
1287
|
+
*/
|
|
1288
|
+
hasForEach = false;
|
|
1289
|
+
constructor(scope, id, props) {
|
|
1290
|
+
const process = isProcess(scope) ? scope : scope.process;
|
|
1291
|
+
super(process, id);
|
|
1292
|
+
this.process = process;
|
|
1293
|
+
this._output = props.output;
|
|
1294
|
+
this.props = props;
|
|
1295
|
+
this.stepKey = toCamelCase(id);
|
|
1296
|
+
process.addNode(this);
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
* Get the output schema for this step.
|
|
1300
|
+
*/
|
|
1301
|
+
get output() {
|
|
1302
|
+
return this._output;
|
|
1303
|
+
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Connect `step` to this step. Optionally provide transition options.
|
|
1306
|
+
* @param step - The next step to connect to
|
|
1307
|
+
* @param options - Optional transition options with `condition` and/or `schedule`
|
|
1308
|
+
*/
|
|
1309
|
+
next(step, options) {
|
|
1310
|
+
return createFlowPath(this, step, this.process, options);
|
|
1311
|
+
}
|
|
1312
|
+
end(step, options) {
|
|
1313
|
+
assertSameProcess(step, this.process);
|
|
1314
|
+
this.process.addEdge(this, step, {
|
|
1315
|
+
condition: options?.condition?.fn,
|
|
1316
|
+
conditionText: options?.condition?.text,
|
|
1317
|
+
schedule: options?.schedule?.fn,
|
|
1318
|
+
scheduleText: options?.schedule?.text
|
|
1319
|
+
});
|
|
1320
|
+
this.process.addEndEdge(step);
|
|
1321
|
+
return step;
|
|
1322
|
+
}
|
|
1323
|
+
};
|
|
1324
|
+
//#endregion
|
|
1325
|
+
//#region ../process/src/lib/system-step.ts
|
|
1326
|
+
/**
|
|
1327
|
+
* Structural guard for AuthorTaggedError (cross-boundary safe; no instanceof).
|
|
1328
|
+
*/
|
|
1329
|
+
const isAuthorTaggedError = (error) => typeof error === "object" && error !== null && "_tag" in error && typeof error._tag === "string";
|
|
1330
|
+
/**
|
|
1331
|
+
* True when a failure value explicitly opts out of system-step retries.
|
|
1332
|
+
* Cross-boundary safe: checks the `retryable` field without `instanceof`.
|
|
1333
|
+
*/
|
|
1334
|
+
const isNonRetryableAuthorError = (error) => isAuthorTaggedError(error) && error.retryable === false;
|
|
1335
|
+
/**
|
|
1336
|
+
* Pass through a tagged author error, otherwise replace with `fallback`.
|
|
1337
|
+
* Use at org/plugin boundaries that still yield untyped Effect failure channels.
|
|
1338
|
+
*/
|
|
1339
|
+
const coerceAuthorTaggedError = (error, fallback) => isAuthorTaggedError(error) ? error : fallback;
|
|
1340
|
+
/**
|
|
1341
|
+
* Error when `input()` is called on a forEach step (use `forEachItems()` instead).
|
|
1342
|
+
*/
|
|
1343
|
+
var ForEachStepRequiresItemsError = class extends Data.TaggedError("ForEachStepRequiresItemsError") {};
|
|
1344
|
+
/**
|
|
1345
|
+
* Error when `forEachItems()` is called on a step that does not use forEach.
|
|
1346
|
+
*/
|
|
1347
|
+
var NotAForEachStepError = class extends Data.TaggedError("NotAForEachStepError") {};
|
|
1348
|
+
/**
|
|
1349
|
+
* Current system-step job identifiers, provided while `executeStep` runs.
|
|
1350
|
+
* Use this from NodeStep `execute` callbacks that need the Todo identity
|
|
1351
|
+
* for replay-safe side effects.
|
|
1352
|
+
*/
|
|
1353
|
+
var CurrentStepJobContext = class extends Context.Tag("processfocus/process/CurrentStepJobContext")() {};
|
|
1354
|
+
/**
|
|
1355
|
+
* Abstract base class for system-executed steps.
|
|
1356
|
+
*
|
|
1357
|
+
* SystemStep represents a step that is automatically executed by the job worker
|
|
1358
|
+
* when the flow reaches it, rather than waiting for human interaction.
|
|
1359
|
+
*
|
|
1360
|
+
* Unlike Form steps which have a `role` (who completes them), SystemSteps have
|
|
1361
|
+
* no role - they are executed by the system. In the database, this is represented
|
|
1362
|
+
* by `role_id = NULL`.
|
|
1363
|
+
*
|
|
1364
|
+
* Subclasses must implement the `execute` method which contains the business logic.
|
|
1365
|
+
*
|
|
1366
|
+
* @typeParam TState - Accumulated state from previous steps
|
|
1367
|
+
* @typeParam TSteps - Record of completed step metadata for ctx.step access
|
|
1368
|
+
* @typeParam TInput - Input derived from state
|
|
1369
|
+
* @typeParam TOutput - Output schema fields merged into process state
|
|
1370
|
+
* @typeParam TId - Step identifier literal type
|
|
1371
|
+
*
|
|
1372
|
+
* @example
|
|
1373
|
+
* ```typescript
|
|
1374
|
+
* // NodeStep is a concrete implementation that takes execute as a prop
|
|
1375
|
+
* const greet = new NodeStep(register, "Greet", {
|
|
1376
|
+
* input: (state) => Effect.succeed({ name: state.name }),
|
|
1377
|
+
* output: {},
|
|
1378
|
+
* execute: (input) => Effect.gen(function* () {
|
|
1379
|
+
* console.log(`Hello ${input.name}`)
|
|
1380
|
+
* }),
|
|
1381
|
+
* })
|
|
1382
|
+
* ```
|
|
1383
|
+
*/
|
|
1384
|
+
var SystemStep = class extends Step {
|
|
1385
|
+
isSystemStep = true;
|
|
1386
|
+
longDuration;
|
|
1387
|
+
/**
|
|
1388
|
+
* Maximum number of retry attempts when the step fails.
|
|
1389
|
+
* - `0`: No retries - fail immediately on first error
|
|
1390
|
+
* - `1+`: Retry up to this many times after failure
|
|
1391
|
+
* - `undefined`: Use system default
|
|
1392
|
+
*/
|
|
1393
|
+
retries;
|
|
1394
|
+
/**
|
|
1395
|
+
* The input derivation function, stored for runtime execution.
|
|
1396
|
+
* Undefined when forEach is used (items replaces input).
|
|
1397
|
+
*/
|
|
1398
|
+
_inputFn;
|
|
1399
|
+
/**
|
|
1400
|
+
* The forEach items function, stored for runtime execution.
|
|
1401
|
+
* Undefined when input is used instead.
|
|
1402
|
+
*/
|
|
1403
|
+
_forEachItemsFn;
|
|
1404
|
+
constructor(scope, id, props) {
|
|
1405
|
+
const stepProps = {
|
|
1406
|
+
...props.name !== void 0 && { name: props.name },
|
|
1407
|
+
...props.purpose !== void 0 && { purpose: props.purpose },
|
|
1408
|
+
...props.phase !== void 0 && { phase: props.phase },
|
|
1409
|
+
...props.sla !== void 0 && { sla: props.sla },
|
|
1410
|
+
...props.alwaysNotify !== void 0 && { alwaysNotify: props.alwaysNotify },
|
|
1411
|
+
output: props.output
|
|
1412
|
+
};
|
|
1413
|
+
super(scope, id, stepProps);
|
|
1414
|
+
this.longDuration = props.longDuration ?? false;
|
|
1415
|
+
if (props.retries !== void 0) {
|
|
1416
|
+
if (!Number.isInteger(props.retries) || props.retries < 0) throw new Error(`Step "${id}" has invalid retries value: ${props.retries}. Must be a non-negative integer.`);
|
|
1417
|
+
}
|
|
1418
|
+
this.retries = props.retries;
|
|
1419
|
+
if (props.forEach) {
|
|
1420
|
+
this._forEachItemsFn = props.forEach.items;
|
|
1421
|
+
this.hasForEach = true;
|
|
1422
|
+
} else this._inputFn = props.input;
|
|
1423
|
+
}
|
|
1424
|
+
/**
|
|
1425
|
+
* Get the output schema for this step.
|
|
1426
|
+
* Overrides base to return non-undefined (SystemSteps always have output).
|
|
1427
|
+
*/
|
|
1428
|
+
get output() {
|
|
1429
|
+
return super.output;
|
|
1430
|
+
}
|
|
1431
|
+
/**
|
|
1432
|
+
* Derive input from the current process state and context.
|
|
1433
|
+
* Called by SystemStepExecutor before executing.
|
|
1434
|
+
* Fails with ForEachStepRequiresItemsError if this is a forEach step
|
|
1435
|
+
* (use forEachItems instead). Author input callbacks may fail with
|
|
1436
|
+
* AuthorTaggedError; requirements stay deferred on R.
|
|
1437
|
+
*/
|
|
1438
|
+
input(state, ctx) {
|
|
1439
|
+
if (!this._inputFn) return Effect.fail(new ForEachStepRequiresItemsError({ stepPath: this.stepKey }));
|
|
1440
|
+
return this._inputFn(state, ctx);
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1443
|
+
* Get the forEach items for this step.
|
|
1444
|
+
* Returns the array of items, where each item IS the input for one execution.
|
|
1445
|
+
* Only available when forEach is configured.
|
|
1446
|
+
*/
|
|
1447
|
+
forEachItems(state, ctx) {
|
|
1448
|
+
if (!this._forEachItemsFn) return Effect.fail(new NotAForEachStepError({ stepPath: this.stepKey }));
|
|
1449
|
+
return this._forEachItemsFn(state, ctx);
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Execute the step with derived input.
|
|
1453
|
+
* This is the main entry point used by SystemStepExecutor for non-forEach steps.
|
|
1454
|
+
* For forEach steps, the executor calls execute(input) directly with item_data.
|
|
1455
|
+
*/
|
|
1456
|
+
executeWithInput(state, ctx) {
|
|
1457
|
+
return Effect.gen(this, function* () {
|
|
1458
|
+
const input = yield* this.input(state, ctx);
|
|
1459
|
+
return yield* this.execute(input);
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Execute the step and wrap output as a StepResult.
|
|
1464
|
+
*
|
|
1465
|
+
* The default implementation calls `execute()` and returns `Completed`.
|
|
1466
|
+
* Runtime/platform decides where and how this code runs (for example,
|
|
1467
|
+
* inline in a worker or dispatched to another runtime for long-duration
|
|
1468
|
+
* steps).
|
|
1469
|
+
*
|
|
1470
|
+
* @param input - Pre-computed input for the step
|
|
1471
|
+
* @param _jobContext - Job identifiers (todoId, stepPath) for external dispatch
|
|
1472
|
+
* @returns A StepResult indicating whether the step completed or was deferred
|
|
1473
|
+
*/
|
|
1474
|
+
executeStep(input, _jobContext) {
|
|
1475
|
+
return Effect.map(this.execute(input), (output) => ({
|
|
1476
|
+
_tag: "Completed",
|
|
1477
|
+
output
|
|
1478
|
+
}));
|
|
1479
|
+
}
|
|
1480
|
+
onError(target, options) {
|
|
1481
|
+
return createOnErrorFlowPath(this, target, this.process, options);
|
|
1482
|
+
}
|
|
1483
|
+
};
|
|
1484
|
+
//#endregion
|
|
1485
|
+
//#region ../process/src/lib/form.ts
|
|
1486
|
+
const astChildKeys = [
|
|
1487
|
+
"type",
|
|
1488
|
+
"types",
|
|
1489
|
+
"from",
|
|
1490
|
+
"to",
|
|
1491
|
+
"elements",
|
|
1492
|
+
"rest"
|
|
1493
|
+
];
|
|
1494
|
+
const isAst = (value) => typeof value === "object" && value !== null && "_tag" in value && typeof value._tag === "string";
|
|
1495
|
+
const getRawAnnotation = (value, annotationId) => {
|
|
1496
|
+
const annotation = value.annotations?.[annotationId];
|
|
1497
|
+
return annotation === void 0 ? Option.none() : Option.some(annotation);
|
|
1498
|
+
};
|
|
1499
|
+
const getSchemaAnnotationDeep = (schema, annotationId) => {
|
|
1500
|
+
const visit = (ast, seen) => {
|
|
1501
|
+
const direct = SchemaAST.getAnnotation(ast, annotationId);
|
|
1502
|
+
if (Option.isSome(direct)) return direct;
|
|
1503
|
+
if (seen.has(ast)) return Option.none();
|
|
1504
|
+
seen.add(ast);
|
|
1505
|
+
if (SchemaAST.isSuspend(ast)) {
|
|
1506
|
+
const result = visit(ast.f(), seen);
|
|
1507
|
+
if (Option.isSome(result)) return result;
|
|
1508
|
+
}
|
|
1509
|
+
const record = ast;
|
|
1510
|
+
if (Array.isArray(record["propertySignatures"])) for (const property of record["propertySignatures"]) {
|
|
1511
|
+
if (typeof property !== "object" || property === null) continue;
|
|
1512
|
+
const propertyRecord = property;
|
|
1513
|
+
const propertyAnnotation = getRawAnnotation(propertyRecord, annotationId);
|
|
1514
|
+
if (Option.isSome(propertyAnnotation)) return propertyAnnotation;
|
|
1515
|
+
if (isAst(propertyRecord.type)) {
|
|
1516
|
+
const result = visit(propertyRecord.type, seen);
|
|
1517
|
+
if (Option.isSome(result)) return result;
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
if (Array.isArray(record["indexSignatures"])) for (const signature of record["indexSignatures"]) {
|
|
1521
|
+
if (typeof signature !== "object" || signature === null) continue;
|
|
1522
|
+
const signatureRecord = signature;
|
|
1523
|
+
for (const child of [signatureRecord.parameter, signatureRecord.type]) {
|
|
1524
|
+
if (!isAst(child)) continue;
|
|
1525
|
+
const result = visit(child, seen);
|
|
1526
|
+
if (Option.isSome(result)) return result;
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
for (const key of astChildKeys) {
|
|
1530
|
+
const child = record[key];
|
|
1531
|
+
if (Array.isArray(child)) {
|
|
1532
|
+
for (const item of child) {
|
|
1533
|
+
if (!isAst(item)) continue;
|
|
1534
|
+
const result = visit(item, seen);
|
|
1535
|
+
if (Option.isSome(result)) return result;
|
|
1536
|
+
}
|
|
1537
|
+
continue;
|
|
1538
|
+
}
|
|
1539
|
+
if (isAst(child)) {
|
|
1540
|
+
const result = visit(child, seen);
|
|
1541
|
+
if (Option.isSome(result)) return result;
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
return Option.none();
|
|
1545
|
+
};
|
|
1546
|
+
return visit(schema.ast, /* @__PURE__ */ new Set());
|
|
1547
|
+
};
|
|
1548
|
+
const dynamicTextBlockResolutionConcurrency = 5;
|
|
1549
|
+
const isFieldSetComponent = (component) => component._tag === "fieldset";
|
|
1550
|
+
const isStaticComponent = (component) => component._tag === "static";
|
|
1551
|
+
const isListComponent = (component) => component._tag === "list";
|
|
1552
|
+
const isTableComponent = (component) => component._tag === "table";
|
|
1553
|
+
const isDynamicTextBlockContent = (value) => typeof value === "function";
|
|
1554
|
+
const getSchemaAst = (schema) => {
|
|
1555
|
+
if (Schema.isPropertySignature(schema)) return fieldInputAst(schema);
|
|
1556
|
+
if (typeof schema !== "object" && typeof schema !== "function" || schema === null || !("ast" in schema)) return;
|
|
1557
|
+
const ast = schema.ast;
|
|
1558
|
+
return isAst(ast) ? ast : void 0;
|
|
1559
|
+
};
|
|
1560
|
+
const getDynamicTextBlockContent = (schema) => {
|
|
1561
|
+
const ast = isAst(schema) ? schema : getSchemaAst(schema);
|
|
1562
|
+
if (!ast) return;
|
|
1563
|
+
const content = Option.getOrUndefined(SchemaAST.getAnnotation(ast, TEXTBLOCK_DYNAMIC_CONTENT_SYMBOL));
|
|
1564
|
+
return isDynamicTextBlockContent(content) ? content : void 0;
|
|
1565
|
+
};
|
|
1566
|
+
const getStructFields = (schema) => {
|
|
1567
|
+
if (typeof schema !== "object" && typeof schema !== "function" || schema === null || !("fields" in schema)) return;
|
|
1568
|
+
const fields = schema.fields;
|
|
1569
|
+
return typeof fields === "object" && fields !== null ? fields : void 0;
|
|
1570
|
+
};
|
|
1571
|
+
const getTypeLiteralFields = (ast) => {
|
|
1572
|
+
if (!ast) return void 0;
|
|
1573
|
+
if (ast._tag === "Transformation" || ast._tag === "Refinement") return getTypeLiteralFields(ast.from);
|
|
1574
|
+
if (ast._tag === "Union") {
|
|
1575
|
+
for (const member of ast.types) {
|
|
1576
|
+
const fields = getTypeLiteralFields(member);
|
|
1577
|
+
if (fields) return fields;
|
|
1578
|
+
}
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1581
|
+
if (ast._tag !== "TypeLiteral") return void 0;
|
|
1582
|
+
return Object.fromEntries(ast.propertySignatures.map((property) => [property.name, Schema.make(SchemaAST.annotations(property.type, property.annotations))]));
|
|
1583
|
+
};
|
|
1584
|
+
const getAstFields = (schema) => {
|
|
1585
|
+
const ast = isAst(schema) ? schema : getSchemaAst(schema);
|
|
1586
|
+
return getTypeLiteralFields(ast);
|
|
1587
|
+
};
|
|
1588
|
+
const getNestedFields = (schema) => getStructFields(schema) ?? getAstFields(schema);
|
|
1589
|
+
const getListItemFields = (schema) => {
|
|
1590
|
+
const ast = getSchemaAst(schema);
|
|
1591
|
+
if (ast?._tag !== "TupleType") return;
|
|
1592
|
+
const itemAst = ast.rest?.[0]?.type;
|
|
1593
|
+
return isAst(itemAst) ? getTypeLiteralFields(itemAst) : void 0;
|
|
1594
|
+
};
|
|
1595
|
+
/**
|
|
1596
|
+
* Counts leaf fields in a nested structure.
|
|
1597
|
+
* A "leaf" is any primitive value or empty array.
|
|
1598
|
+
* Objects and non-empty arrays are recursively traversed.
|
|
1599
|
+
*
|
|
1600
|
+
* @param value - The value to count leaf fields in
|
|
1601
|
+
* @returns The number of leaf fields
|
|
1602
|
+
*/
|
|
1603
|
+
const countLeafFields = (value) => {
|
|
1604
|
+
if (value === null || value === void 0) return 0;
|
|
1605
|
+
if (Array.isArray(value)) {
|
|
1606
|
+
if (value.length === 0) return 1;
|
|
1607
|
+
return value.reduce((total, item) => total + countLeafFields(item), 0);
|
|
1608
|
+
}
|
|
1609
|
+
if (typeof value === "object") {
|
|
1610
|
+
const entries = Object.values(value);
|
|
1611
|
+
if (entries.length === 0) return 0;
|
|
1612
|
+
return entries.reduce((total, item) => total + countLeafFields(item), 0);
|
|
1613
|
+
}
|
|
1614
|
+
return 1;
|
|
1615
|
+
};
|
|
1616
|
+
const FormRuleSelf = Symbol.for("processfocus/process/form-rule-self");
|
|
1617
|
+
const formRuleStateKeys = /* @__PURE__ */ new Set([
|
|
1618
|
+
"hidden",
|
|
1619
|
+
"disabled",
|
|
1620
|
+
"required",
|
|
1621
|
+
"label"
|
|
1622
|
+
]);
|
|
1623
|
+
const formRuleStateTypes = {
|
|
1624
|
+
hidden: "boolean",
|
|
1625
|
+
disabled: "boolean",
|
|
1626
|
+
required: "boolean",
|
|
1627
|
+
label: "string"
|
|
1628
|
+
};
|
|
1629
|
+
const isFormRuleTargetState = (value) => {
|
|
1630
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
1631
|
+
const keys = Object.keys(value);
|
|
1632
|
+
return keys.length > 0 && keys.every((key) => {
|
|
1633
|
+
if (!formRuleStateKeys.has(key)) return false;
|
|
1634
|
+
const expected = formRuleStateTypes[key];
|
|
1635
|
+
if (!expected) return false;
|
|
1636
|
+
return typeof value[key] === expected;
|
|
1637
|
+
});
|
|
1638
|
+
};
|
|
1639
|
+
const ruleFieldValue = (path) => ({
|
|
1640
|
+
_tag: "field",
|
|
1641
|
+
path
|
|
1642
|
+
});
|
|
1643
|
+
const ruleLiteralValue = (value) => ({
|
|
1644
|
+
_tag: "literal",
|
|
1645
|
+
value
|
|
1646
|
+
});
|
|
1647
|
+
const comparison = (tag, path, value) => ({
|
|
1648
|
+
_tag: tag,
|
|
1649
|
+
left: ruleFieldValue(path),
|
|
1650
|
+
right: ruleLiteralValue(value)
|
|
1651
|
+
});
|
|
1652
|
+
const membership = (tag, path, values) => ({
|
|
1653
|
+
_tag: tag,
|
|
1654
|
+
value: ruleFieldValue(path),
|
|
1655
|
+
candidates: ruleLiteralValue(values)
|
|
1656
|
+
});
|
|
1657
|
+
const ordering = (operator, path, value) => ({
|
|
1658
|
+
_tag: typeof value === "number" ? "numberOrder" : "stringOrder",
|
|
1659
|
+
operator,
|
|
1660
|
+
left: ruleFieldValue(path),
|
|
1661
|
+
right: ruleLiteralValue(value)
|
|
1662
|
+
});
|
|
1663
|
+
const makeValueAccessor = (path) => ({
|
|
1664
|
+
equals: (value) => comparison("equals", path, value),
|
|
1665
|
+
notEquals: (value) => comparison("notEquals", path, value),
|
|
1666
|
+
in: (values) => membership("in", path, values),
|
|
1667
|
+
notIn: (values) => membership("notIn", path, values),
|
|
1668
|
+
blank: () => ({
|
|
1669
|
+
_tag: "blank",
|
|
1670
|
+
value: ruleFieldValue(path)
|
|
1671
|
+
}),
|
|
1672
|
+
present: () => ({
|
|
1673
|
+
_tag: "present",
|
|
1674
|
+
value: ruleFieldValue(path)
|
|
1675
|
+
}),
|
|
1676
|
+
lt: (value) => ordering("lt", path, value),
|
|
1677
|
+
lte: (value) => ordering("lte", path, value),
|
|
1678
|
+
gt: (value) => ordering("gt", path, value),
|
|
1679
|
+
gte: (value) => ordering("gte", path, value)
|
|
1680
|
+
});
|
|
1681
|
+
const makeRuleAuthor = () => ({
|
|
1682
|
+
when: (condition) => ({ effects: (effects, otherwise) => ({
|
|
1683
|
+
condition,
|
|
1684
|
+
effects: flattenRuleEffects(effects),
|
|
1685
|
+
...otherwise ? { otherwise: flattenRuleEffects(otherwise) } : {}
|
|
1686
|
+
}) }),
|
|
1687
|
+
and: (...expressions) => ({
|
|
1688
|
+
_tag: "and",
|
|
1689
|
+
expressions
|
|
1690
|
+
}),
|
|
1691
|
+
or: (...expressions) => ({
|
|
1692
|
+
_tag: "or",
|
|
1693
|
+
expressions
|
|
1694
|
+
}),
|
|
1695
|
+
not: (expression) => ({
|
|
1696
|
+
_tag: "not",
|
|
1697
|
+
expression
|
|
1698
|
+
})
|
|
1699
|
+
});
|
|
1700
|
+
const makeValueAccessors = (fields, path = []) => Object.entries(fields).reduce((accessors, [key, schema]) => {
|
|
1701
|
+
if (hasStructuralOnlyAnnotation(schema) || isReadOnlyField(schema)) return accessors;
|
|
1702
|
+
const nextPath = [...path, key];
|
|
1703
|
+
const nestedFields = getNestedFields(schema);
|
|
1704
|
+
const isFlattened = hasFlattenAnnotation(schema);
|
|
1705
|
+
if (nestedFields && isFlattened) {
|
|
1706
|
+
Object.assign(accessors, makeValueAccessors(nestedFields, path));
|
|
1707
|
+
return accessors;
|
|
1708
|
+
}
|
|
1709
|
+
accessors[key] = nestedFields ? makeValueAccessors(nestedFields, nextPath) : makeValueAccessor(nextPath);
|
|
1710
|
+
return accessors;
|
|
1711
|
+
}, {});
|
|
1712
|
+
const flattenRuleEffects = (tree) => {
|
|
1713
|
+
const effects = [];
|
|
1714
|
+
const visit = (value, path) => {
|
|
1715
|
+
if (isFormRuleTargetState(value)) {
|
|
1716
|
+
effects.push({
|
|
1717
|
+
target: path,
|
|
1718
|
+
state: value
|
|
1719
|
+
});
|
|
1720
|
+
return;
|
|
1721
|
+
}
|
|
1722
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return;
|
|
1723
|
+
const record = value;
|
|
1724
|
+
const selfState = record[FormRuleSelf];
|
|
1725
|
+
if (selfState !== void 0 && isFormRuleTargetState(selfState)) effects.push({
|
|
1726
|
+
target: path,
|
|
1727
|
+
state: selfState
|
|
1728
|
+
});
|
|
1729
|
+
for (const [key, child] of Object.entries(record)) visit(child, [...path, key]);
|
|
1730
|
+
};
|
|
1731
|
+
visit(tree, []);
|
|
1732
|
+
return effects;
|
|
1733
|
+
};
|
|
1734
|
+
const getFormRuleTargetComponent = (representation, path) => {
|
|
1735
|
+
let current = representation;
|
|
1736
|
+
let component;
|
|
1737
|
+
for (const segment of path) {
|
|
1738
|
+
if (typeof segment !== "string" || !current) return void 0;
|
|
1739
|
+
component = current[segment];
|
|
1740
|
+
if (!component) return void 0;
|
|
1741
|
+
if (isFieldSetComponent(component)) current = component.children;
|
|
1742
|
+
else if (isListComponent(component) || isTableComponent(component)) current = component.itemChildren;
|
|
1743
|
+
else current = void 0;
|
|
1744
|
+
}
|
|
1745
|
+
return component;
|
|
1746
|
+
};
|
|
1747
|
+
const isStructuralOrStaticRuleTarget = (component) => {
|
|
1748
|
+
switch (component._tag) {
|
|
1749
|
+
case "fieldset":
|
|
1750
|
+
case "static":
|
|
1751
|
+
case "link":
|
|
1752
|
+
case "metric-breakdown": return true;
|
|
1753
|
+
case "table": return true;
|
|
1754
|
+
case "text":
|
|
1755
|
+
case "textarea":
|
|
1756
|
+
case "number":
|
|
1757
|
+
case "date":
|
|
1758
|
+
case "email":
|
|
1759
|
+
case "phone":
|
|
1760
|
+
case "provider-user":
|
|
1761
|
+
case "boolean":
|
|
1762
|
+
case "select":
|
|
1763
|
+
case "radio":
|
|
1764
|
+
case "file":
|
|
1765
|
+
case "list":
|
|
1766
|
+
case "lookup":
|
|
1767
|
+
case "calendar-slot":
|
|
1768
|
+
case "plugin": return false;
|
|
1769
|
+
default: return component;
|
|
1770
|
+
}
|
|
1771
|
+
};
|
|
1772
|
+
const formRulePathToFieldName = (path) => path.every((segment) => typeof segment === "string") ? path.join(".") : void 0;
|
|
1773
|
+
const hasFormRuleFieldName = (representation, fieldName) => {
|
|
1774
|
+
for (const component of Object.values(representation)) {
|
|
1775
|
+
if ("field" in component && component.field === fieldName) return true;
|
|
1776
|
+
if (isFieldSetComponent(component) && hasFormRuleFieldName(component.children, fieldName)) return true;
|
|
1777
|
+
}
|
|
1778
|
+
return false;
|
|
1779
|
+
};
|
|
1780
|
+
const hasFormRuleFieldPath = (representation, path) => {
|
|
1781
|
+
const fieldName = formRulePathToFieldName(path);
|
|
1782
|
+
if (fieldName === void 0) return false;
|
|
1783
|
+
if (hasFormRuleFieldName(representation, fieldName)) return true;
|
|
1784
|
+
let current = representation;
|
|
1785
|
+
let component;
|
|
1786
|
+
for (const segment of path) {
|
|
1787
|
+
if (typeof segment !== "string" || !current) return false;
|
|
1788
|
+
component = current[segment];
|
|
1789
|
+
if (!component) return false;
|
|
1790
|
+
current = isFieldSetComponent(component) ? component.children : void 0;
|
|
1791
|
+
}
|
|
1792
|
+
return component !== void 0;
|
|
1793
|
+
};
|
|
1794
|
+
const validateFormRuleTargets = (formStep, representation, rules) => {
|
|
1795
|
+
for (const rule of rules) {
|
|
1796
|
+
const conditionPaths = formRuleConditionPaths({ expression: rule.condition });
|
|
1797
|
+
for (const path of conditionPaths) if (!hasFormRuleFieldPath(representation, path)) throw new Error(`Form "${formStep}" rule condition references missing field "${path.join(".")}" in rendered form tree`);
|
|
1798
|
+
for (const effect of [...rule.effects, ...rule.otherwise ?? []]) {
|
|
1799
|
+
const target = getFormRuleTargetComponent(representation, effect.target);
|
|
1800
|
+
if (!target) throw new Error(`Form "${formStep}" rule targets missing field "${effect.target.join(".")}" in rendered form tree`);
|
|
1801
|
+
if (effect.state.required !== void 0 && isStructuralOrStaticRuleTarget(target)) throw new Error(`Form "${formStep}" rule target "${effect.target.join(".")}" cannot set required on structural or static display components`);
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
};
|
|
1805
|
+
const defaultProviderUserDisplay = { display: (providerUserIdOrEmail) => Effect.succeed(providerUserIdOrEmail) };
|
|
1806
|
+
const toSummaryContext = (ctx) => {
|
|
1807
|
+
if ("providerUserDisplay" in ctx) return ctx;
|
|
1808
|
+
return {
|
|
1809
|
+
...ctx,
|
|
1810
|
+
providerUserDisplay: defaultProviderUserDisplay
|
|
1811
|
+
};
|
|
1812
|
+
};
|
|
1813
|
+
const normalizeEmbedSite = (site) => {
|
|
1814
|
+
let url;
|
|
1815
|
+
try {
|
|
1816
|
+
url = new URL(site);
|
|
1817
|
+
} catch {
|
|
1818
|
+
throw new Error(`Invalid embed site origin: ${site}`);
|
|
1819
|
+
}
|
|
1820
|
+
if (url.protocol !== "https:" && url.protocol !== "http:" || url.pathname !== "/" && url.pathname !== "" || url.search !== "" || url.hash !== "") throw new Error(`Embed site must be an exact origin without path, query, or hash: ${site}`);
|
|
1821
|
+
return url.origin;
|
|
1822
|
+
};
|
|
1823
|
+
const normalizeEmbedConfig = (config, submissionFields) => {
|
|
1824
|
+
const sites = [...new Set(config.sites.map(normalizeEmbedSite))];
|
|
1825
|
+
if (sites.length === 0) throw new Error("Embedded forms must configure at least one allowed site");
|
|
1826
|
+
const thankYou = config.thankYou.trim();
|
|
1827
|
+
if (thankYou.length === 0) throw new Error("Embedded forms must configure non-empty thank-you copy");
|
|
1828
|
+
const externalParticipantEmailField = config.externalParticipantEmailField.trim();
|
|
1829
|
+
if (externalParticipantEmailField.length === 0) throw new Error("Embedded forms must configure an external participant email field");
|
|
1830
|
+
if (!Object.hasOwn(submissionFields, externalParticipantEmailField)) throw new Error(`Embedded form external participant email field "${externalParticipantEmailField}" is not a submittable form field`);
|
|
1831
|
+
return {
|
|
1832
|
+
sites,
|
|
1833
|
+
thankYou,
|
|
1834
|
+
externalParticipantEmailField
|
|
1835
|
+
};
|
|
1836
|
+
};
|
|
1837
|
+
/**
|
|
1838
|
+
* Flatten a defaults record according to form schema structure.
|
|
1839
|
+
* Wrapper fields' nested values are spread into the parent level.
|
|
1840
|
+
* Structural-only fields are excluded (they have no values).
|
|
1841
|
+
* Read-only fields are kept (they carry resolved values).
|
|
1842
|
+
*/
|
|
1843
|
+
const flattenDefaults = (defaults, schema) => {
|
|
1844
|
+
const flat = {};
|
|
1845
|
+
for (const [key, field] of Object.entries(schema.fields)) {
|
|
1846
|
+
const fieldAsAny = field;
|
|
1847
|
+
if (hasStructuralOnlyAnnotation(fieldAsAny)) continue;
|
|
1848
|
+
if (hasFlattenAnnotation(fieldAsAny) && fieldAsAny.ast._tag === "TypeLiteral" && "fields" in fieldAsAny) {
|
|
1849
|
+
const nestedValue = defaults[key];
|
|
1850
|
+
const nestedFlat = flattenDefaults(typeof nestedValue === "object" && nestedValue !== null ? nestedValue : defaults, fieldAsAny);
|
|
1851
|
+
Object.assign(flat, nestedFlat);
|
|
1852
|
+
} else if (key in defaults) {
|
|
1853
|
+
const value = defaults[key];
|
|
1854
|
+
const nested = getStructFields(field);
|
|
1855
|
+
flat[key] = nested && typeof value === "object" && value !== null && !Array.isArray(value) ? flattenDefaults(value, Schema.Struct(nested)) : value;
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
return flat;
|
|
1859
|
+
};
|
|
1860
|
+
/**
|
|
1861
|
+
* Form step class with support for typed state and context access.
|
|
1862
|
+
*
|
|
1863
|
+
* When using a Step/FlowPath as scope, the state and steps types are
|
|
1864
|
+
* automatically inferred from the accumulated state of previous steps.
|
|
1865
|
+
*
|
|
1866
|
+
* @typeParam TState - Accumulated state type from completed steps
|
|
1867
|
+
* @typeParam TSteps - Record of completed step metadata for ctx.step access
|
|
1868
|
+
* @typeParam TInput - Form input schema (inferred from form function return type)
|
|
1869
|
+
* @typeParam TId - Step identifier literal type
|
|
1870
|
+
* @typeParam TItem - Type of forEach item (undefined when no forEach)
|
|
1871
|
+
* @typeParam TIsForEach - Whether this step uses forEach semantics
|
|
1872
|
+
*
|
|
1873
|
+
* @example
|
|
1874
|
+
* ```typescript
|
|
1875
|
+
* // Static form with Process scope
|
|
1876
|
+
* const submit = new Form(process, "Submit", {
|
|
1877
|
+
* form: () => ({ item: ES.String, value: ES.Number }),
|
|
1878
|
+
* role: employeeRole,
|
|
1879
|
+
* })
|
|
1880
|
+
*
|
|
1881
|
+
* // Dynamic form with Step/Flow scope - state is inferred
|
|
1882
|
+
* const flow = process.start(submit)
|
|
1883
|
+
* const approve = new Form(flow, "Approve", {
|
|
1884
|
+
* form: ({ value }) => ({
|
|
1885
|
+
* item: TextField({ default: value((state) => state.item), readOnly: true }),
|
|
1886
|
+
* approved: ES.Boolean,
|
|
1887
|
+
* }),
|
|
1888
|
+
* summary: (state, ctx) => ({
|
|
1889
|
+
* Item: state.item,
|
|
1890
|
+
* Requester: ctx.step.submit.providerUser.name,
|
|
1891
|
+
* }),
|
|
1892
|
+
* role: managerRole,
|
|
1893
|
+
* })
|
|
1894
|
+
* ```
|
|
1895
|
+
*/
|
|
1896
|
+
/**
|
|
1897
|
+
* Error raised when a lookup field is not found or is not annotated
|
|
1898
|
+
* as a lookup field in the form schema.
|
|
1899
|
+
*/
|
|
1900
|
+
var LookupFieldNotFoundError = class extends Data.TaggedError("LookupFieldNotFoundError") {};
|
|
1901
|
+
var Form = class extends Step {
|
|
1902
|
+
/**
|
|
1903
|
+
* The form fields schema extracted from the form function.
|
|
1904
|
+
*/
|
|
1905
|
+
_formFields;
|
|
1906
|
+
/**
|
|
1907
|
+
* Request-local resolution of the static declaration's lazy expressions.
|
|
1908
|
+
*/
|
|
1909
|
+
_formFn;
|
|
1910
|
+
/**
|
|
1911
|
+
* The summary function, stored for computing summary from process state.
|
|
1912
|
+
*/
|
|
1913
|
+
_summaryFn;
|
|
1914
|
+
_assigneeFn;
|
|
1915
|
+
/**
|
|
1916
|
+
* The forEach items function, stored for runtime execution.
|
|
1917
|
+
* Undefined when no forEach is configured.
|
|
1918
|
+
*/
|
|
1919
|
+
_forEachItemsFn;
|
|
1920
|
+
/**
|
|
1921
|
+
* The full validation schema: Schema.Struct(fields) optionally refined
|
|
1922
|
+
* with a struct-level filterEffect from the validate prop.
|
|
1923
|
+
*/
|
|
1924
|
+
_schema;
|
|
1925
|
+
/**
|
|
1926
|
+
* The flat submission validation schema: submissionSchema(fields) optionally
|
|
1927
|
+
* refined with a struct-level filterEffect from the validate prop.
|
|
1928
|
+
* Used for server-side validation where wrapper nesting is irrelevant.
|
|
1929
|
+
*/
|
|
1930
|
+
_submissionEffectSchema;
|
|
1931
|
+
/**
|
|
1932
|
+
* Lookup query overrides set via `this.lookups.<field>.setQuery()`.
|
|
1933
|
+
*/
|
|
1934
|
+
_lookupOverrides = /* @__PURE__ */ new Map();
|
|
1935
|
+
/**
|
|
1936
|
+
* Typed accessors for lookup fields.
|
|
1937
|
+
* Use `this.lookups.<field>.setQuery()` for independent lookups or
|
|
1938
|
+
* `this.lookups.<field>.dependsOn([...]).setQuery()` for dependent lookups.
|
|
1939
|
+
*/
|
|
1940
|
+
static self = FormRuleSelf;
|
|
1941
|
+
isForm = true;
|
|
1942
|
+
lookups;
|
|
1943
|
+
_rules = [];
|
|
1944
|
+
embed;
|
|
1945
|
+
supportingRoles;
|
|
1946
|
+
publicCompletion;
|
|
1947
|
+
/**
|
|
1948
|
+
* Create a Form step.
|
|
1949
|
+
*
|
|
1950
|
+
* @param scope - Parent Process or Step. When a Step is provided, state type is inferred.
|
|
1951
|
+
* @param id - Unique identifier for this step
|
|
1952
|
+
* @param props - Form properties including form function and optional summary
|
|
1953
|
+
*/
|
|
1954
|
+
constructor(scope, id, props) {
|
|
1955
|
+
if (props.publicCompletion && isProcess(scope)) throw new Error("publicCompletion is only valid on non-start forms");
|
|
1956
|
+
if (props.supportingRoles?.some((r) => r.node.path === props.role.node.path)) throw new Error(`Form "${id}": primary role must not be in supportingRoles`);
|
|
1957
|
+
const supportingPaths = props.supportingRoles?.map((r) => r.node.path) ?? [];
|
|
1958
|
+
if (new Set(supportingPaths).size !== supportingPaths.length) throw new Error(`Form "${id}": supportingRoles contains duplicate roles`);
|
|
1959
|
+
const stepProps = {
|
|
1960
|
+
role: props.role,
|
|
1961
|
+
...props.name !== void 0 && { name: props.name },
|
|
1962
|
+
...props.purpose !== void 0 && { purpose: props.purpose },
|
|
1963
|
+
...props.phase !== void 0 && { phase: props.phase },
|
|
1964
|
+
...props.sla !== void 0 && { sla: props.sla },
|
|
1965
|
+
...props.alwaysNotify !== void 0 && { alwaysNotify: props.alwaysNotify }
|
|
1966
|
+
};
|
|
1967
|
+
super(scope, id, stepProps);
|
|
1968
|
+
const authoring = createFormAuthoring();
|
|
1969
|
+
const fields = Object.freeze({ ...props.form(authoring.helpers) });
|
|
1970
|
+
this._formFields = authoring.project(fields);
|
|
1971
|
+
this._formFn = (state, ctx, item) => authoring.project(fields, [
|
|
1972
|
+
state,
|
|
1973
|
+
ctx,
|
|
1974
|
+
item
|
|
1975
|
+
]);
|
|
1976
|
+
assertResolvedFormFields(this._formFields);
|
|
1977
|
+
const struct = Schema.Struct(this._formFields);
|
|
1978
|
+
this._schema = props.validate ? struct.pipe(Schema.filterEffect(props.validate)) : struct;
|
|
1979
|
+
const flatSubmission = submissionSchemaSync(struct);
|
|
1980
|
+
this._submissionEffectSchema = props.validate ? flatSubmission.pipe(Schema.filterEffect(props.validate)) : flatSubmission;
|
|
1981
|
+
this.lookups = Object.fromEntries(Object.keys(this._formFields).map((k) => [k, new LookupAccessor(this, k)]));
|
|
1982
|
+
this.embed = props.embed ? normalizeEmbedConfig(props.embed, flatSubmission.fields) : void 0;
|
|
1983
|
+
this.supportingRoles = props.supportingRoles;
|
|
1984
|
+
this.publicCompletion = props.publicCompletion;
|
|
1985
|
+
if (props.summary) this._summaryFn = props.summary;
|
|
1986
|
+
if (props.assignee) this._assigneeFn = props.assignee;
|
|
1987
|
+
if (props.forEach) {
|
|
1988
|
+
this._forEachItemsFn = props.forEach.items;
|
|
1989
|
+
this.hasForEach = true;
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
/** @internal Called by LookupAccessor/LookupBuilder to store overrides. */
|
|
1993
|
+
_setLookupOverride(fieldName, override) {
|
|
1994
|
+
this._lookupOverrides.set(fieldName, override);
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Returns all lookup overrides set via `this.lookups`.
|
|
1998
|
+
* Used by the schema generator to emit per-lookup GraphQL queries.
|
|
1999
|
+
*/
|
|
2000
|
+
lookupOverrides() {
|
|
2001
|
+
return this._lookupOverrides;
|
|
2002
|
+
}
|
|
2003
|
+
/**
|
|
2004
|
+
* Append browser-safe form rules authored against typed field accessors and
|
|
2005
|
+
* a typed target tree matching this form's schema.
|
|
2006
|
+
*/
|
|
2007
|
+
rules(build) {
|
|
2008
|
+
this._rules.push(...build(makeValueAccessors(this._formFields), makeRuleAuthor()));
|
|
2009
|
+
return this;
|
|
2010
|
+
}
|
|
2011
|
+
authoritativeFormRules() {
|
|
2012
|
+
return [...this._rules];
|
|
2013
|
+
}
|
|
2014
|
+
flattenRuleTargetPath(path) {
|
|
2015
|
+
const flat = [];
|
|
2016
|
+
let currentFields = this._formFields;
|
|
2017
|
+
for (const segment of path) {
|
|
2018
|
+
if (typeof segment !== "string" || !currentFields) {
|
|
2019
|
+
flat.push(segment);
|
|
2020
|
+
continue;
|
|
2021
|
+
}
|
|
2022
|
+
const fieldSchema = currentFields[segment];
|
|
2023
|
+
if (!fieldSchema) {
|
|
2024
|
+
flat.push(segment);
|
|
2025
|
+
currentFields = void 0;
|
|
2026
|
+
continue;
|
|
2027
|
+
}
|
|
2028
|
+
const nestedFields = getNestedFields(fieldSchema);
|
|
2029
|
+
if (hasFlattenAnnotation(fieldSchema) && nestedFields) currentFields = nestedFields;
|
|
2030
|
+
else {
|
|
2031
|
+
flat.push(segment);
|
|
2032
|
+
currentFields = nestedFields;
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
return flat;
|
|
2036
|
+
}
|
|
2037
|
+
evaluateFormRules(values, baseValues) {
|
|
2038
|
+
return evaluateFormRules({
|
|
2039
|
+
rules: this._rules,
|
|
2040
|
+
values,
|
|
2041
|
+
...baseValues === void 0 ? {} : { baseValues }
|
|
2042
|
+
});
|
|
2043
|
+
}
|
|
2044
|
+
/**
|
|
2045
|
+
* Returns the GraphQL query name for a dependent lookup field.
|
|
2046
|
+
* E.g. `lookupDevopsAddEnvironmentInputEnvironmentDetailsStageId`
|
|
2047
|
+
*/
|
|
2048
|
+
lookupQueryName(fieldName) {
|
|
2049
|
+
return `lookup${pathToPascalCase(this.node.path)}${fieldName.charAt(0).toUpperCase() + fieldName.slice(1)}`;
|
|
2050
|
+
}
|
|
2051
|
+
/**
|
|
2052
|
+
* Get the output schema for this form.
|
|
2053
|
+
* Returns the fields extracted from the form function.
|
|
2054
|
+
*/
|
|
2055
|
+
get output() {
|
|
2056
|
+
return this._formFields;
|
|
2057
|
+
}
|
|
2058
|
+
/**
|
|
2059
|
+
* Get the output validation schema for this form.
|
|
2060
|
+
* Returns Schema.Struct(fields), optionally refined with a struct-level
|
|
2061
|
+
* filterEffect when a `validate` callback was provided.
|
|
2062
|
+
*/
|
|
2063
|
+
get outputSchema() {
|
|
2064
|
+
return this._schema;
|
|
2065
|
+
}
|
|
2066
|
+
/**
|
|
2067
|
+
* Get the flat submission validation schema for this form.
|
|
2068
|
+
* Returns submissionSchema(fields) (wrapper fields flattened, read-only/
|
|
2069
|
+
* structural-only removed), optionally refined with a struct-level
|
|
2070
|
+
* filterEffect when a `validate` callback was provided.
|
|
2071
|
+
*
|
|
2072
|
+
* Used by start/complete resolvers for server-side validation where
|
|
2073
|
+
* wrapper nesting should not affect persisted state shape.
|
|
2074
|
+
*/
|
|
2075
|
+
get submissionEffectSchema() {
|
|
2076
|
+
return this._submissionEffectSchema;
|
|
2077
|
+
}
|
|
2078
|
+
/**
|
|
2079
|
+
* Get the forEach items for this form.
|
|
2080
|
+
* Returns the array of items, where each item is context data for one form instance.
|
|
2081
|
+
* Only available when forEach is configured.
|
|
2082
|
+
*/
|
|
2083
|
+
forEachItems(state, ctx) {
|
|
2084
|
+
if (!this._forEachItemsFn) return Effect.fail(new NotAForEachStepError({ stepPath: this.stepKey }));
|
|
2085
|
+
return this._forEachItemsFn(state, ctx);
|
|
2086
|
+
}
|
|
2087
|
+
/**
|
|
2088
|
+
* Get the form fields with defaults resolved against the given state.
|
|
2089
|
+
* Resolves inline lazy expressions against actual execution data.
|
|
2090
|
+
*
|
|
2091
|
+
* @param state - Process state to resolve defaults against
|
|
2092
|
+
* @param ctx - Flow context with step metadata
|
|
2093
|
+
* @param item - Optional forEach item data for per-instance context
|
|
2094
|
+
* @throws FormDecorationError when a runtime value or presentation is invalid
|
|
2095
|
+
* @returns Validated schema fields with defaults properly resolved
|
|
2096
|
+
*/
|
|
2097
|
+
getFieldsWithState(state, ctx, item) {
|
|
2098
|
+
return this._formFn(state, ctx, item);
|
|
2099
|
+
}
|
|
2100
|
+
/**
|
|
2101
|
+
* Check if this form has a summary function defined.
|
|
2102
|
+
*/
|
|
2103
|
+
get hasSummaryFunction() {
|
|
2104
|
+
return this._summaryFn !== void 0;
|
|
2105
|
+
}
|
|
2106
|
+
get hasAssigneeFunction() {
|
|
2107
|
+
return this._assigneeFn !== void 0;
|
|
2108
|
+
}
|
|
2109
|
+
/**
|
|
2110
|
+
* Resolve the assignee for this form given the current process state.
|
|
2111
|
+
* Returns undefined if no assignee function is defined.
|
|
2112
|
+
*
|
|
2113
|
+
* Errors in user-provided assignee functions are logged and undefined is
|
|
2114
|
+
* returned (same containment as getSummary / dynamic text blocks). Callers
|
|
2115
|
+
* must treat `hasAssigneeFunction === true` as “an assignee callback exists”,
|
|
2116
|
+
* not as a guarantee that a provider user id will be resolved.
|
|
2117
|
+
*/
|
|
2118
|
+
getAssignee(state, ctx, item) {
|
|
2119
|
+
if (!this._assigneeFn) return Effect.succeed(void 0);
|
|
2120
|
+
const assigneeFn = this._assigneeFn;
|
|
2121
|
+
return Effect.try(() => assigneeFn(state, ctx, item)).pipe(Effect.flatMap((assignee) => Effect.isEffect(assignee) ? assignee : Effect.succeed(assignee)), Effect.catchAllCause((cause) => Effect.logWarning(`Failed to resolve assignee for form "${this.node.id}"`, { cause }).pipe(Effect.as(void 0))));
|
|
2122
|
+
}
|
|
2123
|
+
/**
|
|
2124
|
+
* Compute the summary for this form given the current process state.
|
|
2125
|
+
* Returns an empty object if no summary function is defined.
|
|
2126
|
+
*
|
|
2127
|
+
* Errors in user-provided summary functions are logged and an empty object is returned.
|
|
2128
|
+
*
|
|
2129
|
+
* @param state - Process state to compute summary from
|
|
2130
|
+
* @param ctx - Flow context with step metadata
|
|
2131
|
+
* @param item - Optional forEach item data for per-instance context
|
|
2132
|
+
* @returns Effect producing summary record (label -> value)
|
|
2133
|
+
*/
|
|
2134
|
+
getSummary(state, ctx, item) {
|
|
2135
|
+
if (!this._summaryFn) return Effect.succeed({});
|
|
2136
|
+
const summaryFn = this._summaryFn;
|
|
2137
|
+
const summaryCtx = toSummaryContext(ctx);
|
|
2138
|
+
return Effect.try(() => summaryFn(state, summaryCtx, item)).pipe(Effect.flatMap((summary) => Effect.isEffect(summary) ? summary : Effect.succeed(summary)), Effect.catchAllCause((cause) => Effect.logWarning(`Failed to compute summary for form "${this.node.id}"`, { cause }).pipe(Effect.as({}))));
|
|
2139
|
+
}
|
|
2140
|
+
/**
|
|
2141
|
+
* Resolve default values from schema annotations.
|
|
2142
|
+
* Walks through the schema fields and executes any default functions.
|
|
2143
|
+
* Errors in user-provided default functions are logged and the field is skipped.
|
|
2144
|
+
*/
|
|
2145
|
+
resolveFieldDefaults(fields, currentProviderUser) {
|
|
2146
|
+
return resolveFormFieldDefaults(fields, currentProviderUser ?? "");
|
|
2147
|
+
}
|
|
2148
|
+
/**
|
|
2149
|
+
* Get the number of leaf fields in this form.
|
|
2150
|
+
* Counts primitive fields recursively, not just top-level keys.
|
|
2151
|
+
*/
|
|
2152
|
+
get totalFields() {
|
|
2153
|
+
return countLeafFields(getSchemaDefaults(this.output));
|
|
2154
|
+
}
|
|
2155
|
+
/**
|
|
2156
|
+
* Get the schema defaults for this form's input fields.
|
|
2157
|
+
* Returns type-compatible placeholder values (empty strings, 0, false, etc.).
|
|
2158
|
+
*
|
|
2159
|
+
* We need this as input for Tanstack Form in order to display the
|
|
2160
|
+
* initial values for a form.
|
|
2161
|
+
*
|
|
2162
|
+
* @returns Record of field names to their default values
|
|
2163
|
+
*/
|
|
2164
|
+
defaults() {
|
|
2165
|
+
return getSchemaDefaults(this.output);
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* Resolve initial metadata defaults without process state.
|
|
2169
|
+
* This keeps start-step metadata from leaking symbolic defaults to clients.
|
|
2170
|
+
*/
|
|
2171
|
+
resolveInitialDefaults(currentProviderUser) {
|
|
2172
|
+
return Effect.gen(this, function* () {
|
|
2173
|
+
const resolvedDefaults = yield* this.resolveFieldDefaults(this._formFields, currentProviderUser);
|
|
2174
|
+
return flattenDefaults(mergeFormDefaults(this.defaults(), resolvedDefaults), Schema.Struct(this._formFields));
|
|
2175
|
+
});
|
|
2176
|
+
}
|
|
2177
|
+
/**
|
|
2178
|
+
* Get the client representation for this form's fields.
|
|
2179
|
+
* Used for rendering the form in the UI.
|
|
2180
|
+
*
|
|
2181
|
+
* Post-processes the representation to add `dependencies` and `queryName`
|
|
2182
|
+
* to any lookup components that have dependent overrides.
|
|
2183
|
+
*
|
|
2184
|
+
* @returns Effect that produces the client representation
|
|
2185
|
+
*/
|
|
2186
|
+
buildClientComponents(fields) {
|
|
2187
|
+
const effectSchema = Schema.Struct(fields);
|
|
2188
|
+
return Effect.gen(this, function* () {
|
|
2189
|
+
const components = { ...yield* asClientRepresentation(effectSchema) };
|
|
2190
|
+
for (const [fieldName, override] of this._lookupOverrides) if (override.dependencies && override.dependencies.length > 0) {
|
|
2191
|
+
const component = components[fieldName];
|
|
2192
|
+
if (component && component._tag === "lookup") components[fieldName] = {
|
|
2193
|
+
...component,
|
|
2194
|
+
dependencies: override.dependencies,
|
|
2195
|
+
queryName: this.lookupQueryName(fieldName)
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2198
|
+
return components;
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
buildClientFormDefinition(fields) {
|
|
2202
|
+
return this.buildClientComponents(fields).pipe(Effect.map((components) => {
|
|
2203
|
+
if (this._rules.length > 0) validateFormRuleTargets(this.stepKey, components, this._rules);
|
|
2204
|
+
return {
|
|
2205
|
+
components,
|
|
2206
|
+
rules: this._rules
|
|
2207
|
+
};
|
|
2208
|
+
}));
|
|
2209
|
+
}
|
|
2210
|
+
resolveDynamicTextBlockComponent(fieldSchema, component) {
|
|
2211
|
+
if (isFieldSetComponent(component)) {
|
|
2212
|
+
const nestedFields = getNestedFields(fieldSchema);
|
|
2213
|
+
if (!nestedFields) return Effect.succeed(component);
|
|
2214
|
+
return this.resolveDynamicTextBlocks(nestedFields, component.children).pipe(Effect.map((children) => ({
|
|
2215
|
+
...component,
|
|
2216
|
+
children
|
|
2217
|
+
})));
|
|
2218
|
+
}
|
|
2219
|
+
if (isListComponent(component) || isTableComponent(component)) {
|
|
2220
|
+
const itemFields = getListItemFields(fieldSchema);
|
|
2221
|
+
if (!itemFields) return Effect.succeed(component);
|
|
2222
|
+
return this.resolveDynamicTextBlocks(itemFields, component.itemChildren).pipe(Effect.map((itemChildren) => ({
|
|
2223
|
+
...component,
|
|
2224
|
+
itemChildren
|
|
2225
|
+
})));
|
|
2226
|
+
}
|
|
2227
|
+
if (!fieldSchema || !isStaticComponent(component)) return Effect.succeed(component);
|
|
2228
|
+
const dynamicContent = getDynamicTextBlockContent(fieldSchema);
|
|
2229
|
+
if (!dynamicContent) return Effect.succeed(component);
|
|
2230
|
+
return dynamicContent().pipe(Effect.map((content) => ({
|
|
2231
|
+
...component,
|
|
2232
|
+
content
|
|
2233
|
+
})), Effect.catchAllCause((cause) => Effect.logWarning(`Failed to resolve dynamic text block for form "${this.node.id}"`, {
|
|
2234
|
+
cause,
|
|
2235
|
+
fieldName: component.field
|
|
2236
|
+
}).pipe(Effect.as(component))));
|
|
2237
|
+
}
|
|
2238
|
+
resolveDynamicTextBlocks(fields, representation) {
|
|
2239
|
+
return Effect.gen(this, function* () {
|
|
2240
|
+
const entries = yield* Effect.forEach(Object.entries(representation), ([fieldName, component]) => {
|
|
2241
|
+
const fieldSchema = fields[fieldName];
|
|
2242
|
+
return this.resolveDynamicTextBlockComponent(fieldSchema, component).pipe(Effect.map((resolved) => [fieldName, resolved]));
|
|
2243
|
+
}, { concurrency: dynamicTextBlockResolutionConcurrency });
|
|
2244
|
+
return Object.fromEntries(entries);
|
|
2245
|
+
});
|
|
2246
|
+
}
|
|
2247
|
+
buildRenderableClientFormDefinition(fields) {
|
|
2248
|
+
return this.buildClientFormDefinition(fields).pipe(Effect.flatMap((definition) => this.resolveDynamicTextBlocks(fields, definition.components).pipe(Effect.map((components) => ({
|
|
2249
|
+
components,
|
|
2250
|
+
rules: definition.rules
|
|
2251
|
+
})))));
|
|
2252
|
+
}
|
|
2253
|
+
clientFormDefinition() {
|
|
2254
|
+
return this.buildClientFormDefinition(this.output);
|
|
2255
|
+
}
|
|
2256
|
+
renderableClientFormDefinition() {
|
|
2257
|
+
return this.buildRenderableClientFormDefinition(this.output);
|
|
2258
|
+
}
|
|
2259
|
+
clientFormDefinitionWithState(state, ctx, item) {
|
|
2260
|
+
return this.buildClientFormDefinition(this.getFieldsWithState(state, ctx, item));
|
|
2261
|
+
}
|
|
2262
|
+
renderableClientFormDefinitionWithState(state, ctx, item) {
|
|
2263
|
+
return this.buildRenderableClientFormDefinition(this.getFieldsWithState(state, ctx, item));
|
|
2264
|
+
}
|
|
2265
|
+
/**
|
|
2266
|
+
* Get the submission schema for form validation.
|
|
2267
|
+
* Excludes read-only fields and removes additionalProperties constraint
|
|
2268
|
+
* to allow form values to include read-only fields.
|
|
2269
|
+
*
|
|
2270
|
+
* @returns JSON schema object
|
|
2271
|
+
*/
|
|
2272
|
+
submissionSchema() {
|
|
2273
|
+
const effectSchema = Schema.Struct(this.output);
|
|
2274
|
+
const submission = submissionSchemaSync(effectSchema);
|
|
2275
|
+
const { additionalProperties: _, ...schema } = JSONSchema.make(submission);
|
|
2276
|
+
const properties = schema["properties"];
|
|
2277
|
+
if (properties && submission.ast._tag === "TypeLiteral") for (const prop of submission.ast.propertySignatures) {
|
|
2278
|
+
const msg = SchemaAST.getAnnotation(prop.type, FormMessage);
|
|
2279
|
+
if (Option.isSome(msg) && typeof msg.value === "string") {
|
|
2280
|
+
const name = String(prop.name);
|
|
2281
|
+
if (properties[name]) properties[name]["x-message"] = msg.value;
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
return schema;
|
|
2285
|
+
}
|
|
2286
|
+
/**
|
|
2287
|
+
* Execute a lookup query for a specific field in this form.
|
|
2288
|
+
*
|
|
2289
|
+
* Checks for an override (set via `this.lookups`) first, then falls back
|
|
2290
|
+
* to the annotation-based query from the LookupField constructor.
|
|
2291
|
+
*
|
|
2292
|
+
* @param fieldName - The name of the lookup field
|
|
2293
|
+
* @param filter - Search filter string
|
|
2294
|
+
* @param limit - Maximum number of results
|
|
2295
|
+
* @param deps - Dependency values for dependent lookups (field name → value)
|
|
2296
|
+
* @returns Effect producing an array of LookupItems
|
|
2297
|
+
*/
|
|
2298
|
+
executeLookup(fieldName, filter, limit, deps = {}) {
|
|
2299
|
+
const override = this._lookupOverrides.get(fieldName);
|
|
2300
|
+
if (override) {
|
|
2301
|
+
const input = { filter };
|
|
2302
|
+
for (const [k, v] of Object.entries(deps)) if (v !== void 0) input[k] = v;
|
|
2303
|
+
return override.query(input, limit);
|
|
2304
|
+
}
|
|
2305
|
+
const fieldSchema = this._formFields[fieldName];
|
|
2306
|
+
if (!fieldSchema) return new LookupFieldNotFoundError({
|
|
2307
|
+
fieldName,
|
|
2308
|
+
formStep: this.stepKey,
|
|
2309
|
+
message: `Lookup field "${fieldName}" not found in form "${this.stepKey}"`
|
|
2310
|
+
});
|
|
2311
|
+
const metadata = Option.getOrUndefined(getSchemaAnnotationDeep(fieldSchema, FormLookupInput));
|
|
2312
|
+
if (!metadata?.query) return new LookupFieldNotFoundError({
|
|
2313
|
+
fieldName,
|
|
2314
|
+
formStep: this.stepKey,
|
|
2315
|
+
message: `Field "${fieldName}" in form "${this.stepKey}" is not a lookup field (no query defined)`
|
|
2316
|
+
});
|
|
2317
|
+
return metadata.query(filter, limit);
|
|
2318
|
+
}
|
|
2319
|
+
/** Re-run the form so lookup query closures can see process state. */
|
|
2320
|
+
executeLookupWithState(fieldName, filter, limit, state, ctx, item, deps = {}) {
|
|
2321
|
+
if (this._lookupOverrides.has(fieldName)) return this.executeLookup(fieldName, filter, limit, deps);
|
|
2322
|
+
const fieldSchema = this.getFieldsWithState(state, ctx, item)[fieldName];
|
|
2323
|
+
if (!fieldSchema) return new LookupFieldNotFoundError({
|
|
2324
|
+
fieldName,
|
|
2325
|
+
formStep: this.stepKey,
|
|
2326
|
+
message: `Lookup field "${fieldName}" not found in form "${this.stepKey}"`
|
|
2327
|
+
});
|
|
2328
|
+
const metadata = Option.getOrUndefined(getSchemaAnnotationDeep(fieldSchema, FormLookupInput));
|
|
2329
|
+
if (!metadata?.query) return new LookupFieldNotFoundError({
|
|
2330
|
+
fieldName,
|
|
2331
|
+
formStep: this.stepKey,
|
|
2332
|
+
message: `Field "${fieldName}" in form "${this.stepKey}" is not a lookup field (no query defined)`
|
|
2333
|
+
});
|
|
2334
|
+
return metadata.query(filter, limit);
|
|
2335
|
+
}
|
|
2336
|
+
_runCalendarSlotQuery(fieldName, fieldSchema) {
|
|
2337
|
+
if (!fieldSchema) return new LookupFieldNotFoundError({
|
|
2338
|
+
fieldName,
|
|
2339
|
+
formStep: this.stepKey,
|
|
2340
|
+
message: `Calendar slot field "${fieldName}" not found in form "${this.stepKey}"`
|
|
2341
|
+
});
|
|
2342
|
+
const metadata = Option.getOrUndefined(getSchemaAnnotationDeep(fieldSchema, FormCalendarSlotInput));
|
|
2343
|
+
if (!metadata?.query) return new LookupFieldNotFoundError({
|
|
2344
|
+
fieldName,
|
|
2345
|
+
formStep: this.stepKey,
|
|
2346
|
+
message: `Field "${fieldName}" in form "${this.stepKey}" is not a calendar slot field (no query defined)`
|
|
2347
|
+
});
|
|
2348
|
+
return metadata.query();
|
|
2349
|
+
}
|
|
2350
|
+
executeCalendarSlots(fieldName) {
|
|
2351
|
+
return this._runCalendarSlotQuery(fieldName, this._formFields[fieldName]);
|
|
2352
|
+
}
|
|
2353
|
+
executeCalendarSlotsWithState(fieldName, state, ctx, item) {
|
|
2354
|
+
const fields = this.getFieldsWithState(state, ctx, item);
|
|
2355
|
+
return this._runCalendarSlotQuery(fieldName, fields[fieldName]);
|
|
2356
|
+
}
|
|
2357
|
+
/**
|
|
2358
|
+
* Resolves all default values for this Form given the current process state.
|
|
2359
|
+
* Re-executes the form function with state to get fields with state-based defaults.
|
|
2360
|
+
* Returns flat defaults (wrapper fields are flattened into parent level).
|
|
2361
|
+
*
|
|
2362
|
+
* @param processState - Current process state
|
|
2363
|
+
* @param ctx - Flow context with step metadata
|
|
2364
|
+
* @param item - Optional forEach item data for per-instance context
|
|
2365
|
+
* @returns Record of field names to their resolved default values (flat)
|
|
2366
|
+
*/
|
|
2367
|
+
resolveDefaults(processState, ctx, item, currentProviderUser) {
|
|
2368
|
+
return Effect.gen(this, function* () {
|
|
2369
|
+
const defaults = this.defaults();
|
|
2370
|
+
const fieldsWithState = this.getFieldsWithState(processState, ctx, item);
|
|
2371
|
+
const resolvedDefaults = yield* this.resolveFieldDefaults(fieldsWithState, currentProviderUser);
|
|
2372
|
+
return flattenDefaults(mergeFormDefaults(defaults, resolvedDefaults), Schema.Struct(this._formFields));
|
|
2373
|
+
});
|
|
2374
|
+
}
|
|
2375
|
+
};
|
|
2376
|
+
//#endregion
|
|
2377
|
+
//#region ../process/src/lib/invitation.ts
|
|
2378
|
+
/**
|
|
2379
|
+
* An invitation for a user to join the organisation with pre-assigned roles.
|
|
2380
|
+
*
|
|
2381
|
+
* When a user signs in for the first time with a matching email address,
|
|
2382
|
+
* they will automatically be assigned the specified roles.
|
|
2383
|
+
*
|
|
2384
|
+
* @example
|
|
2385
|
+
* ```typescript
|
|
2386
|
+
* const employee = new Role(org, "Employee", { name: "Employee" })
|
|
2387
|
+
*
|
|
2388
|
+
* new Invitation(org, "admin-invite", {
|
|
2389
|
+
* email: "admin@example.com",
|
|
2390
|
+
* roles: [employee],
|
|
2391
|
+
* })
|
|
2392
|
+
* ```
|
|
2393
|
+
*/
|
|
2394
|
+
var Invitation = class extends Construct {
|
|
2395
|
+
isInvitation = true;
|
|
2396
|
+
email;
|
|
2397
|
+
roles;
|
|
2398
|
+
constructor(scope, id, props) {
|
|
2399
|
+
super(scope, id);
|
|
2400
|
+
this.email = props.email;
|
|
2401
|
+
this.roles = props.roles;
|
|
2402
|
+
}
|
|
2403
|
+
};
|
|
2404
|
+
//#endregion
|
|
2405
|
+
//#region ../process/src/lib/list.ts
|
|
2406
|
+
/**
|
|
2407
|
+
* Error thrown when executeItemQuery is called on a List without an itemQuery defined.
|
|
2408
|
+
*/
|
|
2409
|
+
var ListItemQueryNotDefinedError = class extends Data.TaggedError("ListItemQueryNotDefinedError") {
|
|
2410
|
+
get message() {
|
|
2411
|
+
return `List ${this.listPath} has no itemQuery defined`;
|
|
2412
|
+
}
|
|
2413
|
+
};
|
|
2414
|
+
/**
|
|
2415
|
+
* Error thrown when executeUpdate is called on a List without an update function defined.
|
|
2416
|
+
*/
|
|
2417
|
+
var ListItemUpdateNotDefinedError = class extends Data.TaggedError("ListItemUpdateNotDefinedError") {
|
|
2418
|
+
get message() {
|
|
2419
|
+
return `List ${this.listPath} has no update function defined`;
|
|
2420
|
+
}
|
|
2421
|
+
};
|
|
2422
|
+
/**
|
|
2423
|
+
* Error thrown when executeDelete is called on a List without a delete function defined.
|
|
2424
|
+
*/
|
|
2425
|
+
var ListItemDeleteNotDefinedError = class extends Data.TaggedError("ListItemDeleteNotDefinedError") {
|
|
2426
|
+
get message() {
|
|
2427
|
+
return `List ${this.listPath} has no delete function defined`;
|
|
2428
|
+
}
|
|
2429
|
+
};
|
|
2430
|
+
Data.TaggedError("ListCreateError");
|
|
2431
|
+
var ListCreateNotDefinedError = class extends Data.TaggedError("ListCreateNotDefinedError") {};
|
|
2432
|
+
/** Client-safe field validation error returned by a List update callback. */
|
|
2433
|
+
var ListUpdateValidationError = class extends Data.TaggedError("ListUpdateValidationError") {};
|
|
2434
|
+
/**
|
|
2435
|
+
* Column metadata for list output fields.
|
|
2436
|
+
*/
|
|
2437
|
+
const ListVisibleInList = Symbol.for("pf/list/annotation/VisibleInList");
|
|
2438
|
+
/**
|
|
2439
|
+
* Optional sortability override for list output fields. This can opt hidden
|
|
2440
|
+
* fields into API-level sorting, for example internal timestamps that should
|
|
2441
|
+
* order rows without being displayed as columns.
|
|
2442
|
+
*/
|
|
2443
|
+
const ListSortable = Symbol.for("pf/list/annotation/Sortable");
|
|
2444
|
+
const defaultSchemaDescriptions = /* @__PURE__ */ new Set([
|
|
2445
|
+
"a string",
|
|
2446
|
+
"a number",
|
|
2447
|
+
"a boolean"
|
|
2448
|
+
]);
|
|
2449
|
+
function isObjectLikeListColumnAst(ast) {
|
|
2450
|
+
switch (ast._tag) {
|
|
2451
|
+
case "TypeLiteral":
|
|
2452
|
+
case "TupleType": return true;
|
|
2453
|
+
case "Refinement": return isObjectLikeListColumnAst(ast.from);
|
|
2454
|
+
case "Transformation": return isObjectLikeListColumnAst(ast.to);
|
|
2455
|
+
case "Union": return ast.types.some((type) => isObjectLikeListColumnAst(type));
|
|
2456
|
+
default: return false;
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
function isScalarListColumnAst(ast) {
|
|
2460
|
+
switch (ast._tag) {
|
|
2461
|
+
case "StringKeyword":
|
|
2462
|
+
case "NumberKeyword":
|
|
2463
|
+
case "BooleanKeyword": return true;
|
|
2464
|
+
case "Literal": return typeof ast.literal === "string" || typeof ast.literal === "number" || typeof ast.literal === "boolean";
|
|
2465
|
+
case "Refinement": return isScalarListColumnAst(ast.from);
|
|
2466
|
+
case "Transformation": return isScalarListColumnAst(ast.from) && !isObjectLikeListColumnAst(ast.to);
|
|
2467
|
+
case "Union": {
|
|
2468
|
+
const sortableMembers = ast.types.filter((type) => !(type._tag === "Literal" && type.literal === null) && type._tag !== "UndefinedKeyword" && type._tag !== "VoidKeyword");
|
|
2469
|
+
return sortableMembers.length > 0 && sortableMembers.every((member) => isScalarListColumnAst(member));
|
|
2470
|
+
}
|
|
2471
|
+
default: return false;
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
function toListColumn(field, schema, options) {
|
|
2475
|
+
const titleAnnotation = schema.ast.annotations[SchemaAST.TitleAnnotationId];
|
|
2476
|
+
const label = typeof titleAnnotation === "string" ? titleAnnotation : String$1.capitalize(field);
|
|
2477
|
+
const visibleInList = schema.ast.annotations[ListVisibleInList] !== false;
|
|
2478
|
+
const sortableAnnotation = schema.ast.annotations[ListSortable];
|
|
2479
|
+
const sortable = options?.sortable ?? (typeof sortableAnnotation === "boolean" ? sortableAnnotation : visibleInList && isScalarListColumnAst(schema.ast));
|
|
2480
|
+
const descriptionAnnotation = schema.ast.annotations[SchemaAST.DescriptionAnnotationId];
|
|
2481
|
+
const description = typeof descriptionAnnotation === "string" && !defaultSchemaDescriptions.has(descriptionAnnotation) ? descriptionAnnotation : void 0;
|
|
2482
|
+
return description === void 0 ? {
|
|
2483
|
+
field,
|
|
2484
|
+
label,
|
|
2485
|
+
visibleInList,
|
|
2486
|
+
sortable
|
|
2487
|
+
} : {
|
|
2488
|
+
field,
|
|
2489
|
+
label,
|
|
2490
|
+
description,
|
|
2491
|
+
visibleInList,
|
|
2492
|
+
sortable
|
|
2493
|
+
};
|
|
2494
|
+
}
|
|
2495
|
+
const collectMetricBreakdownControlsFromAst = (ast) => {
|
|
2496
|
+
const metricAnnotation = SchemaAST.getAnnotation(ast, METRIC_BREAKDOWN_SYMBOL);
|
|
2497
|
+
const metricOptions = Option.getOrUndefined(metricAnnotation);
|
|
2498
|
+
const ownControls = isMetricBreakdownOptions(metricOptions) && metricOptions.dataSource === "item" ? metricOptions.controls ?? [] : [];
|
|
2499
|
+
switch (ast._tag) {
|
|
2500
|
+
case "TypeLiteral": return [...ownControls, ...ast.propertySignatures.flatMap((property) => collectMetricBreakdownControlsFromAst(property.type))];
|
|
2501
|
+
case "Refinement": return [...ownControls, ...collectMetricBreakdownControlsFromAst(ast.from)];
|
|
2502
|
+
case "Transformation": return [...ownControls, ...collectMetricBreakdownControlsFromAst(ast.to)];
|
|
2503
|
+
case "Union": return [...ownControls, ...ast.types.flatMap((type) => collectMetricBreakdownControlsFromAst(type))];
|
|
2504
|
+
default: return ownControls;
|
|
2505
|
+
}
|
|
2506
|
+
};
|
|
2507
|
+
/**
|
|
2508
|
+
* Default page size for lists.
|
|
2509
|
+
*/
|
|
2510
|
+
const DEFAULT_PAGE_SIZE = 20;
|
|
2511
|
+
/**
|
|
2512
|
+
* Maximum allowed page size for lists.
|
|
2513
|
+
*/
|
|
2514
|
+
const MAX_PAGE_SIZE = 100;
|
|
2515
|
+
function isScalarExportAst(ast) {
|
|
2516
|
+
switch (ast._tag) {
|
|
2517
|
+
case "StringKeyword":
|
|
2518
|
+
case "NumberKeyword":
|
|
2519
|
+
case "BooleanKeyword": return true;
|
|
2520
|
+
case "Literal": return ast.literal === null || typeof ast.literal === "string" || typeof ast.literal === "number" || typeof ast.literal === "boolean";
|
|
2521
|
+
case "Refinement": return isScalarExportAst(ast.from);
|
|
2522
|
+
case "Transformation": return isScalarExportAst(ast.to);
|
|
2523
|
+
case "Union": {
|
|
2524
|
+
const allowedMembers = ast.types.filter((type) => !(type._tag === "Literal" && type.literal === null) && type._tag !== "UndefinedKeyword" && type._tag !== "VoidKeyword");
|
|
2525
|
+
return allowedMembers.length > 0 && allowedMembers.every((member) => isScalarExportAst(member));
|
|
2526
|
+
}
|
|
2527
|
+
default: return false;
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
function assertScalarExportFields(listPath, fields) {
|
|
2531
|
+
for (const [field, schema] of Object.entries(fields)) if (!isScalarExportAst(schema.ast)) throw new Error(`List ${normalizePath(listPath)} export field "${field}" must be a flat scalar value (string, number, boolean, or null)`);
|
|
2532
|
+
}
|
|
2533
|
+
function assertExportFieldsHaveQuery(listPath, output, exportOutput, hasExportQuery) {
|
|
2534
|
+
if (!exportOutput || hasExportQuery) return;
|
|
2535
|
+
for (const field of Object.keys(exportOutput)) if (!(field in output)) throw new Error(`List ${normalizePath(listPath)} export field "${field}" requires exportQuery because it is not part of the normal list output`);
|
|
2536
|
+
}
|
|
2537
|
+
/**
|
|
2538
|
+
* List construct for defining paginated data queries.
|
|
2539
|
+
*
|
|
2540
|
+
* Lists are organizational-level data views that can be accessed
|
|
2541
|
+
* based on role authorization. They define:
|
|
2542
|
+
* - Output schema for type-safe item structure
|
|
2543
|
+
* - Optional filter definitions
|
|
2544
|
+
* - A query function that returns paginated results
|
|
2545
|
+
*
|
|
2546
|
+
* @example
|
|
2547
|
+
* ```typescript
|
|
2548
|
+
* const employeesList = new List(schoolUnit, "employees", {
|
|
2549
|
+
* name: "Example Employees",
|
|
2550
|
+
* purpose: "View all school employees",
|
|
2551
|
+
* roles: [adminRole],
|
|
2552
|
+
* output: {
|
|
2553
|
+
* id: ES.String,
|
|
2554
|
+
* name: ES.String,
|
|
2555
|
+
* staffNumber: ES.String,
|
|
2556
|
+
* hireDate: DateTimeUtcSchema,
|
|
2557
|
+
* },
|
|
2558
|
+
* query: (ctx) => Effect.gen(function* () {
|
|
2559
|
+
* const ops = yield* SchoolOperations
|
|
2560
|
+
* return yield* ops.queryEmployees(ctx)
|
|
2561
|
+
* }),
|
|
2562
|
+
* })
|
|
2563
|
+
* ```
|
|
2564
|
+
*/
|
|
2565
|
+
var List = class extends Construct {
|
|
2566
|
+
isList = true;
|
|
2567
|
+
_create;
|
|
2568
|
+
createFormFields;
|
|
2569
|
+
/** Display name for the list */
|
|
2570
|
+
name;
|
|
2571
|
+
/** Optional display name for a single list item detail view */
|
|
2572
|
+
detailName;
|
|
2573
|
+
/** Optional description of what this list shows */
|
|
2574
|
+
purpose;
|
|
2575
|
+
/** Roles allowed to access this list */
|
|
2576
|
+
roles;
|
|
2577
|
+
/** Output schema defining the shape of list items */
|
|
2578
|
+
output;
|
|
2579
|
+
/** Default page size */
|
|
2580
|
+
defaultPageSize;
|
|
2581
|
+
/** The query function */
|
|
2582
|
+
_query;
|
|
2583
|
+
/** Effective export schema fields */
|
|
2584
|
+
_exportOutput;
|
|
2585
|
+
/** Optional export query override */
|
|
2586
|
+
_exportQuery;
|
|
2587
|
+
/** Form schema function (optional) */
|
|
2588
|
+
_form;
|
|
2589
|
+
/** Cached form fields from calling _form() at construction */
|
|
2590
|
+
_formFields;
|
|
2591
|
+
/** Item query function (optional) */
|
|
2592
|
+
_itemQuery;
|
|
2593
|
+
/** Update function (optional) */
|
|
2594
|
+
_update;
|
|
2595
|
+
/** Delete function (optional) */
|
|
2596
|
+
_delete;
|
|
2597
|
+
/**
|
|
2598
|
+
* Create a List construct.
|
|
2599
|
+
*
|
|
2600
|
+
* @param scope - Parent OrgUnit
|
|
2601
|
+
* @param id - Unique identifier for this list within the OrgUnit
|
|
2602
|
+
* @param props - List configuration
|
|
2603
|
+
*/
|
|
2604
|
+
constructor(scope, id, props) {
|
|
2605
|
+
super(scope, id);
|
|
2606
|
+
this._create = props.create;
|
|
2607
|
+
this.createFormFields = props.create?.form();
|
|
2608
|
+
if (this.createFormFields && Object.keys(submissionSchemaSync(Schema.Struct(this.createFormFields)).fields).length === 0) throw new Error(`List ${normalizePath(this.node.path)} create form requires at least one submittable field`);
|
|
2609
|
+
this.name = props.name;
|
|
2610
|
+
if (props.detailName !== void 0) this.detailName = props.detailName;
|
|
2611
|
+
if (props.purpose !== void 0) this.purpose = props.purpose;
|
|
2612
|
+
if (props.roles.length === 0) throw new Error(`List ${normalizePath(this.node.path)} requires at least one role`);
|
|
2613
|
+
this.roles = props.roles;
|
|
2614
|
+
this.output = props.output;
|
|
2615
|
+
this.defaultPageSize = Math.min(props.defaultPageSize ?? 20, 100);
|
|
2616
|
+
this._query = props.query;
|
|
2617
|
+
if (props.exportOutput) assertScalarExportFields(this.node.path, props.exportOutput);
|
|
2618
|
+
assertExportFieldsHaveQuery(this.node.path, props.output, props.exportOutput, props.exportQuery !== void 0);
|
|
2619
|
+
this._exportOutput = props.exportOutput ?? props.output;
|
|
2620
|
+
this._exportQuery = props.exportQuery;
|
|
2621
|
+
if (props.form) {
|
|
2622
|
+
this._form = props.form;
|
|
2623
|
+
this._formFields = props.form();
|
|
2624
|
+
}
|
|
2625
|
+
if (props.itemQuery) this._itemQuery = props.itemQuery;
|
|
2626
|
+
if (props.update) this._update = props.update;
|
|
2627
|
+
if (props.delete) this._delete = props.delete;
|
|
2628
|
+
}
|
|
2629
|
+
get hasCreate() {
|
|
2630
|
+
return this._create !== void 0;
|
|
2631
|
+
}
|
|
2632
|
+
createMutationName() {
|
|
2633
|
+
return `createListItem${pathToPascalCase(this.node.path)}`;
|
|
2634
|
+
}
|
|
2635
|
+
createInputTypeName() {
|
|
2636
|
+
return `Create${pathToPascalCase(this.node.path)}`;
|
|
2637
|
+
}
|
|
2638
|
+
createSubmissionSchema() {
|
|
2639
|
+
return this.createFormFields ? submissionSchemaSync(Schema.Struct(this.createFormFields)) : null;
|
|
2640
|
+
}
|
|
2641
|
+
createFormMetadata(currentProviderUser) {
|
|
2642
|
+
if (!this.createFormFields) return Effect.succeed(null);
|
|
2643
|
+
const fields = this.createFormFields;
|
|
2644
|
+
const submission = submissionSchemaSync(Schema.Struct(fields));
|
|
2645
|
+
const createMutationName = this.createMutationName();
|
|
2646
|
+
const createInputTypeName = this.createInputTypeName();
|
|
2647
|
+
return Effect.gen(function* () {
|
|
2648
|
+
const components = yield* asClientRepresentation(Schema.Struct(fields));
|
|
2649
|
+
const defaults = yield* resolveFormFieldDefaults(fields, currentProviderUser);
|
|
2650
|
+
return {
|
|
2651
|
+
formDefinition: {
|
|
2652
|
+
components,
|
|
2653
|
+
rules: []
|
|
2654
|
+
},
|
|
2655
|
+
defaultValues: mergeFormDefaults(getSchemaDefaults(fields), defaults),
|
|
2656
|
+
jsonSchema: JSONSchema.make(submission),
|
|
2657
|
+
createMutationName,
|
|
2658
|
+
createInputTypeName
|
|
2659
|
+
};
|
|
2660
|
+
});
|
|
2661
|
+
}
|
|
2662
|
+
executeCreate(input) {
|
|
2663
|
+
if (!this._create) return Effect.fail(new ListCreateNotDefinedError({ listPath: this.node.path }));
|
|
2664
|
+
return this._create.submit(input);
|
|
2665
|
+
}
|
|
2666
|
+
/**
|
|
2667
|
+
* Get the GraphQL query name for this list.
|
|
2668
|
+
* Format: "list" + PascalCase path (e.g., "listSchoolEmployees")
|
|
2669
|
+
*
|
|
2670
|
+
* Uses pathToPascalCase to ensure valid GraphQL identifiers even
|
|
2671
|
+
* with paths containing hyphens, numbers, or special characters.
|
|
2672
|
+
*/
|
|
2673
|
+
queryName() {
|
|
2674
|
+
return `list${pathToPascalCase(this.node.path)}`;
|
|
2675
|
+
}
|
|
2676
|
+
/**
|
|
2677
|
+
* Execute the list query with the given context.
|
|
2678
|
+
*
|
|
2679
|
+
* @param ctx - Query context with pagination and optional filter text
|
|
2680
|
+
* @returns Effect producing the query result
|
|
2681
|
+
*/
|
|
2682
|
+
executeQuery(ctx) {
|
|
2683
|
+
return this._query(ctx);
|
|
2684
|
+
}
|
|
2685
|
+
/**
|
|
2686
|
+
* Get the parent OrgUnit of this list.
|
|
2687
|
+
*/
|
|
2688
|
+
get orgUnit() {
|
|
2689
|
+
return this.node.scope;
|
|
2690
|
+
}
|
|
2691
|
+
/**
|
|
2692
|
+
* Get the field names from the output schema.
|
|
2693
|
+
* Used to build GraphQL queries with the correct subfield selection.
|
|
2694
|
+
*/
|
|
2695
|
+
outputFieldNames() {
|
|
2696
|
+
return Object.keys(this.output);
|
|
2697
|
+
}
|
|
2698
|
+
/**
|
|
2699
|
+
* Get column metadata from the output schema.
|
|
2700
|
+
* Extracts field names, labels, and visibility metadata from schema annotations.
|
|
2701
|
+
*/
|
|
2702
|
+
outputColumns() {
|
|
2703
|
+
return Object.entries(this.output).map(([field, schema]) => toListColumn(field, schema));
|
|
2704
|
+
}
|
|
2705
|
+
/**
|
|
2706
|
+
* Get the field names from the effective export schema.
|
|
2707
|
+
*/
|
|
2708
|
+
exportFieldNames() {
|
|
2709
|
+
return Object.keys(this._exportOutput);
|
|
2710
|
+
}
|
|
2711
|
+
/**
|
|
2712
|
+
* Get column metadata from the effective export schema.
|
|
2713
|
+
*/
|
|
2714
|
+
exportColumns() {
|
|
2715
|
+
return Object.entries(this._exportOutput).map(([field, schema]) => toListColumn(field, schema));
|
|
2716
|
+
}
|
|
2717
|
+
/**
|
|
2718
|
+
* Execute the effective export query.
|
|
2719
|
+
*/
|
|
2720
|
+
executeExportQuery(ctx) {
|
|
2721
|
+
return this._exportQuery ? this._exportQuery(ctx) : this._query(ctx);
|
|
2722
|
+
}
|
|
2723
|
+
/**
|
|
2724
|
+
* Check if this list has a detail form defined.
|
|
2725
|
+
*/
|
|
2726
|
+
get hasForm() {
|
|
2727
|
+
return this._form !== void 0;
|
|
2728
|
+
}
|
|
2729
|
+
/**
|
|
2730
|
+
* Get the cached form fields.
|
|
2731
|
+
* Returns undefined if no form is defined.
|
|
2732
|
+
*/
|
|
2733
|
+
get formFields() {
|
|
2734
|
+
return this._formFields;
|
|
2735
|
+
}
|
|
2736
|
+
/**
|
|
2737
|
+
* Get the GraphQL query name for fetching a single item's detail.
|
|
2738
|
+
* Format: "listItem" + PascalCase path (e.g., "listItemSchoolEmployees")
|
|
2739
|
+
*/
|
|
2740
|
+
itemQueryName() {
|
|
2741
|
+
return `listItem${pathToPascalCase(this.node.path)}`;
|
|
2742
|
+
}
|
|
2743
|
+
/**
|
|
2744
|
+
* Execute the item query to fetch a single item by ID.
|
|
2745
|
+
* Fails with ListItemQueryNotDefinedError if no itemQuery is defined.
|
|
2746
|
+
*
|
|
2747
|
+
* @param id - The ID of the item to fetch
|
|
2748
|
+
* @returns Effect producing the item or null
|
|
2749
|
+
*/
|
|
2750
|
+
executeItemQuery(id, ctx = {}) {
|
|
2751
|
+
if (!this._itemQuery) return Effect.fail(new ListItemQueryNotDefinedError({ listPath: this.node.path }));
|
|
2752
|
+
return this._itemQuery(id, ctx);
|
|
2753
|
+
}
|
|
2754
|
+
/**
|
|
2755
|
+
* Get declared generic controls that can be passed to the item query.
|
|
2756
|
+
*/
|
|
2757
|
+
itemQueryControls() {
|
|
2758
|
+
if (!this._formFields) return [];
|
|
2759
|
+
const controls = Object.values(this._formFields).flatMap((schema) => collectMetricBreakdownControlsFromAst(schema.ast));
|
|
2760
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2761
|
+
return controls.filter((control) => {
|
|
2762
|
+
if (seen.has(control.name)) return false;
|
|
2763
|
+
seen.add(control.name);
|
|
2764
|
+
return true;
|
|
2765
|
+
});
|
|
2766
|
+
}
|
|
2767
|
+
/**
|
|
2768
|
+
* Get the field names from the form schema.
|
|
2769
|
+
* Returns empty array if no form is defined.
|
|
2770
|
+
*/
|
|
2771
|
+
formFieldNames() {
|
|
2772
|
+
return this._formFields ? Object.keys(this._formFields) : [];
|
|
2773
|
+
}
|
|
2774
|
+
/**
|
|
2775
|
+
* Get column metadata from the form schema.
|
|
2776
|
+
* Returns empty array if no form is defined.
|
|
2777
|
+
*/
|
|
2778
|
+
formColumns() {
|
|
2779
|
+
if (!this._formFields) return [];
|
|
2780
|
+
return Object.entries(this._formFields).map(([field, schema]) => toListColumn(field, schema, { sortable: false }));
|
|
2781
|
+
}
|
|
2782
|
+
/**
|
|
2783
|
+
* Generate the browser-safe form definition for the form fields.
|
|
2784
|
+
* List forms do not currently support dynamic rules, so the canonical rule
|
|
2785
|
+
* channel is always an empty array.
|
|
2786
|
+
* Returns null if no form is defined.
|
|
2787
|
+
*/
|
|
2788
|
+
clientFormDefinition() {
|
|
2789
|
+
if (!this._formFields) return Effect.succeed(null);
|
|
2790
|
+
const effectSchema = Schema.Struct(this._formFields);
|
|
2791
|
+
return asClientRepresentation(effectSchema).pipe(Effect.map((components) => ({
|
|
2792
|
+
components,
|
|
2793
|
+
rules: []
|
|
2794
|
+
})));
|
|
2795
|
+
}
|
|
2796
|
+
/**
|
|
2797
|
+
* Generate JSON Schema for the form's submittable fields.
|
|
2798
|
+
* Strips read-only and structural-only fields; removes additionalProperties.
|
|
2799
|
+
* Returns null if no form is defined.
|
|
2800
|
+
*/
|
|
2801
|
+
formSubmissionSchema() {
|
|
2802
|
+
if (!this._formFields) return null;
|
|
2803
|
+
const effectSchema = Schema.Struct(this.editableFormFields());
|
|
2804
|
+
const submission = submissionSchemaSync(effectSchema);
|
|
2805
|
+
const { additionalProperties: _, ...schema } = JSONSchema.make(submission);
|
|
2806
|
+
return schema;
|
|
2807
|
+
}
|
|
2808
|
+
/**
|
|
2809
|
+
* Get default values for the form fields.
|
|
2810
|
+
* Returns null if no form is defined.
|
|
2811
|
+
*/
|
|
2812
|
+
formDefaults() {
|
|
2813
|
+
if (!this._formFields) return null;
|
|
2814
|
+
return getSchemaDefaults(this._formFields);
|
|
2815
|
+
}
|
|
2816
|
+
/**
|
|
2817
|
+
* Check if this list has an update function defined.
|
|
2818
|
+
*/
|
|
2819
|
+
get hasUpdate() {
|
|
2820
|
+
return this._update !== void 0;
|
|
2821
|
+
}
|
|
2822
|
+
/**
|
|
2823
|
+
* Check if this list has a delete function defined.
|
|
2824
|
+
*/
|
|
2825
|
+
get hasDelete() {
|
|
2826
|
+
return this._delete !== void 0;
|
|
2827
|
+
}
|
|
2828
|
+
/**
|
|
2829
|
+
* Get the GraphQL mutation name for updating a list item.
|
|
2830
|
+
* Format: "updateListItem" + PascalCase path (e.g., "updateListItemSchoolEmployees")
|
|
2831
|
+
*/
|
|
2832
|
+
updateMutationName() {
|
|
2833
|
+
return `updateListItem${pathToPascalCase(this.node.path)}`;
|
|
2834
|
+
}
|
|
2835
|
+
/**
|
|
2836
|
+
* Get the GraphQL mutation name for deleting a list item.
|
|
2837
|
+
* Format: "deleteListItem" + PascalCase path (e.g., "deleteListItemSchoolEmployees")
|
|
2838
|
+
*/
|
|
2839
|
+
deleteMutationName() {
|
|
2840
|
+
return `deleteListItem${pathToPascalCase(this.node.path)}`;
|
|
2841
|
+
}
|
|
2842
|
+
/**
|
|
2843
|
+
* Get the GraphQL input type name for list item updates.
|
|
2844
|
+
* Format: "Update" + PascalCase path (e.g., "UpdateSchoolEmployees")
|
|
2845
|
+
*/
|
|
2846
|
+
updateInputTypeName() {
|
|
2847
|
+
return `Update${pathToPascalCase(this.node.path)}`;
|
|
2848
|
+
}
|
|
2849
|
+
/**
|
|
2850
|
+
* Execute the update function to update a single item by ID.
|
|
2851
|
+
* Fails with ListItemUpdateNotDefinedError if no update function is defined,
|
|
2852
|
+
* or ListUpdateValidationError if server-side validation rejects the input.
|
|
2853
|
+
*
|
|
2854
|
+
* @param id - The ID of the item to update
|
|
2855
|
+
* @param input - The fields to update (flattened submission schema)
|
|
2856
|
+
* @returns Effect producing the updated item or null
|
|
2857
|
+
*/
|
|
2858
|
+
executeUpdate(id, input) {
|
|
2859
|
+
if (!this._update) return Effect.fail(new ListItemUpdateNotDefinedError({ listPath: this.node.path }));
|
|
2860
|
+
return this._update(id, input);
|
|
2861
|
+
}
|
|
2862
|
+
/**
|
|
2863
|
+
* Execute the delete function to delete a single item by ID.
|
|
2864
|
+
* Fails with ListItemDeleteNotDefinedError if no delete function is defined.
|
|
2865
|
+
*
|
|
2866
|
+
* @param id - The ID of the item to delete
|
|
2867
|
+
* @returns Effect producing void on success
|
|
2868
|
+
*/
|
|
2869
|
+
executeDelete(id) {
|
|
2870
|
+
if (!this._delete) return Effect.fail(new ListItemDeleteNotDefinedError({ listPath: this.node.path }));
|
|
2871
|
+
return this._delete(id);
|
|
2872
|
+
}
|
|
2873
|
+
/**
|
|
2874
|
+
* Filter form field entries to only those NOT annotated FormReadOnly=true.
|
|
2875
|
+
*/
|
|
2876
|
+
editableFormFieldEntries() {
|
|
2877
|
+
if (!this._formFields) return [];
|
|
2878
|
+
return Object.entries(this._formFields).filter(([, schema]) => !isReadOnlyField(schema));
|
|
2879
|
+
}
|
|
2880
|
+
/**
|
|
2881
|
+
* Get editable form fields as a record (excludes FormReadOnly fields).
|
|
2882
|
+
* Useful for schema generation where the full field schemas are needed.
|
|
2883
|
+
*/
|
|
2884
|
+
editableFormFields() {
|
|
2885
|
+
return Object.fromEntries(this.editableFormFieldEntries());
|
|
2886
|
+
}
|
|
2887
|
+
/**
|
|
2888
|
+
* Get column metadata for editable form fields only.
|
|
2889
|
+
* Returns columns for fields NOT annotated with FormReadOnly.
|
|
2890
|
+
*/
|
|
2891
|
+
editableFormColumns() {
|
|
2892
|
+
return this.editableFormFieldEntries().map(([field, schema]) => toListColumn(field, schema, { sortable: false }));
|
|
2893
|
+
}
|
|
2894
|
+
/**
|
|
2895
|
+
* Get a URL-safe slug derived from the list name.
|
|
2896
|
+
* Used for generating unique object keys for CSV exports.
|
|
2897
|
+
*/
|
|
2898
|
+
slugName() {
|
|
2899
|
+
return this.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
2900
|
+
}
|
|
2901
|
+
/**
|
|
2902
|
+
* Get the list path in normalized form (with leading slash).
|
|
2903
|
+
*/
|
|
2904
|
+
normalizedPath() {
|
|
2905
|
+
return normalizePath(this.node.path);
|
|
2906
|
+
}
|
|
2907
|
+
};
|
|
2908
|
+
//#endregion
|
|
2909
|
+
//#region ../process/src/lib/node_step.ts
|
|
2910
|
+
/**
|
|
2911
|
+
* NodeStep is a concrete implementation of SystemStep that takes execute as a prop.
|
|
2912
|
+
*
|
|
2913
|
+
* This is the most common way to create system steps - you provide the execute
|
|
2914
|
+
* function directly as a prop rather than subclassing SystemStep.
|
|
2915
|
+
*
|
|
2916
|
+
* @typeParam TState - Accumulated state from previous steps
|
|
2917
|
+
* @typeParam TSteps - Record of completed step metadata for ctx.step access
|
|
2918
|
+
* @typeParam TInput - Input derived from state
|
|
2919
|
+
* @typeParam TOutput - Output schema fields merged into process state
|
|
2920
|
+
* @typeParam TId - Step identifier literal type
|
|
2921
|
+
* @typeParam TIsForEach - Whether this step uses forEach semantics
|
|
2922
|
+
*
|
|
2923
|
+
* @example
|
|
2924
|
+
* ```typescript
|
|
2925
|
+
* const greet = new NodeStep(register, "Greet", {
|
|
2926
|
+
* input: (state) => Effect.succeed({ name: state.name }),
|
|
2927
|
+
* output: {},
|
|
2928
|
+
* execute: (input) => Effect.gen(function* () {
|
|
2929
|
+
* console.log(`Hello ${input.name}`)
|
|
2930
|
+
* }),
|
|
2931
|
+
* })
|
|
2932
|
+
*
|
|
2933
|
+
* this.start(register).next(greet).end()
|
|
2934
|
+
* ```
|
|
2935
|
+
*/
|
|
2936
|
+
var NodeStep = class extends SystemStep {
|
|
2937
|
+
/**
|
|
2938
|
+
* The execute function provided as a prop.
|
|
2939
|
+
*/
|
|
2940
|
+
_executeFn;
|
|
2941
|
+
constructor(scope, id, props) {
|
|
2942
|
+
super(scope, id, props);
|
|
2943
|
+
this._executeFn = props.execute;
|
|
2944
|
+
}
|
|
2945
|
+
/**
|
|
2946
|
+
* Execute the step logic with the derived input.
|
|
2947
|
+
* Delegates to the execute prop.
|
|
2948
|
+
*
|
|
2949
|
+
* The returned Effect may have requirements (services) and tagged domain
|
|
2950
|
+
* errors that are propagated when the step is executed by the
|
|
2951
|
+
* SystemStepExecutor.
|
|
2952
|
+
*/
|
|
2953
|
+
execute(input) {
|
|
2954
|
+
return this._executeFn(input);
|
|
2955
|
+
}
|
|
2956
|
+
};
|
|
2957
|
+
//#endregion
|
|
2958
|
+
//#region ../process/src/lib/org-unit.ts
|
|
2959
|
+
/**
|
|
2960
|
+
* Represents an organizational unit within the hierarchy.
|
|
2961
|
+
*
|
|
2962
|
+
* Organizational units form a strict tree hierarchy where each unit
|
|
2963
|
+
* has exactly one parent (except the root Organisation). They provide
|
|
2964
|
+
* scoping for processes and roles.
|
|
2965
|
+
*
|
|
2966
|
+
* Note: The type "organisation" is reserved for the root Organisation
|
|
2967
|
+
* class and cannot be used when creating regular OrgUnit instances.
|
|
2968
|
+
*
|
|
2969
|
+
* @example
|
|
2970
|
+
* ```typescript
|
|
2971
|
+
* const org = new Organisation({ name: "Acme Corp" })
|
|
2972
|
+
* const board = new OrgUnit(org, "board", {
|
|
2973
|
+
* name: "Board of Directors",
|
|
2974
|
+
* type: "board"
|
|
2975
|
+
* })
|
|
2976
|
+
*
|
|
2977
|
+
* const finance = new OrgUnit(board, "finance", {
|
|
2978
|
+
* name: "Finance Department",
|
|
2979
|
+
* type: "department"
|
|
2980
|
+
* })
|
|
2981
|
+
* ```
|
|
2982
|
+
*/
|
|
2983
|
+
var OrgUnit = class extends Construct {
|
|
2984
|
+
isOrgUnit = true;
|
|
2985
|
+
name;
|
|
2986
|
+
type;
|
|
2987
|
+
acronym;
|
|
2988
|
+
constructor(scope, id, props) {
|
|
2989
|
+
if (props.type === "organisation" && scope !== null) throw new Error("Cannot create OrgUnit with type 'organisation'. Use Organisation class instead.");
|
|
2990
|
+
super(scope, id);
|
|
2991
|
+
this.name = props.name;
|
|
2992
|
+
if (props.type !== void 0) this.type = props.type;
|
|
2993
|
+
if (props.acronym !== void 0) this.acronym = props.acronym;
|
|
2994
|
+
}
|
|
2995
|
+
};
|
|
2996
|
+
//#endregion
|
|
2997
|
+
//#region ../process/src/lib/process.ts
|
|
2998
|
+
var Process = class Process extends Construct {
|
|
2999
|
+
static START_NODE = "__start__";
|
|
3000
|
+
static END_NODE = "__end__";
|
|
3001
|
+
isProcess = true;
|
|
3002
|
+
/**
|
|
3003
|
+
* Returns true if the node ID is a virtual node (__start__ or __end__).
|
|
3004
|
+
*/
|
|
3005
|
+
static isVirtualNode(nodeId) {
|
|
3006
|
+
return nodeId === Process.START_NODE || nodeId === Process.END_NODE;
|
|
3007
|
+
}
|
|
3008
|
+
graph;
|
|
3009
|
+
/**
|
|
3010
|
+
* Reference to this Process instance, allowing Process to be used
|
|
3011
|
+
* as a scope when creating Steps.
|
|
3012
|
+
*/
|
|
3013
|
+
process;
|
|
3014
|
+
props;
|
|
3015
|
+
orgUnit;
|
|
3016
|
+
constructor(scope, id, props) {
|
|
3017
|
+
super(scope, id);
|
|
3018
|
+
this.graph = new DirectedGraph({
|
|
3019
|
+
multi: true,
|
|
3020
|
+
type: "directed"
|
|
3021
|
+
});
|
|
3022
|
+
this.graph.addNode(Process.START_NODE);
|
|
3023
|
+
this.graph.addNode(Process.END_NODE);
|
|
3024
|
+
this.process = this;
|
|
3025
|
+
this.props = props;
|
|
3026
|
+
this.orgUnit = scope;
|
|
3027
|
+
if (props.responsibilities) {
|
|
3028
|
+
const rolePaths = /* @__PURE__ */ new Set();
|
|
3029
|
+
for (const resp of props.responsibilities) {
|
|
3030
|
+
const rolePath = resp.role.node.path;
|
|
3031
|
+
if (rolePaths.has(rolePath)) throw new Error(`Duplicate role "${resp.role.name}" in responsibilities for process "${props.name}"`);
|
|
3032
|
+
rolePaths.add(rolePath);
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
/**
|
|
3037
|
+
* Returns the GraphQL mutation name for starting this process.
|
|
3038
|
+
* Example: "engineering/bug-report-fix" -> "startEngineeringBugReportFix"
|
|
3039
|
+
*/
|
|
3040
|
+
startMutationName() {
|
|
3041
|
+
return `start${pathToPascalCase(this.node.path)}`;
|
|
3042
|
+
}
|
|
3043
|
+
start(initialStep) {
|
|
3044
|
+
this.graph.addDirectedEdge(Process.START_NODE, initialStep.node.path);
|
|
3045
|
+
return wrapInFlowPath(initialStep, this);
|
|
3046
|
+
}
|
|
3047
|
+
addEndEdge(step) {
|
|
3048
|
+
const stepPath = step.node.path;
|
|
3049
|
+
if (this.graph.hasDirectedEdge(stepPath, Process.END_NODE)) throw new Error(`Step "${stepPath}" already has .end() called`);
|
|
3050
|
+
this.graph.addDirectedEdge(stepPath, Process.END_NODE);
|
|
3051
|
+
}
|
|
3052
|
+
/**
|
|
3053
|
+
* Adds an else edge to the __end__ node.
|
|
3054
|
+
* This is followed ONLY if NO conditional edges from the step match.
|
|
3055
|
+
*/
|
|
3056
|
+
addElseEndEdge(step) {
|
|
3057
|
+
const stepPath = step.node.path;
|
|
3058
|
+
const existingEdges = this.graph.outEdges(stepPath) ?? [];
|
|
3059
|
+
for (const edge of existingEdges) if (this.graph.target(edge) === Process.END_NODE) {
|
|
3060
|
+
if (this.graph.getEdgeAttributes(edge).isElse) throw new Error(`Step "${stepPath}" already has .elseEnd() called`);
|
|
3061
|
+
}
|
|
3062
|
+
this.graph.addDirectedEdge(stepPath, Process.END_NODE, { isElse: true });
|
|
3063
|
+
}
|
|
3064
|
+
/**
|
|
3065
|
+
* Validates process flows and returns problematic step paths.
|
|
3066
|
+
* Checks for:
|
|
3067
|
+
* - Dangling steps: no outgoing edges (missing .end())
|
|
3068
|
+
* - Unreachable steps: not reachable from start
|
|
3069
|
+
* - Missing else branches: steps with conditional edges but no else branch
|
|
3070
|
+
* - Multiple else branches: steps with more than one else edge
|
|
3071
|
+
* - Orphan else branches: steps with else edge but no conditional edges
|
|
3072
|
+
*
|
|
3073
|
+
* @returns Object with separate arrays for unreachable, dangling, missingElse, multipleElse, and orphanElse steps
|
|
3074
|
+
*/
|
|
3075
|
+
validateFlows() {
|
|
3076
|
+
const reachable = /* @__PURE__ */ new Set();
|
|
3077
|
+
const queue = [Process.START_NODE];
|
|
3078
|
+
while (queue.length > 0) {
|
|
3079
|
+
const nodeId = queue.pop();
|
|
3080
|
+
if (nodeId === void 0 || reachable.has(nodeId)) continue;
|
|
3081
|
+
reachable.add(nodeId);
|
|
3082
|
+
for (const neighbor of this.graph.outNeighbors(nodeId)) queue.push(neighbor);
|
|
3083
|
+
}
|
|
3084
|
+
const unreachable = [];
|
|
3085
|
+
const dangling = [];
|
|
3086
|
+
const missingElse = [];
|
|
3087
|
+
const multipleElse = [];
|
|
3088
|
+
const orphanElse = [];
|
|
3089
|
+
for (const nodeId of this.realNodes()) if (!reachable.has(nodeId)) unreachable.push(nodeId);
|
|
3090
|
+
else if (this.graph.outDegree(nodeId) === 0) dangling.push(nodeId);
|
|
3091
|
+
else {
|
|
3092
|
+
const outEdges = this.graph.outEdges(nodeId) ?? [];
|
|
3093
|
+
let hasConditional = false;
|
|
3094
|
+
let elseCount = 0;
|
|
3095
|
+
for (const edge of outEdges) {
|
|
3096
|
+
const attrs = this.graph.getEdgeAttributes(edge);
|
|
3097
|
+
if (attrs.condition) hasConditional = true;
|
|
3098
|
+
if (attrs.isElse) elseCount++;
|
|
3099
|
+
}
|
|
3100
|
+
if (hasConditional) {
|
|
3101
|
+
if (elseCount === 0) missingElse.push(nodeId);
|
|
3102
|
+
else if (elseCount > 1) multipleElse.push(nodeId);
|
|
3103
|
+
} else if (elseCount > 0) orphanElse.push(nodeId);
|
|
3104
|
+
}
|
|
3105
|
+
return {
|
|
3106
|
+
unreachable,
|
|
3107
|
+
dangling,
|
|
3108
|
+
missingElse,
|
|
3109
|
+
multipleElse,
|
|
3110
|
+
orphanElse
|
|
3111
|
+
};
|
|
3112
|
+
}
|
|
3113
|
+
/**
|
|
3114
|
+
* Returns steps connected from __start__ (hides graph implementation).
|
|
3115
|
+
* @returns Array of start steps for this process
|
|
3116
|
+
*/
|
|
3117
|
+
startNodes() {
|
|
3118
|
+
return this.graph.outNeighbors(Process.START_NODE).map((nodeId) => this.graph.getNodeAttributes(nodeId));
|
|
3119
|
+
}
|
|
3120
|
+
getGraph() {
|
|
3121
|
+
return this.graph;
|
|
3122
|
+
}
|
|
3123
|
+
/**
|
|
3124
|
+
* Returns all real (non-virtual) node IDs in the process graph.
|
|
3125
|
+
* Filters out __start__ and __end__ nodes.
|
|
3126
|
+
*/
|
|
3127
|
+
realNodes() {
|
|
3128
|
+
return this.graph.nodes().filter((id) => !Process.isVirtualNode(id));
|
|
3129
|
+
}
|
|
3130
|
+
addNode(step) {
|
|
3131
|
+
const id = step.node.path;
|
|
3132
|
+
if (!this.graph.hasNode(id)) this.graph.addNode(id, step);
|
|
3133
|
+
}
|
|
3134
|
+
addEdge(source, dest, attributes) {
|
|
3135
|
+
const source_id = source.node.path;
|
|
3136
|
+
const dest_id = dest.node.path;
|
|
3137
|
+
const existingParallelEdges = (this.graph.outEdges(source_id) ?? []).filter((edge) => this.graph.target(edge) === dest_id);
|
|
3138
|
+
if (attributes?.isOnError !== true && existingParallelEdges.some((edge) => this.graph.getEdgeAttributes(edge).isOnError !== true)) throw new Error(`Flow from "${source_id}" to "${dest_id}" already exists`);
|
|
3139
|
+
this.graph.addDirectedEdge(source_id, dest_id, attributes);
|
|
3140
|
+
}
|
|
3141
|
+
/** Get all Form steps in this process. */
|
|
3142
|
+
forms() {
|
|
3143
|
+
const result = [];
|
|
3144
|
+
for (const nodeId of this.graph.nodes()) {
|
|
3145
|
+
const step = this.graph.getNodeAttributes(nodeId);
|
|
3146
|
+
if (isForm(step)) result.push({
|
|
3147
|
+
form: step,
|
|
3148
|
+
path: nodeId
|
|
3149
|
+
});
|
|
3150
|
+
}
|
|
3151
|
+
return result;
|
|
3152
|
+
}
|
|
3153
|
+
};
|
|
3154
|
+
//#endregion
|
|
3155
|
+
//#region ../process/src/lib/organisation.ts
|
|
3156
|
+
/**
|
|
3157
|
+
* Set of valid IANA timezone identifiers.
|
|
3158
|
+
* Cached for performance.
|
|
3159
|
+
* Note: "UTC" is valid for Intl.DateTimeFormat but not in supportedValuesOf,
|
|
3160
|
+
* so we add it explicitly.
|
|
3161
|
+
*/
|
|
3162
|
+
const validTimeZones = /* @__PURE__ */ new Set([...Intl.supportedValuesOf("timeZone"), "UTC"]);
|
|
3163
|
+
/**
|
|
3164
|
+
* Validates that a string is a valid IANA timezone identifier.
|
|
3165
|
+
* @throws Error if timezone is invalid
|
|
3166
|
+
*/
|
|
3167
|
+
const validateTimeZone = (timeZone) => {
|
|
3168
|
+
if (!validTimeZones.has(timeZone)) throw new Error(`Invalid timezone: "${timeZone}". Must be a valid IANA timezone identifier (e.g., "Europe/Amsterdam", "America/New_York").`);
|
|
3169
|
+
};
|
|
3170
|
+
/**
|
|
3171
|
+
* Represents the root organizational unit.
|
|
3172
|
+
*
|
|
3173
|
+
* Organisation extends OrgUnit and is automatically assigned type "organisation".
|
|
3174
|
+
* It serves as the root of the organizational hierarchy tree.
|
|
3175
|
+
*
|
|
3176
|
+
* @example
|
|
3177
|
+
* ```typescript
|
|
3178
|
+
* const org = new Organisation({
|
|
3179
|
+
* name: "Acme Corp",
|
|
3180
|
+
* timeZone: "Europe/Amsterdam"
|
|
3181
|
+
* })
|
|
3182
|
+
* const hr = new OrgUnit(org, "hr", {
|
|
3183
|
+
* name: "Human Resources",
|
|
3184
|
+
* type: "department"
|
|
3185
|
+
* })
|
|
3186
|
+
* ```
|
|
3187
|
+
*/
|
|
3188
|
+
var Organisation = class extends OrgUnit {
|
|
3189
|
+
isOrganisation = true;
|
|
3190
|
+
/**
|
|
3191
|
+
* IANA timezone identifier (e.g., "Europe/Amsterdam", "America/New_York").
|
|
3192
|
+
*/
|
|
3193
|
+
timeZone;
|
|
3194
|
+
/**
|
|
3195
|
+
* BCP 47 locale used for organisation-authored date/time display.
|
|
3196
|
+
*/
|
|
3197
|
+
locale;
|
|
3198
|
+
/**
|
|
3199
|
+
* Business calendar configuration for the organisation.
|
|
3200
|
+
* Defines working hours, holidays, and special periods.
|
|
3201
|
+
*/
|
|
3202
|
+
businessCalendar;
|
|
3203
|
+
constructor(props) {
|
|
3204
|
+
const timeZone = props.timeZone ?? "UTC";
|
|
3205
|
+
validateTimeZone(timeZone);
|
|
3206
|
+
super(null, "", {
|
|
3207
|
+
name: props.name,
|
|
3208
|
+
type: "organisation",
|
|
3209
|
+
...props.acronym !== void 0 && { acronym: props.acronym }
|
|
3210
|
+
});
|
|
3211
|
+
this.timeZone = timeZone;
|
|
3212
|
+
this.locale = props.locale ?? "en";
|
|
3213
|
+
this.businessCalendar = props.businessCalendar;
|
|
3214
|
+
}
|
|
3215
|
+
/**
|
|
3216
|
+
* Find a step by its path relative to the organisation root.
|
|
3217
|
+
* Path format: "orgUnit/processName/stepName"
|
|
3218
|
+
*
|
|
3219
|
+
* @param stepPath - Path like "engineering/bug-report-fix/Report bug"
|
|
3220
|
+
* @returns The Step if found, otherwise undefined
|
|
3221
|
+
*
|
|
3222
|
+
* @example
|
|
3223
|
+
* ```ts
|
|
3224
|
+
* const step = org.stepByPath("engineering/bug-report-fix/Report bug")
|
|
3225
|
+
* if (step) {
|
|
3226
|
+
* // Handle step
|
|
3227
|
+
* }
|
|
3228
|
+
* ```
|
|
3229
|
+
*/
|
|
3230
|
+
stepByPath(stepPath) {
|
|
3231
|
+
const segments = stepPath.split("/").filter((segment) => segment.length > 0);
|
|
3232
|
+
let currentNode = this;
|
|
3233
|
+
for (const segment of segments) try {
|
|
3234
|
+
currentNode = currentNode.node.findChild(segment);
|
|
3235
|
+
} catch {
|
|
3236
|
+
return;
|
|
3237
|
+
}
|
|
3238
|
+
return isStep(currentNode) ? currentNode : void 0;
|
|
3239
|
+
}
|
|
3240
|
+
/**
|
|
3241
|
+
* Find a Form step by its path relative to the organisation root.
|
|
3242
|
+
* Returns undefined if the path doesn't exist or points to a non-Form step.
|
|
3243
|
+
*
|
|
3244
|
+
* @param stepPath - Path like "engineering/bug-report-fix/Report bug"
|
|
3245
|
+
* @returns The Form if found, otherwise undefined
|
|
3246
|
+
*/
|
|
3247
|
+
formByPath(stepPath) {
|
|
3248
|
+
const step = this.stepByPath(stepPath);
|
|
3249
|
+
return isForm(step) ? step : void 0;
|
|
3250
|
+
}
|
|
3251
|
+
/**
|
|
3252
|
+
* Recursively collects all processes from this organisation.
|
|
3253
|
+
*
|
|
3254
|
+
* @returns Array of all Process instances in the organisation tree
|
|
3255
|
+
*/
|
|
3256
|
+
processes() {
|
|
3257
|
+
const result = [];
|
|
3258
|
+
const stack = [this];
|
|
3259
|
+
while (stack.length > 0) {
|
|
3260
|
+
const current = stack.pop();
|
|
3261
|
+
if (current) {
|
|
3262
|
+
for (const child of current.node.children) if (isOrgUnit(child)) stack.push(child);
|
|
3263
|
+
else if (isProcess(child)) result.push(child);
|
|
3264
|
+
}
|
|
3265
|
+
}
|
|
3266
|
+
return result;
|
|
3267
|
+
}
|
|
3268
|
+
/**
|
|
3269
|
+
* Recursively collects all lists from this organisation.
|
|
3270
|
+
*
|
|
3271
|
+
* @returns Array of all List instances in the organisation tree
|
|
3272
|
+
*/
|
|
3273
|
+
lists() {
|
|
3274
|
+
const result = [];
|
|
3275
|
+
const stack = [this];
|
|
3276
|
+
while (stack.length > 0) {
|
|
3277
|
+
const current = stack.pop();
|
|
3278
|
+
if (current) {
|
|
3279
|
+
for (const child of current.node.children) if (isOrgUnit(child)) stack.push(child);
|
|
3280
|
+
else if (isList(child)) result.push(child);
|
|
3281
|
+
}
|
|
3282
|
+
}
|
|
3283
|
+
return result;
|
|
3284
|
+
}
|
|
3285
|
+
/**
|
|
3286
|
+
* Recursively collects all document stores from this organisation.
|
|
3287
|
+
*
|
|
3288
|
+
* @returns Array of all DocumentStore instances in the organisation tree
|
|
3289
|
+
*/
|
|
3290
|
+
documentStores() {
|
|
3291
|
+
const result = [];
|
|
3292
|
+
const stack = [this];
|
|
3293
|
+
while (stack.length > 0) {
|
|
3294
|
+
const current = stack.pop();
|
|
3295
|
+
if (current) {
|
|
3296
|
+
for (const child of current.node.children) if (isOrgUnit(child)) stack.push(child);
|
|
3297
|
+
else if (isDocumentStore(child)) result.push(child);
|
|
3298
|
+
}
|
|
3299
|
+
}
|
|
3300
|
+
return result;
|
|
3301
|
+
}
|
|
3302
|
+
/**
|
|
3303
|
+
* Recursively collects all stats views from this organisation.
|
|
3304
|
+
*
|
|
3305
|
+
* @returns Array of all StatsView instances in the organisation tree
|
|
3306
|
+
*/
|
|
3307
|
+
statsViews() {
|
|
3308
|
+
const result = [];
|
|
3309
|
+
const stack = [this];
|
|
3310
|
+
while (stack.length > 0) {
|
|
3311
|
+
const current = stack.pop();
|
|
3312
|
+
if (current) {
|
|
3313
|
+
for (const child of current.node.children) if (isOrgUnit(child)) stack.push(child);
|
|
3314
|
+
else if (isStatsView(child)) result.push(child);
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
return result;
|
|
3318
|
+
}
|
|
3319
|
+
/**
|
|
3320
|
+
* Find a List by its path relative to the organisation root.
|
|
3321
|
+
* Path format: "orgUnit/listName" (e.g., "school/employees")
|
|
3322
|
+
*
|
|
3323
|
+
* @param listPath - Path to the list
|
|
3324
|
+
* @returns The List if found, otherwise undefined
|
|
3325
|
+
*
|
|
3326
|
+
* @example
|
|
3327
|
+
* ```ts
|
|
3328
|
+
* const list = org.listByPath("school/employees")
|
|
3329
|
+
* if (list) {
|
|
3330
|
+
* // Use the list
|
|
3331
|
+
* }
|
|
3332
|
+
* ```
|
|
3333
|
+
*/
|
|
3334
|
+
listByPath(listPath) {
|
|
3335
|
+
const segments = listPath.split("/").filter((segment) => segment.length > 0);
|
|
3336
|
+
let currentNode = this;
|
|
3337
|
+
for (const segment of segments) try {
|
|
3338
|
+
currentNode = currentNode.node.findChild(segment);
|
|
3339
|
+
} catch {
|
|
3340
|
+
return;
|
|
3341
|
+
}
|
|
3342
|
+
return isList(currentNode) ? currentNode : void 0;
|
|
3343
|
+
}
|
|
3344
|
+
/**
|
|
3345
|
+
* Returns true if the node ID is the virtual end node (__end__).
|
|
3346
|
+
* Used when walking process graphs to skip the end node.
|
|
3347
|
+
*/
|
|
3348
|
+
isEndNode(nodeId) {
|
|
3349
|
+
return nodeId === Process.END_NODE;
|
|
3350
|
+
}
|
|
3351
|
+
/**
|
|
3352
|
+
* Validates all process flows in the organisation.
|
|
3353
|
+
* A flow is valid if all non-virtual nodes are reachable and have an edge to the end node.
|
|
3354
|
+
*
|
|
3355
|
+
* @returns Array of validation errors with process path and problem details
|
|
3356
|
+
*/
|
|
3357
|
+
validateAllFlows() {
|
|
3358
|
+
const results = [];
|
|
3359
|
+
for (const process of this.processes()) {
|
|
3360
|
+
const { unreachable, dangling, missingElse, multipleElse, orphanElse } = process.validateFlows();
|
|
3361
|
+
if (unreachable.length > 0 || dangling.length > 0 || missingElse.length > 0 || multipleElse.length > 0 || orphanElse.length > 0) results.push({
|
|
3362
|
+
processPath: process.node.path,
|
|
3363
|
+
unreachable,
|
|
3364
|
+
dangling,
|
|
3365
|
+
missingElse,
|
|
3366
|
+
multipleElse,
|
|
3367
|
+
orphanElse
|
|
3368
|
+
});
|
|
3369
|
+
}
|
|
3370
|
+
return results;
|
|
3371
|
+
}
|
|
3372
|
+
};
|
|
3373
|
+
//#endregion
|
|
3374
|
+
//#region ../process/src/lib/phase.ts
|
|
3375
|
+
/**
|
|
3376
|
+
* Represents a phase in a process. Steps can be assigned a phase, and
|
|
3377
|
+
* will be visually indicates as being part of the given phase in a
|
|
3378
|
+
* swimlane.
|
|
3379
|
+
*
|
|
3380
|
+
*/
|
|
3381
|
+
var Phase = class extends Construct {
|
|
3382
|
+
name;
|
|
3383
|
+
orgUnit;
|
|
3384
|
+
constructor(scope, id, props) {
|
|
3385
|
+
super(scope, id);
|
|
3386
|
+
this.name = props ? props.name : id;
|
|
3387
|
+
this.orgUnit = scope;
|
|
3388
|
+
}
|
|
3389
|
+
};
|
|
3390
|
+
//#endregion
|
|
3391
|
+
//#region ../process/src/lib/public-form-branding.ts
|
|
3392
|
+
var PublicFormBranding = class extends Construct {
|
|
3393
|
+
isPublicFormBranding = true;
|
|
3394
|
+
headerHtml;
|
|
3395
|
+
footerHtml;
|
|
3396
|
+
constructor(scope, id, props) {
|
|
3397
|
+
super(scope, id);
|
|
3398
|
+
const headerHtml = normalizeSnippet(props.headerHtml);
|
|
3399
|
+
const footerHtml = normalizeSnippet(props.footerHtml);
|
|
3400
|
+
if (headerHtml === void 0 && footerHtml === void 0) throw new Error(`PublicFormBranding "${id}" must declare headerHtml or footerHtml`);
|
|
3401
|
+
this.headerHtml = headerHtml;
|
|
3402
|
+
this.footerHtml = footerHtml;
|
|
3403
|
+
}
|
|
3404
|
+
};
|
|
3405
|
+
const normalizeSnippet = (html) => {
|
|
3406
|
+
if (html === void 0 || html.trim().length === 0) return;
|
|
3407
|
+
return html;
|
|
3408
|
+
};
|
|
3409
|
+
//#endregion
|
|
3410
|
+
//#region ../process/src/lib/role.ts
|
|
3411
|
+
/**
|
|
3412
|
+
* Represents a role within an organizational unit.
|
|
3413
|
+
*
|
|
3414
|
+
* Roles are scoped to specific organizational units and define
|
|
3415
|
+
* who (human or system) can execute steps in a process.
|
|
3416
|
+
*
|
|
3417
|
+
* @example
|
|
3418
|
+
* ```typescript
|
|
3419
|
+
* const finance = new OrgUnit(org, "finance", {
|
|
3420
|
+
* name: "Finance Department",
|
|
3421
|
+
* type: "department"
|
|
3422
|
+
* })
|
|
3423
|
+
*
|
|
3424
|
+
* const accountant = new Role(finance, "accountant", {
|
|
3425
|
+
* name: "Accountant"
|
|
3426
|
+
* })
|
|
3427
|
+
* ```
|
|
3428
|
+
*/
|
|
3429
|
+
var Role = class extends Construct {
|
|
3430
|
+
isRole = true;
|
|
3431
|
+
name;
|
|
3432
|
+
orgUnit;
|
|
3433
|
+
constructor(scope, id, props) {
|
|
3434
|
+
super(scope, id);
|
|
3435
|
+
this.name = props ? props.name : id;
|
|
3436
|
+
this.orgUnit = scope;
|
|
3437
|
+
}
|
|
3438
|
+
};
|
|
3439
|
+
//#endregion
|
|
3440
|
+
//#region ../process/src/lib/schedule.ts
|
|
3441
|
+
/**
|
|
3442
|
+
* Schedule types for business-calendar-aware scheduling.
|
|
3443
|
+
*
|
|
3444
|
+
* Schedule functions in `flow.next()` can return either:
|
|
3445
|
+
* - A raw `DateTime.DateTime` (backward compatible, wall-clock time)
|
|
3446
|
+
* - A marker type from this module that gets resolved at execution time
|
|
3447
|
+
*
|
|
3448
|
+
* Business-time markers are resolved in the job-handler using the
|
|
3449
|
+
* BusinessCalendarService from `processfocus/business-calendar`.
|
|
3450
|
+
*
|
|
3451
|
+
* @example
|
|
3452
|
+
* ```typescript
|
|
3453
|
+
* import { Schedule } from "processfocus/process"
|
|
3454
|
+
*
|
|
3455
|
+
* flow.next(reviewStep, {
|
|
3456
|
+
* schedule: {
|
|
3457
|
+
* fn: (_state, ctx) => Schedule.businessHours(
|
|
3458
|
+
* ctx.step.submitRequest.completedAt,
|
|
3459
|
+
* 1 // 1 business hour
|
|
3460
|
+
* ),
|
|
3461
|
+
* text: "1 business hour after submission",
|
|
3462
|
+
* },
|
|
3463
|
+
* })
|
|
3464
|
+
*
|
|
3465
|
+
* // Also available:
|
|
3466
|
+
* // Schedule.businessDays(from, days) - business days
|
|
3467
|
+
* // Schedule.clockTime(from, duration) - explicit wall-clock time
|
|
3468
|
+
* ```
|
|
3469
|
+
*/
|
|
3470
|
+
/**
|
|
3471
|
+
* Schedule helper functions for creating schedule marker types.
|
|
3472
|
+
*
|
|
3473
|
+
* @example
|
|
3474
|
+
* ```typescript
|
|
3475
|
+
* import { Schedule } from "processfocus/process"
|
|
3476
|
+
* import { Duration } from "effect"
|
|
3477
|
+
*
|
|
3478
|
+
* // Schedule 2 business hours after step completion
|
|
3479
|
+
* Schedule.businessHours(ctx.step.submitRequest.completedAt, 2)
|
|
3480
|
+
*
|
|
3481
|
+
* // Schedule 3 business days after step completion
|
|
3482
|
+
* Schedule.businessDays(ctx.step.submitRequest.completedAt, 3)
|
|
3483
|
+
*
|
|
3484
|
+
* // Explicit clock time (for when you want wall-clock, not business time)
|
|
3485
|
+
* Schedule.clockTime(ctx.step.submitRequest.completedAt, "1 hour")
|
|
3486
|
+
* Schedule.clockTime(ctx.step.submitRequest.completedAt, Duration.hours(1))
|
|
3487
|
+
* ```
|
|
3488
|
+
*/
|
|
3489
|
+
const Schedule = {
|
|
3490
|
+
/**
|
|
3491
|
+
* Create a business minutes schedule marker.
|
|
3492
|
+
*
|
|
3493
|
+
* @param from - Starting datetime
|
|
3494
|
+
* @param minutes - Number of business minutes to add
|
|
3495
|
+
* @returns A BusinessMinutesSchedule marker resolved at execution time
|
|
3496
|
+
*/
|
|
3497
|
+
businessMinutes(from, minutes) {
|
|
3498
|
+
if (minutes < 0) throw new Error(`Schedule.businessMinutes: minutes must be non-negative, got ${minutes}`);
|
|
3499
|
+
return {
|
|
3500
|
+
_tag: "BusinessMinutes",
|
|
3501
|
+
from,
|
|
3502
|
+
minutes
|
|
3503
|
+
};
|
|
3504
|
+
},
|
|
3505
|
+
/**
|
|
3506
|
+
* Create a business hours schedule marker.
|
|
3507
|
+
*
|
|
3508
|
+
* @param from - Starting datetime
|
|
3509
|
+
* @param hours - Number of business hours to add (can be fractional, e.g., 1.5)
|
|
3510
|
+
* @returns A BusinessHoursSchedule marker resolved at execution time
|
|
3511
|
+
*/
|
|
3512
|
+
businessHours(from, hours) {
|
|
3513
|
+
if (hours < 0) throw new Error(`Schedule.businessHours: hours must be non-negative, got ${hours}`);
|
|
3514
|
+
return {
|
|
3515
|
+
_tag: "BusinessHours",
|
|
3516
|
+
from,
|
|
3517
|
+
hours
|
|
3518
|
+
};
|
|
3519
|
+
},
|
|
3520
|
+
/**
|
|
3521
|
+
* Create a business days schedule marker.
|
|
3522
|
+
*
|
|
3523
|
+
* @param from - Starting datetime
|
|
3524
|
+
* @param days - Number of business days to add
|
|
3525
|
+
* @returns A BusinessDaysSchedule marker resolved at execution time
|
|
3526
|
+
*/
|
|
3527
|
+
businessDays(from, days) {
|
|
3528
|
+
if (days < 0) throw new Error(`Schedule.businessDays: days must be non-negative, got ${days}`);
|
|
3529
|
+
return {
|
|
3530
|
+
_tag: "BusinessDays",
|
|
3531
|
+
from,
|
|
3532
|
+
days
|
|
3533
|
+
};
|
|
3534
|
+
},
|
|
3535
|
+
/**
|
|
3536
|
+
* Create a clock time schedule marker.
|
|
3537
|
+
*
|
|
3538
|
+
* Unlike returning a raw DateTime (which bypasses resolution entirely),
|
|
3539
|
+
* this returns a marker that explicitly signals clock-time semantics
|
|
3540
|
+
* during resolution. Use this when you want to clearly indicate that
|
|
3541
|
+
* a schedule should use wall-clock time, not business time.
|
|
3542
|
+
*
|
|
3543
|
+
* @param from - Starting datetime
|
|
3544
|
+
* @param duration - Duration to add (DurationInput accepts string like "1 hour")
|
|
3545
|
+
* @returns A ClockTimeSchedule marker resolved at execution time
|
|
3546
|
+
*/
|
|
3547
|
+
clockTime(from, duration) {
|
|
3548
|
+
return {
|
|
3549
|
+
_tag: "ClockTime",
|
|
3550
|
+
from,
|
|
3551
|
+
duration: Duration.decode(duration)
|
|
3552
|
+
};
|
|
3553
|
+
},
|
|
3554
|
+
/**
|
|
3555
|
+
* Create a from-point schedule marker.
|
|
3556
|
+
*
|
|
3557
|
+
* Computes a calendar offset from a reference date and snaps the result to
|
|
3558
|
+
* the nearest business day/hours. The snap direction matches the offset sign:
|
|
3559
|
+
* negative offsets snap backward, positive snap forward.
|
|
3560
|
+
*
|
|
3561
|
+
* Edge case: Zero offset on a non-business day (weekend/holiday) snaps forward
|
|
3562
|
+
* to the next business day, ensuring the schedule always lands on a valid
|
|
3563
|
+
* business day.
|
|
3564
|
+
*
|
|
3565
|
+
* @example
|
|
3566
|
+
* ```typescript
|
|
3567
|
+
* // Schedule 1 week before start date
|
|
3568
|
+
* Schedule.fromPoint(state.start_date, { days: -7 })
|
|
3569
|
+
* // If Feb 17 - 7 days = Feb 10 (closed), snaps backward to Feb 9
|
|
3570
|
+
*
|
|
3571
|
+
* // Schedule on the reference date itself
|
|
3572
|
+
* Schedule.fromPoint(state.start_date, { days: 0 })
|
|
3573
|
+
* // If start_date is Saturday, snaps to following Monday
|
|
3574
|
+
* ```
|
|
3575
|
+
*
|
|
3576
|
+
* @param from - Starting datetime (reference point)
|
|
3577
|
+
* @param offset - Calendar offset to apply (can have negative values). Zero on non-business days snaps forward.
|
|
3578
|
+
* @returns A FromPointSchedule marker resolved at execution time
|
|
3579
|
+
*/
|
|
3580
|
+
fromPoint(from, offset) {
|
|
3581
|
+
return {
|
|
3582
|
+
_tag: "FromPoint",
|
|
3583
|
+
from,
|
|
3584
|
+
offset
|
|
3585
|
+
};
|
|
3586
|
+
},
|
|
3587
|
+
/**
|
|
3588
|
+
* Type guard to check if a value is a schedule marker (not a raw DateTime).
|
|
3589
|
+
*
|
|
3590
|
+
* @param value - Value to check
|
|
3591
|
+
* @returns True if value is a ScheduleMarker
|
|
3592
|
+
*/
|
|
3593
|
+
isScheduleMarker(value) {
|
|
3594
|
+
return typeof value === "object" && value !== null && "_tag" in value && (value._tag === "BusinessMinutes" || value._tag === "BusinessHours" || value._tag === "BusinessDays" || value._tag === "ClockTime" || value._tag === "FromPoint");
|
|
3595
|
+
},
|
|
3596
|
+
/**
|
|
3597
|
+
* Pattern match on a ScheduleMarker, similar to Effect's Option.match/Either.match.
|
|
3598
|
+
*
|
|
3599
|
+
* @param marker - The schedule marker to match on
|
|
3600
|
+
* @param handlers - Object with handler functions for each marker type
|
|
3601
|
+
* @returns The result of the matching handler
|
|
3602
|
+
*
|
|
3603
|
+
* @example
|
|
3604
|
+
* ```typescript
|
|
3605
|
+
* Schedule.match(marker, {
|
|
3606
|
+
* onBusinessMinutes: (m) => `${m.minutes} business minutes`,
|
|
3607
|
+
* onBusinessHours: (m) => `${m.hours} business hours`,
|
|
3608
|
+
* onBusinessDays: (m) => `${m.days} business days`,
|
|
3609
|
+
* onClockTime: (m) => `clock time duration`,
|
|
3610
|
+
* onFromPoint: (m) => `from ${m.from} with offset`,
|
|
3611
|
+
* })
|
|
3612
|
+
* ```
|
|
3613
|
+
*/
|
|
3614
|
+
match(marker, handlers) {
|
|
3615
|
+
switch (marker._tag) {
|
|
3616
|
+
case "BusinessMinutes": return handlers.onBusinessMinutes(marker);
|
|
3617
|
+
case "BusinessHours": return handlers.onBusinessHours(marker);
|
|
3618
|
+
case "BusinessDays": return handlers.onBusinessDays(marker);
|
|
3619
|
+
case "ClockTime": return handlers.onClockTime(marker);
|
|
3620
|
+
case "FromPoint": return handlers.onFromPoint(marker);
|
|
3621
|
+
}
|
|
3622
|
+
}
|
|
3623
|
+
};
|
|
3624
|
+
//#endregion
|
|
3625
|
+
//#region ../process/src/lib/sla.ts
|
|
3626
|
+
const DEFAULT_WARNING_AT = .8;
|
|
3627
|
+
/**
|
|
3628
|
+
* Validates SLA options and returns the warning percentage (0-100).
|
|
3629
|
+
*/
|
|
3630
|
+
const validateAndGetWarning = (options) => {
|
|
3631
|
+
const warningAt = options?.warningAt ?? DEFAULT_WARNING_AT;
|
|
3632
|
+
if (warningAt < 0 || warningAt > 1) throw new Error(`SLA warningAt must be between 0 and 1, got ${warningAt}`);
|
|
3633
|
+
return Math.round(warningAt * 100);
|
|
3634
|
+
};
|
|
3635
|
+
/**
|
|
3636
|
+
* Validates that the duration value is a positive integer.
|
|
3637
|
+
*/
|
|
3638
|
+
const validateDuration = (value, unit) => {
|
|
3639
|
+
if (!Number.isInteger(value) || value <= 0) throw new Error(`SLA ${unit} value must be a positive integer, got ${value}`);
|
|
3640
|
+
};
|
|
3641
|
+
/**
|
|
3642
|
+
* SLA helper functions for creating SLA configurations.
|
|
3643
|
+
*
|
|
3644
|
+
* @example
|
|
3645
|
+
* ```typescript
|
|
3646
|
+
* import { Sla } from "processfocus/process"
|
|
3647
|
+
*
|
|
3648
|
+
* // Duration units (integer values only)
|
|
3649
|
+
* sla: Sla.businessHours(4) // 4 business hours
|
|
3650
|
+
* sla: Sla.businessDays(5) // 5 business days
|
|
3651
|
+
* sla: Sla.businessWeeks(2) // 2 business weeks (10 days)
|
|
3652
|
+
*
|
|
3653
|
+
* // With warning threshold (optional)
|
|
3654
|
+
* sla: Sla.businessDays(5, { warningAt: 0.8 }) // warn at 80% (4 days elapsed)
|
|
3655
|
+
* ```
|
|
3656
|
+
*/
|
|
3657
|
+
const Sla = {
|
|
3658
|
+
/**
|
|
3659
|
+
* Creates an SLA configuration with a duration in minutes.
|
|
3660
|
+
* Note: Minutes are clock time, not business calendar time.
|
|
3661
|
+
*
|
|
3662
|
+
* @param minutes - Number of minutes (positive integer)
|
|
3663
|
+
* @param options - Optional configuration (warningAt)
|
|
3664
|
+
*/
|
|
3665
|
+
minutes(minutes, options) {
|
|
3666
|
+
validateDuration(minutes, "minutes");
|
|
3667
|
+
return {
|
|
3668
|
+
value: minutes,
|
|
3669
|
+
unit: "minutes",
|
|
3670
|
+
warningAt: validateAndGetWarning(options)
|
|
3671
|
+
};
|
|
3672
|
+
},
|
|
3673
|
+
/**
|
|
3674
|
+
* Creates an SLA configuration with a duration in business hours.
|
|
3675
|
+
*
|
|
3676
|
+
* @param hours - Number of business hours (positive integer)
|
|
3677
|
+
* @param options - Optional configuration (warningAt)
|
|
3678
|
+
*/
|
|
3679
|
+
businessHours(hours, options) {
|
|
3680
|
+
validateDuration(hours, "businessHours");
|
|
3681
|
+
return {
|
|
3682
|
+
value: hours,
|
|
3683
|
+
unit: "businessHours",
|
|
3684
|
+
warningAt: validateAndGetWarning(options)
|
|
3685
|
+
};
|
|
3686
|
+
},
|
|
3687
|
+
/**
|
|
3688
|
+
* Creates an SLA configuration with a duration in business days.
|
|
3689
|
+
*
|
|
3690
|
+
* @param days - Number of business days (positive integer)
|
|
3691
|
+
* @param options - Optional configuration (warningAt)
|
|
3692
|
+
*/
|
|
3693
|
+
businessDays(days, options) {
|
|
3694
|
+
validateDuration(days, "businessDays");
|
|
3695
|
+
return {
|
|
3696
|
+
value: days,
|
|
3697
|
+
unit: "businessDays",
|
|
3698
|
+
warningAt: validateAndGetWarning(options)
|
|
3699
|
+
};
|
|
3700
|
+
},
|
|
3701
|
+
/**
|
|
3702
|
+
* Creates an SLA configuration with a duration in business weeks.
|
|
3703
|
+
* A business week is 5 business days.
|
|
3704
|
+
*
|
|
3705
|
+
* @param weeks - Number of business weeks (positive integer)
|
|
3706
|
+
* @param options - Optional configuration (warningAt)
|
|
3707
|
+
*/
|
|
3708
|
+
businessWeeks(weeks, options) {
|
|
3709
|
+
validateDuration(weeks, "businessWeeks");
|
|
3710
|
+
return {
|
|
3711
|
+
value: weeks,
|
|
3712
|
+
unit: "businessWeeks",
|
|
3713
|
+
warningAt: validateAndGetWarning(options)
|
|
3714
|
+
};
|
|
3715
|
+
}
|
|
3716
|
+
};
|
|
3717
|
+
//#endregion
|
|
3718
|
+
//#region ../process/src/lib/stats-view.ts
|
|
3719
|
+
/**
|
|
3720
|
+
* Stats view construct for defining custom analytics/visualization screens.
|
|
3721
|
+
*
|
|
3722
|
+
* StatsViews are organizational-level custom data views that provide
|
|
3723
|
+
* visualizations beyond the standard list/table model. They are:
|
|
3724
|
+
* - Discovered by the frontend via the `availableStatsViews` GraphQL query
|
|
3725
|
+
* - Rendered at `/stats/<path>` in the frontend
|
|
3726
|
+
* - Backed by a custom GraphQL query from the org's `CustomGraphqlSchema`
|
|
3727
|
+
*
|
|
3728
|
+
* Unlike `List`, StatsView does not generate its own GraphQL schema —
|
|
3729
|
+
* the org is responsible for providing the query via `CustomGraphqlSchema`.
|
|
3730
|
+
* StatsView only carries metadata (name, renderer type, query name, roles)
|
|
3731
|
+
* that the frontend uses to discover and render the view.
|
|
3732
|
+
*
|
|
3733
|
+
* @example
|
|
3734
|
+
* ```typescript
|
|
3735
|
+
* new StatsView(org, "enrolment-journeys", {
|
|
3736
|
+
* name: "Enrolment Journeys",
|
|
3737
|
+
* purpose: "See how quickly enrolments move through the pipeline",
|
|
3738
|
+
* roles: [officeStaff],
|
|
3739
|
+
* renderer: "timeline",
|
|
3740
|
+
* queryName: "timelineAllEnrolmentEnquiries",
|
|
3741
|
+
* })
|
|
3742
|
+
* ```
|
|
3743
|
+
*/
|
|
3744
|
+
var StatsView = class extends Construct {
|
|
3745
|
+
isStatsView = true;
|
|
3746
|
+
/** Display name for the stats view */
|
|
3747
|
+
name;
|
|
3748
|
+
/** Optional description of what this stats view shows */
|
|
3749
|
+
purpose;
|
|
3750
|
+
/** Roles allowed to access this stats view */
|
|
3751
|
+
roles;
|
|
3752
|
+
/** Built-in renderer type the frontend should use */
|
|
3753
|
+
renderer;
|
|
3754
|
+
/** GraphQL query name that returns the stats data */
|
|
3755
|
+
queryName;
|
|
3756
|
+
constructor(scope, id, props) {
|
|
3757
|
+
super(scope, id);
|
|
3758
|
+
this.name = props.name;
|
|
3759
|
+
if (props.purpose !== void 0) this.purpose = props.purpose;
|
|
3760
|
+
if (props.roles.length === 0) throw new Error(`StatsView ${normalizePath(this.node.path)} requires at least one role`);
|
|
3761
|
+
this.roles = props.roles;
|
|
3762
|
+
this.renderer = props.renderer;
|
|
3763
|
+
this.queryName = props.queryName;
|
|
3764
|
+
}
|
|
3765
|
+
};
|
|
3766
|
+
Data.TaggedError("StepNotFoundError");
|
|
3767
|
+
Data.TaggedError("NotASystemStepError");
|
|
3768
|
+
Data.TaggedError("SystemStepExecutionError");
|
|
3769
|
+
Data.TaggedError("OutputValidationError");
|
|
3770
|
+
Data.TaggedError("LongDurationDispatchError");
|
|
3771
|
+
Context.Tag("processfocus/process/LongDurationDispatcher")();
|
|
3772
|
+
/**
|
|
3773
|
+
* Optional service that lets system steps read their process state at
|
|
3774
|
+
* execution time. Used by deferred steps to check idempotency guards
|
|
3775
|
+
* (e.g. has this Resend email already been sent on a previous retry?).
|
|
3776
|
+
*/
|
|
3777
|
+
var StepProcessStateReader = class extends Context.Tag("processfocus/process/StepProcessStateReader")() {};
|
|
3778
|
+
Context.Tag("processfocus/process/SystemStepExecutor")();
|
|
3779
|
+
//#endregion
|
|
3780
|
+
export { AppIcons, AppleOAuthProviderConfigSchema, AuthenticationConfig, CognitoOAuthProviderConfigSchema, CurrentStepJobContext, CustomEntitiesConfig, DEFAULT_OAUTH_PROVIDER_SCOPES, DEFAULT_PAGE_SIZE, DocumentStore, ElseBranch, ExecutionFailureNotifications, FlowPath, Form, FormRuleSelf, GoogleOAuthProviderConfigSchema, Invitation, KeycloakOAuthProviderConfigSchema, List, ListSortable, ListUpdateValidationError, ListVisibleInList, LookupAccessor, LookupBuilder, LookupFieldNotFoundError, MAX_PAGE_SIZE, MicrosoftOAuthProviderConfigSchema, NodeStep, OAUTH_PROVIDER_NAMES, OAuthProviderConfigSchema, OAuthProviderNameSchema, OrgUnit, Organisation, PasskeyProviderConfigSchema, Phase, PoliciesConfig, Process, PublicFormBranding, Role, Schedule, SecretClientConfigSchema, Sla, SlackOAuthProviderConfigSchema, StatsView, Step, StepProcessStateReader, SystemStep, coerceAuthorTaggedError, isAuthenticationConfig, isAuthorTaggedError, isCustomEntitiesConfig, isDocumentStore, isForm, isInvitation, isList, isNonRetryableAuthorError, isOrgUnit, isOrganisation, isPoliciesConfig, isProcess, isRole, isStatsView, isStep };
|