@magmonium/cli 0.8.30 → 0.10.1

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.
@@ -0,0 +1,2331 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // apps/m-one-ui/src/app/pages/design/lib/gesture-catalog.ts
21
+ var gesture_catalog_exports = {};
22
+ __export(gesture_catalog_exports, {
23
+ GESTURES: () => GESTURES,
24
+ applyGesture: () => applyGesture,
25
+ functionBodyCheckFor: () => functionBodyCheckFor,
26
+ gestureByName: () => gestureByName,
27
+ runBatch: () => runBatch,
28
+ runGesture: () => runGesture,
29
+ setFunctionBodyCheck: () => setFunctionBodyCheck
30
+ });
31
+ module.exports = __toCommonJS(gesture_catalog_exports);
32
+
33
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/gesture-context.ts
34
+ var import_codegen = require("./index.js");
35
+ var gestureContextOf = (source) => {
36
+ const byId = new Map(source.screens.map((slot) => [slot.meta.id, slot]));
37
+ return {
38
+ source,
39
+ screenOf: (screenId) => byId.get(screenId),
40
+ controlMapOf: (screenId) => byId.get(screenId)?.state.controlMap
41
+ };
42
+ };
43
+ var NO_FEATURE = (0, import_codegen.emptyFeature)("", "");
44
+ var screenScopeOf = (source, slot) => {
45
+ const feature = (0, import_codegen.isFeatureScreen)(slot.meta) ? source.features[slot.meta.featureId] : void 0;
46
+ const functionsInScope = { ...source.functions, ...feature?.functions ?? {} };
47
+ const shapes = feature ? { ...source.sharedShapes, ...feature.shapes } : Object.values(source.features).reduce(
48
+ (acc, one) => ({ ...acc, ...one.shapes }),
49
+ { ...source.sharedShapes }
50
+ );
51
+ const readable = (0, import_codegen.readableMembers)(feature ?? NO_FEATURE, import_codegen.MAIN_STORE_OWNER);
52
+ return {
53
+ meta: {
54
+ ...slot.meta,
55
+ variables: (0, import_codegen.withVariableEnums)(slot.meta.variables ?? {}, slot.state.controlMap)
56
+ },
57
+ feature,
58
+ functionsInScope,
59
+ shapes,
60
+ pathRoots: (0, import_codegen.propertiesWithComputeds)(
61
+ readable.properties,
62
+ readable.computeds,
63
+ functionsInScope
64
+ )
65
+ };
66
+ };
67
+
68
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/control-gestures.ts
69
+ var import_codegen3 = require("./index.js");
70
+
71
+ // apps/m-one-ui/src/app/pages/design/lib/move-helper.ts
72
+ var import_codegen2 = require("./index.js");
73
+ function applyMove(controlMap, rootControlIds, sourceId, targetId, position) {
74
+ if (sourceId === targetId) return null;
75
+ const updatedControlMap = { ...controlMap };
76
+ const sourceControl = updatedControlMap[sourceId];
77
+ if (!sourceControl) return null;
78
+ if ((0, import_codegen2.isDescendant)(sourceId, targetId, updatedControlMap)) return null;
79
+ const oldParentId = sourceControl.parentId;
80
+ let updatedRootControlIds = [...rootControlIds];
81
+ if (!oldParentId) {
82
+ updatedRootControlIds = updatedRootControlIds.filter(
83
+ (id) => id !== sourceId
84
+ );
85
+ } else {
86
+ const oldParent = updatedControlMap[oldParentId];
87
+ if (oldParent?.childrens) {
88
+ updatedControlMap[oldParentId] = {
89
+ ...oldParent,
90
+ childrens: oldParent.childrens.filter((id) => id !== sourceId)
91
+ };
92
+ }
93
+ }
94
+ if (position === "inside") {
95
+ const targetParent = updatedControlMap[targetId];
96
+ if (!targetParent || !(0, import_codegen2.canPlaceChild)(targetParent, sourceControl.type, updatedControlMap)) {
97
+ return null;
98
+ }
99
+ updatedControlMap[sourceId] = { ...sourceControl, parentId: targetId };
100
+ updatedControlMap[targetId] = {
101
+ ...targetParent,
102
+ childrens: [...targetParent.childrens ?? [], sourceId]
103
+ };
104
+ return {
105
+ controlMap: updatedControlMap,
106
+ rootControlIds: updatedRootControlIds
107
+ };
108
+ }
109
+ const targetControl = updatedControlMap[targetId];
110
+ const newParentId = targetControl?.parentId;
111
+ const newParent = newParentId ? updatedControlMap[newParentId] : void 0;
112
+ if (!(0, import_codegen2.canPlaceChild)(newParent, sourceControl.type, updatedControlMap)) {
113
+ return null;
114
+ }
115
+ updatedControlMap[sourceId] = { ...sourceControl, parentId: newParentId };
116
+ const insertBesideTarget = (ids) => {
117
+ const next = [...ids];
118
+ const index = next.indexOf(targetId);
119
+ if (index === -1) {
120
+ next.push(sourceId);
121
+ } else {
122
+ next.splice(position === "before" ? index : index + 1, 0, sourceId);
123
+ }
124
+ return next;
125
+ };
126
+ if (!newParentId) {
127
+ updatedRootControlIds = insertBesideTarget(updatedRootControlIds);
128
+ } else if (newParent) {
129
+ updatedControlMap[newParentId] = {
130
+ ...newParent,
131
+ childrens: insertBesideTarget(newParent.childrens ?? [])
132
+ };
133
+ }
134
+ return {
135
+ controlMap: updatedControlMap,
136
+ rootControlIds: updatedRootControlIds
137
+ };
138
+ }
139
+ function movePatch(result, sourceId) {
140
+ const controlMap = (0, import_codegen2.rebaseSubtree)(result.controlMap, sourceId);
141
+ return {
142
+ controlMap,
143
+ rootControlIds: result.rootControlIds,
144
+ selectedControl: sourceId,
145
+ selectedLayerId: (0, import_codegen2.getControlLayer)(sourceId, controlMap)
146
+ };
147
+ }
148
+ function siblingNeighbour(controlMap, rootControlIds, id, direction) {
149
+ const control = controlMap[id];
150
+ if (!control) return void 0;
151
+ const siblings = control.parentId ? controlMap[control.parentId]?.childrens ?? [] : rootControlIds;
152
+ const index = siblings.indexOf(id);
153
+ if (index === -1) return void 0;
154
+ return direction === "up" ? siblings[index - 1] : siblings[index + 1];
155
+ }
156
+
157
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/control-gestures.ts
158
+ var SCORE_SET_SEED = [
159
+ { key: "score", label: "score", value: 74, primary: true },
160
+ { key: "momentum", label: "momentum", value: 88 },
161
+ { key: "volume", label: "volume", value: 41 }
162
+ ];
163
+ function addControlTree(input) {
164
+ const { type, parentId, genId: genId2 } = input;
165
+ const currentMap = input.controlMap;
166
+ const seeded = [];
167
+ const targetParent = parentId ? currentMap[parentId] : void 0;
168
+ if (parentId && !targetParent) return { refusal: "parent-missing", seeded };
169
+ if (!(0, import_codegen3.canPlaceChild)(targetParent, type, currentMap))
170
+ return { refusal: "placement-refused", seeded };
171
+ if (type === import_codegen3.ControlType.ROUTER_OUTLET && (!(0, import_codegen3.isRoutableKind)(input.screenKind) || (0, import_codegen3.hasRouterOutlet)(currentMap))) {
172
+ return { refusal: "router-outlet-refused", seeded };
173
+ }
174
+ const bornScreenBranch = type === import_codegen3.ControlType.VARIANT_BRANCH && input.screenKind !== "feature";
175
+ const id = genId2();
176
+ const variants = (0, import_codegen3.canCarryVariants)(type) ? (0, import_codegen3.variantsForNewControl)(
177
+ currentMap,
178
+ parentId,
179
+ // Show-all is not a ScreenVariant to land under — a Control born
180
+ // while the filter is off is base, the same as under none.
181
+ (0, import_codegen3.isAllVariantSelection)(input.variantSelection) ? [] : input.variantSelection,
182
+ type
183
+ ) : [];
184
+ const newControl = {
185
+ id,
186
+ type,
187
+ parentId,
188
+ // Every Control is born answering to a name, because the name is its
189
+ // ControlAsset's filename (ADR 0001) — its own id, which is unique for
190
+ // free and marks it as one the User has not named yet.
191
+ //
192
+ // A Field's name is also the data key the consuming app binds (ADR
193
+ // 0008), and a uuid there emits a form nobody can bind to, so it is
194
+ // born with a readable one instead.
195
+ // A branch and its arms emit no tag, so there is nothing for a `name`
196
+ // to sit on and no ControlAsset for one to resolve (ADR 0053).
197
+ configs: !(0, import_codegen3.isBornNamed)(type) ? {} : type === import_codegen3.ControlType.FIELD ? {
198
+ type: "text" /* TEXT */,
199
+ name: (0, import_codegen3.nextFieldName)(currentMap, parentId)
200
+ } : type === import_codegen3.ControlType.CARD ? { name: id, variant: "roundedBorder", padding: "none" } : (
201
+ // A menu with nothing draws nothing, and a Control that
202
+ // draws nothing cannot be selected — born with the
203
+ // primitive's standard authored configuration (ADR 0123).
204
+ type === import_codegen3.ControlType.CONTEXT_MENU ? (0, import_codegen3.standardMenuConfigs)(id) : (
205
+ // A table with no columns draws no heading, and one
206
+ // whose cells had nothing to line up with would be a
207
+ // grid with no reading (ADR 0148).
208
+ type === import_codegen3.ControlType.SECTION_TABLE ? { name: id, [import_codegen3.SECTION_TABLE_COLUMNS_KEY]: (0, import_codegen3.seedColumns)() } : { name: id }
209
+ )
210
+ ),
211
+ childrens: [],
212
+ ...variants.length ? { variants } : {},
213
+ ...bornScreenBranch ? { variantKind: "screen" } : {},
214
+ // A Repeat is born naming its row and its position, both free of any
215
+ // ancestor Repeat's words — a shadowed alias is one whose wrong
216
+ // resolution wins silently (GLOSSARY.md BindingAlias). Its `track`
217
+ // stays absent until a source gives it a shape to pick a key from.
218
+ ...type === import_codegen3.ControlType.REPEAT ? { repeat: (0, import_codegen3.newRepeatSpec)(parentId, currentMap) } : {}
219
+ };
220
+ const updatedControlMap = { ...currentMap };
221
+ updatedControlMap[id] = newControl;
222
+ if (type === import_codegen3.ControlType.STAT) {
223
+ const slotIds = [import_codegen3.ControlType.STAT_VALUE, import_codegen3.ControlType.STAT_CORNER].map(
224
+ (slotType) => {
225
+ const slotId = genId2();
226
+ updatedControlMap[slotId] = {
227
+ id: slotId,
228
+ type: slotType,
229
+ parentId: id,
230
+ configs: {},
231
+ childrens: []
232
+ };
233
+ seeded.push(slotType);
234
+ return slotId;
235
+ }
236
+ );
237
+ updatedControlMap[id] = { ...newControl, childrens: slotIds };
238
+ }
239
+ if (type === import_codegen3.ControlType.SCORE_SET) {
240
+ const itemIds = SCORE_SET_SEED.map((configs) => {
241
+ const itemId = genId2();
242
+ updatedControlMap[itemId] = {
243
+ id: itemId,
244
+ type: import_codegen3.ControlType.SCORE_SET_ITEM,
245
+ parentId: id,
246
+ configs: { ...configs },
247
+ childrens: []
248
+ };
249
+ seeded.push(import_codegen3.ControlType.SCORE_SET_ITEM);
250
+ return itemId;
251
+ });
252
+ updatedControlMap[id] = {
253
+ ...newControl,
254
+ configs: { ...newControl.configs, label: "score", showBand: true },
255
+ childrens: itemIds
256
+ };
257
+ }
258
+ if (type === import_codegen3.ControlType.SECTION_TABLE) {
259
+ const repeatId = genId2();
260
+ const rowId = genId2();
261
+ updatedControlMap[repeatId] = {
262
+ id: repeatId,
263
+ type: import_codegen3.ControlType.REPEAT,
264
+ parentId: id,
265
+ configs: {},
266
+ childrens: [rowId],
267
+ repeat: (0, import_codegen3.newRepeatSpec)(id, currentMap)
268
+ };
269
+ Object.assign(
270
+ updatedControlMap,
271
+ (0, import_codegen3.seedSectionTableRow)(rowId, repeatId, import_codegen3.SECTION_TABLE_SEED_COLUMNS, genId2)
272
+ );
273
+ updatedControlMap[id] = { ...newControl, childrens: [repeatId] };
274
+ seeded.push(import_codegen3.ControlType.REPEAT, import_codegen3.ControlType.SECTION_TABLE_ROW);
275
+ }
276
+ if (type === import_codegen3.ControlType.SECTION_TABLE_ROW && parentId) {
277
+ const table = (0, import_codegen3.enclosingSectionTable)(newControl, currentMap);
278
+ const columns = (0, import_codegen3.toSectionTableColumns)(
279
+ table?.configs?.[import_codegen3.SECTION_TABLE_COLUMNS_KEY]
280
+ );
281
+ const seededRow = (0, import_codegen3.seedSectionTableRow)(id, parentId, columns.length, genId2);
282
+ Object.assign(updatedControlMap, seededRow);
283
+ if (columns.length) seeded.push(import_codegen3.ControlType.SECTION_TABLE_CELL);
284
+ }
285
+ if (type === import_codegen3.ControlType.CONTENT && parentId) {
286
+ const field = updatedControlMap[parentId];
287
+ if (field && (0, import_codegen3.isCardHolder)(field) && !field.cards?.itemAlias) {
288
+ updatedControlMap[parentId] = {
289
+ ...field,
290
+ cards: {
291
+ ...(0, import_codegen3.cardSpec)(field),
292
+ ...(0, import_codegen3.newCardAliases)(parentId, currentMap)
293
+ }
294
+ };
295
+ }
296
+ }
297
+ const updatedRootControlIds = [...input.rootControlIds];
298
+ if (!parentId) {
299
+ updatedRootControlIds.push(id);
300
+ } else {
301
+ const parent = updatedControlMap[parentId];
302
+ if (parent) {
303
+ updatedControlMap[parentId] = {
304
+ ...parent,
305
+ childrens: [...parent.childrens || [], id]
306
+ };
307
+ }
308
+ }
309
+ return {
310
+ id,
311
+ controlMap: updatedControlMap,
312
+ rootControlIds: updatedRootControlIds,
313
+ seeded
314
+ };
315
+ }
316
+ function controlDeleteBlockers(id, controlMap, screenVariants) {
317
+ const held = (0, import_codegen3.heldFieldIds)(id, controlMap);
318
+ return (0, import_codegen3.listVariants)(screenVariants).filter(
319
+ (variant) => (0, import_codegen3.readsHeldField)(variant, held)
320
+ );
321
+ }
322
+ function dropControlSubtree(input) {
323
+ const { id } = input;
324
+ const updatedControlMap = { ...input.controlMap };
325
+ const control = updatedControlMap[id];
326
+ if (!control) return void 0;
327
+ const parentId = control.parentId;
328
+ let updatedRootControlIds = [...input.rootControlIds];
329
+ const siblings = parentId ? updatedControlMap[parentId]?.childrens ?? [] : updatedRootControlIds;
330
+ const index = siblings.indexOf(id);
331
+ const nextSelected = (index === -1 ? void 0 : siblings[index + 1] ?? siblings[index - 1]) ?? parentId;
332
+ if (!parentId) {
333
+ updatedRootControlIds = updatedRootControlIds.filter((rid) => rid !== id);
334
+ } else {
335
+ const parent = updatedControlMap[parentId];
336
+ if (parent && parent.childrens) {
337
+ updatedControlMap[parentId] = {
338
+ ...parent,
339
+ childrens: parent.childrens.filter((cid) => cid !== id)
340
+ };
341
+ }
342
+ }
343
+ const labelSamples = { ...input.labelSamples };
344
+ const deleteRecursive = (ctrlId) => {
345
+ const ctrl = updatedControlMap[ctrlId];
346
+ if (!ctrl) return;
347
+ Object.values(updatedControlMap).filter((c) => c.parentId === ctrlId).forEach((child) => deleteRecursive(child.id));
348
+ delete updatedControlMap[ctrlId];
349
+ delete labelSamples[ctrlId];
350
+ };
351
+ deleteRecursive(id);
352
+ let clearedSubmitTargets = 0;
353
+ for (const ctrl of Object.values(updatedControlMap)) {
354
+ const target = ctrl.configs?.[import_codegen3.SUBMIT_TARGET_KEY];
355
+ if (typeof target !== "string" || updatedControlMap[target]) continue;
356
+ clearedSubmitTargets++;
357
+ updatedControlMap[ctrl.id] = {
358
+ ...ctrl,
359
+ configs: { ...ctrl.configs, [import_codegen3.SUBMIT_TARGET_KEY]: void 0 }
360
+ };
361
+ }
362
+ let repairedOutcomes = 0;
363
+ for (const ctrl of Object.values(updatedControlMap)) {
364
+ for (const [field, map] of [["outputOutcomes", ctrl.outputOutcomes]]) {
365
+ if (!map) continue;
366
+ let moved = false;
367
+ const repaired = {};
368
+ for (const [key, outcome] of Object.entries(map)) {
369
+ const next = (0, import_codegen3.repairCallOutcome)(updatedControlMap, outcome);
370
+ if (next) moved = true;
371
+ const kept = next ?? outcome;
372
+ if ((0, import_codegen3.hasCallOutcome)(kept)) repaired[key] = kept;
373
+ else moved = true;
374
+ }
375
+ if (!moved) continue;
376
+ repairedOutcomes++;
377
+ updatedControlMap[ctrl.id] = {
378
+ ...updatedControlMap[ctrl.id],
379
+ [field]: Object.keys(repaired).length ? repaired : void 0
380
+ };
381
+ }
382
+ }
383
+ const sites = input.screen ? (0, import_codegen3.repairClassCallSites)(updatedControlMap, {
384
+ methods: input.screen.methods,
385
+ autoCalls: input.screen.autoCalls
386
+ }) : void 0;
387
+ return {
388
+ // A deleted Field's key is gone from its form, and with it every row
389
+ // that form's outputs read it through.
390
+ controlMap: (0, import_codegen3.pruneFormEventReads)(input.controlMap, updatedControlMap),
391
+ rootControlIds: updatedRootControlIds,
392
+ labelSamples,
393
+ ...sites ? { sites } : {},
394
+ nextSelected,
395
+ clearedSubmitTargets,
396
+ repairedOutcomes
397
+ };
398
+ }
399
+ var refuse = (reason, detail) => ({
400
+ ok: false,
401
+ notes: [],
402
+ refusal: detail ? { reason, detail } : { reason }
403
+ });
404
+ var CONTROL_TYPES = new Set(Object.values(import_codegen3.ControlType));
405
+ var nextGestureId = import_codegen3.genId;
406
+ var controlAdd = {
407
+ name: "control-add",
408
+ summary: "Drop a Control from the Palette, seeded as the editor seeds it",
409
+ args: {
410
+ screenId: { type: "string", required: true, doc: "Screen to add to" },
411
+ type: { type: "string", required: true, doc: "A ControlType value, e.g. `text`" },
412
+ parentId: { type: "string", doc: "Parent Control; absent = a root (Section / Flex only)" },
413
+ variantIds: { type: "array", doc: "ScreenVariant ids it lands under; absent = base" },
414
+ id: {
415
+ type: "string",
416
+ doc: "A fresh UUID for the Control, so a later batch step can name it as a parent; absent = minted"
417
+ }
418
+ },
419
+ run: (ctx, { screenId, type, parentId, variantIds, id }) => {
420
+ const slot = ctx.screenOf(screenId);
421
+ if (!slot) return refuse("screen-missing");
422
+ if (!CONTROL_TYPES.has(type)) return refuse("control-type-unknown", { type });
423
+ if (id && ctx.source.screens.some(({ state }) => !!state.controlMap[id]))
424
+ return refuse("control-id-taken", { id });
425
+ let first = !!id;
426
+ const mint = () => {
427
+ if (first) {
428
+ first = false;
429
+ return id;
430
+ }
431
+ return nextGestureId();
432
+ };
433
+ const added = addControlTree({
434
+ controlMap: slot.state.controlMap,
435
+ rootControlIds: slot.state.rootControlIds,
436
+ type,
437
+ parentId,
438
+ screenKind: slot.meta.kind,
439
+ variantSelection: variantIds ?? [],
440
+ genId: mint
441
+ });
442
+ if (added.refusal || !added.controlMap || !added.rootControlIds)
443
+ return refuse(added.refusal ?? "placement-refused");
444
+ return {
445
+ ok: true,
446
+ notes: [
447
+ `added ${type} ${added.id}`,
448
+ ...added.seeded.length ? [`seeded ${added.seeded.join(", ")}`] : []
449
+ ],
450
+ patch: {
451
+ screens: {
452
+ [screenId]: {
453
+ ...slot,
454
+ state: {
455
+ ...slot.state,
456
+ controlMap: added.controlMap,
457
+ rootControlIds: added.rootControlIds
458
+ }
459
+ }
460
+ }
461
+ }
462
+ };
463
+ }
464
+ };
465
+ var controlMove = {
466
+ name: "control-move",
467
+ summary: "Move a Control: drop beside / inside a target, nudge up or down, or lift out of its parent",
468
+ args: {
469
+ screenId: { type: "string", required: true, doc: "Screen holding it" },
470
+ controlId: { type: "string", required: true, doc: "Control to move" },
471
+ targetId: { type: "string", doc: "With `position`: the Control to drop against" },
472
+ position: { type: "string", doc: "`before` | `after` | `inside`" },
473
+ direction: { type: "string", doc: "`up` | `down`: one step among its siblings" },
474
+ out: { type: "boolean", doc: "Lift one Layer up, right after its parent" }
475
+ },
476
+ run: (ctx, { screenId, controlId, targetId, position, direction, out }) => {
477
+ const slot = ctx.screenOf(screenId);
478
+ if (!slot) return refuse("screen-missing");
479
+ const { controlMap, rootControlIds } = slot.state;
480
+ if (!controlMap[controlId]) return refuse("control-missing");
481
+ const aim = direction ? [
482
+ siblingNeighbour(controlMap, rootControlIds, controlId, direction),
483
+ direction === "up" ? "before" : "after"
484
+ ] : out ? [controlMap[controlId].parentId, "after"] : [targetId, position ?? "inside"];
485
+ const [target, at] = aim;
486
+ if (!target) return refuse("move-refused");
487
+ const result = applyMove(controlMap, rootControlIds, controlId, target, at);
488
+ if (!result) return refuse("move-refused");
489
+ const patch = movePatch(result, controlId);
490
+ const rebased = patch.controlMap ?? result.controlMap;
491
+ const next = (0, import_codegen3.pruneFormEventReads)(controlMap, rebased);
492
+ const rebasedIds = Object.keys(rebased).filter(
493
+ (id) => rebased[id].variants !== result.controlMap[id]?.variants
494
+ );
495
+ return {
496
+ ok: true,
497
+ notes: [
498
+ ...rebasedIds.length ? [`rebased variants on ${rebasedIds.length} Control(s)`] : [],
499
+ ...next !== rebased ? ["dropped form event reads of a Field that left its form"] : []
500
+ ],
501
+ patch: {
502
+ screens: {
503
+ [screenId]: {
504
+ ...slot,
505
+ state: {
506
+ ...slot.state,
507
+ controlMap: next,
508
+ rootControlIds: patch.rootControlIds ?? result.rootControlIds
509
+ }
510
+ }
511
+ }
512
+ }
513
+ };
514
+ }
515
+ };
516
+ var controlDelete = {
517
+ name: "control-delete",
518
+ summary: "Delete a Control and everything under it, with the links to it",
519
+ args: {
520
+ screenId: { type: "string", required: true, doc: "Screen holding it" },
521
+ controlId: { type: "string", required: true, doc: "Control to delete" }
522
+ },
523
+ run: (ctx, { screenId, controlId }) => {
524
+ const slot = ctx.screenOf(screenId);
525
+ if (!slot) return refuse("screen-missing");
526
+ const blockers = controlDeleteBlockers(
527
+ controlId,
528
+ slot.state.controlMap,
529
+ slot.meta.variants ?? {}
530
+ );
531
+ if (blockers.length)
532
+ return refuse("control-delete-blocked", {
533
+ variants: blockers.map(({ id, name }) => ({ id, name }))
534
+ });
535
+ const dropped = dropControlSubtree({
536
+ controlMap: slot.state.controlMap,
537
+ rootControlIds: slot.state.rootControlIds,
538
+ labelSamples: slot.state.labelSamples,
539
+ screen: slot.meta,
540
+ id: controlId
541
+ });
542
+ if (!dropped) return refuse("control-missing");
543
+ return {
544
+ ok: true,
545
+ notes: [
546
+ ...dropped.clearedSubmitTargets ? [`cleared ${dropped.clearedSubmitTargets} submit target(s)`] : [],
547
+ ...dropped.repairedOutcomes ? [`repaired FormReset rows on ${dropped.repairedOutcomes} Control(s)`] : [],
548
+ ...dropped.sites ? ["repaired ScreenMethod / AutoCall arms"] : []
549
+ ],
550
+ patch: {
551
+ screens: {
552
+ [screenId]: {
553
+ meta: dropped.sites ? { ...slot.meta, ...dropped.sites } : slot.meta,
554
+ state: {
555
+ ...slot.state,
556
+ controlMap: dropped.controlMap,
557
+ rootControlIds: dropped.rootControlIds,
558
+ labelSamples: dropped.labelSamples
559
+ }
560
+ }
561
+ }
562
+ }
563
+ };
564
+ }
565
+ };
566
+
567
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/config-gestures.ts
568
+ var import_codegen6 = require("./index.js");
569
+
570
+ // apps/m-one-ui/src/app/pages/design/lib/control-outputs.ts
571
+ var import_codegen4 = require("./index.js");
572
+ var CONTROL_OUTPUTS = {
573
+ [import_codegen4.ControlType.BUTTON]: ["clicked"],
574
+ [import_codegen4.ControlType.CONTEXT_MENU]: ["action"],
575
+ // The picker's own value, once the User has moved it — the write half of the
576
+ // controlled binding, drawn as a StateWrite rather than as `[(audience)]`
577
+ // (ADR 0187, ADR 0065). Offered whatever the two halves hold: a picker bound
578
+ // to no `audience` still edits its own value and still fires this.
579
+ [import_codegen4.ControlType.AUDIENCE_PICKER]: ["audienceChange"],
580
+ [import_codegen4.ControlType.CARD]: ["clicked"],
581
+ // `submitted` is offered only under a Button declaring `isSubmit` — see
582
+ // `outputsOf` below.
583
+ [import_codegen4.ControlType.FORM]: ["submitted", "dataChange", "formInitialized"],
584
+ // The Field's own `dataChange`, at field granularity — the value the User
585
+ // typed into this one field, not the form's record (libs/one ADR 0032).
586
+ // Needs no Button, the way the form's does not (see `outputsOf`).
587
+ [import_codegen4.ControlType.FIELD]: ["dataChange"],
588
+ [import_codegen4.ControlType.SECTION]: ["inView"],
589
+ [import_codegen4.ControlType.SECTION_HEADER]: ["actionClick", "action", "back"],
590
+ // Debounced already by the component — what arrives here is the term the User
591
+ // stopped typing, which is the only thing worth binding a call to.
592
+ [import_codegen4.ControlType.SECTION_SEARCH]: ["searchChange"],
593
+ // One output for the whole bar, carrying the Button that was pressed — an
594
+ // `m-action` names its Buttons rather than holding them, so there is no
595
+ // per-Button Control for a binding to sit on (ADR 0009).
596
+ [import_codegen4.ControlType.SECTION_ACTION]: ["clicked"],
597
+ // Which slide is showing, every time it changes — by drag, by indicator, or
598
+ // by the clock. Two spellings of the one event, because what a caller binds
599
+ // differs: `slideChange` carries the position, `itemChange` the row behind it,
600
+ // which is what a call needing the slide's own data takes.
601
+ [import_codegen4.ControlType.SECTION_CAROUSEL]: ["slideChange", "itemChange"],
602
+ // The whole group's selection, every time any Filter beneath it changes
603
+ // (libs/one ADR 0025). Per-change rather than on-close: a group has no single
604
+ // close event full-width, and `switchMap` in the emitted store already drops
605
+ // the responses of calls a later change supersedes.
606
+ [import_codegen4.ControlType.SECTION_FILTER_GROUP]: ["filterChange"],
607
+ // Offered only outside a group — see `outputsOf` below.
608
+ [import_codegen4.ControlType.SECTION_FILTER]: ["filterChange"],
609
+ // One payload, `{offset, perPage}`, and both members are pickable — a
610
+ // CallArgMapping reading `event.offset` gets a number, which is what an
611
+ // ApiOperation's query param takes. The whole `$event` works too, unlike a
612
+ // FilterGroup's list of pairs (ADR 0097).
613
+ [import_codegen4.ControlType.SECTION_PAGINATION]: ["paginationChange"],
614
+ // `{id, direction}`, after the rows were reordered in place — bound when the
615
+ // table holds one page of a longer list and whoever fetches has to sort the
616
+ // rest (ADR 0148). `tableInitialized` fires once, after the first render —
617
+ // no payload, the Form's `formInitialized` for a table.
618
+ [import_codegen4.ControlType.SECTION_TABLE]: ["sortChange", "tableInitialized"],
619
+ // Repeated rows emit their Repeat item; static rows emit `undefined`.
620
+ [import_codegen4.ControlType.SECTION_TABLE_ROW]: ["rowClick"],
621
+ // The preset picked, and the window it drew as `{from, to}` ISO text — both
622
+ // members pickable, each a date an ApiOperation's param takes. Fired when the
623
+ // reader picks a preset or lets go of the navigator, never because an input
624
+ // moved, so a fetch bound here cannot loop (libs/one GLOSSARY.md
625
+ // SectionChart, the SectionPagination rule of ADR 0097).
626
+ [import_codegen4.ControlType.SECTION_CHART]: ["rangeChange", "windowChange"],
627
+ // Offered under the `link` variant alone — see `outputsOf` below.
628
+ [import_codegen4.ControlType.TEXT_OUTPUT]: ["clicked"]
629
+ };
630
+ var OUTPUT_MAP_FIELDS = [
631
+ ...import_codegen4.OUTPUT_GROUP_MAPS,
632
+ "outputCalls",
633
+ "outputArms"
634
+ ];
635
+ var CLEARED_OUTPUT_WIRING = Object.fromEntries(
636
+ OUTPUT_MAP_FIELDS.map((field) => [field, void 0])
637
+ );
638
+
639
+ // apps/m-one-ui/src/app/pages/design/lib/screen-embed-helper.ts
640
+ var import_codegen5 = require("./index.js");
641
+ var isScreenControl = (control) => control.type === import_codegen5.ControlType.SCREEN && typeof control.screenId === "string";
642
+ function embeddedScreenIds(controlMap) {
643
+ return Object.values(controlMap).filter(isScreenControl).map((control) => control.screenId);
644
+ }
645
+ function reachableScreenIds(rootId, maps) {
646
+ const seen = /* @__PURE__ */ new Set();
647
+ const queue = [...embeddedScreenIds(maps[rootId] ?? {})];
648
+ while (queue.length) {
649
+ const id = queue.shift();
650
+ if (seen.has(id)) continue;
651
+ seen.add(id);
652
+ queue.push(...embeddedScreenIds(maps[id] ?? {}));
653
+ }
654
+ return seen;
655
+ }
656
+ function wouldCycle(hostId, targetId, maps) {
657
+ if (hostId === targetId) return true;
658
+ return reachableScreenIds(targetId, maps).has(hostId);
659
+ }
660
+ var firesFromMount = (screen) => (0, import_codegen5.isFeatureScreen)(screen) && !!screen.autoCalls?.length;
661
+ function duplicateFeatureEmbeds(rootId, maps, screens) {
662
+ return [
663
+ ...new Set(
664
+ duplicateFeatureEmbedControls(rootId, maps, screens).map(
665
+ (mount) => mount.screenId
666
+ )
667
+ )
668
+ ].sort();
669
+ }
670
+ function duplicateFeatureEmbedControls(rootId, maps, screens) {
671
+ const byId = new Map(screens.map((screen) => [screen.id, screen]));
672
+ const mounts = /* @__PURE__ */ new Map();
673
+ const duplicates = /* @__PURE__ */ new Map();
674
+ const contains = (left, right) => [...right].every((gate) => left.has(gate));
675
+ const walk = (hostId, inherited, ancestors, instance) => {
676
+ if (ancestors.has(hostId)) return;
677
+ const seen = /* @__PURE__ */ new Set([...ancestors, hostId]);
678
+ const controls = maps[hostId] ?? {};
679
+ for (const control of Object.values(controls).filter(isScreenControl)) {
680
+ const gates = new Set(inherited);
681
+ const parents = /* @__PURE__ */ new Set();
682
+ let parent = control;
683
+ while (parent && !parents.has(parent.id)) {
684
+ parents.add(parent.id);
685
+ if (parent.variants?.length) {
686
+ gates.add(JSON.stringify([instance, "variants", parent.variants]));
687
+ }
688
+ if (parent.type === import_codegen5.ControlType.BRANCH_ARM) {
689
+ gates.add(
690
+ JSON.stringify([instance, "arm", parent.parentId, parent.id])
691
+ );
692
+ }
693
+ parent = parent.parentId ? controls[parent.parentId] : void 0;
694
+ }
695
+ const screen = byId.get(control.screenId);
696
+ if (screen && firesFromMount(screen)) {
697
+ const previous = mounts.get(screen.id) ?? [];
698
+ const mount = {
699
+ hostId,
700
+ controlId: control.id,
701
+ screenId: screen.id,
702
+ gates
703
+ };
704
+ previous.forEach((other) => {
705
+ if (contains(gates, other.gates) || contains(other.gates, gates)) {
706
+ duplicates.set(JSON.stringify([hostId, control.id]), mount);
707
+ duplicates.set(
708
+ JSON.stringify([other.hostId, other.controlId]),
709
+ other
710
+ );
711
+ }
712
+ });
713
+ previous.push(mount);
714
+ mounts.set(screen.id, previous);
715
+ }
716
+ walk(control.screenId, gates, seen, [...instance, control.id]);
717
+ }
718
+ };
719
+ walk(rootId, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set(), [rootId]);
720
+ return [...duplicates.values()].map(({ hostId, controlId, screenId }) => ({
721
+ hostId,
722
+ controlId,
723
+ screenId
724
+ }));
725
+ }
726
+ function featureReachEdges(maps, screens) {
727
+ const byId = new Map(screens.map((screen) => [screen.id, screen]));
728
+ const edges = /* @__PURE__ */ new Map();
729
+ for (const screen of screens) {
730
+ if (!(0, import_codegen5.isFeatureScreen)(screen)) continue;
731
+ for (const id of embeddedScreenIds(maps[screen.id] ?? {})) {
732
+ const target = byId.get(id);
733
+ if (!target || !(0, import_codegen5.isFeatureScreen)(target)) continue;
734
+ if (target.featureId === screen.featureId) continue;
735
+ const reached = edges.get(screen.featureId) ?? /* @__PURE__ */ new Set();
736
+ reached.add(target.featureId);
737
+ edges.set(screen.featureId, reached);
738
+ }
739
+ }
740
+ return edges;
741
+ }
742
+ function featuresReachedBy(featureId, edges) {
743
+ const seen = /* @__PURE__ */ new Set();
744
+ const queue = [...edges.get(featureId) ?? []];
745
+ while (queue.length) {
746
+ const id = queue.shift();
747
+ if (seen.has(id)) continue;
748
+ seen.add(id);
749
+ queue.push(...edges.get(id) ?? []);
750
+ }
751
+ return seen;
752
+ }
753
+ function wouldCycleFeatures(hostFeatureId, targetFeatureId, edges) {
754
+ if (hostFeatureId === targetFeatureId) return false;
755
+ return targetFeatureId === hostFeatureId || featuresReachedBy(targetFeatureId, edges).has(hostFeatureId);
756
+ }
757
+ function screensEmbedding(screenId, maps) {
758
+ return Object.entries(maps).filter(
759
+ ([, controlMap]) => embeddedScreenIds(controlMap).includes(screenId)
760
+ ).map(([hostId]) => hostId).sort();
761
+ }
762
+
763
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/config-gestures.ts
764
+ var mergeConfigs = (current, incoming) => {
765
+ const merged = { ...current, ...incoming };
766
+ Object.keys(incoming).forEach((key) => {
767
+ if (incoming[key] === void 0) delete merged[key];
768
+ });
769
+ return merged;
770
+ };
771
+ var withoutActionSelection = (control) => {
772
+ const { [import_codegen6.ACTION_SELECTION_KEY]: _pick, ...configs } = control.configs ?? {};
773
+ const { [import_codegen6.BINDING_SLOT.selection]: _bound, ...bindings } = control.bindings ?? {};
774
+ const { bindings: _all, ...rest } = control;
775
+ return Object.keys(bindings).length ? { ...rest, configs, bindings } : { ...rest, configs };
776
+ };
777
+ function fieldRetypeBlockers(controlMap, id, configs, scope) {
778
+ const control = controlMap[id];
779
+ if (!control || control.type !== import_codegen6.ControlType.FIELD) return [];
780
+ const merged = mergeConfigs(control.configs, configs);
781
+ const before = (0, import_codegen6.fieldKeyType)(control.configs);
782
+ const after = (0, import_codegen6.fieldKeyType)(merged);
783
+ if (before.dataType.type === after.dataType.type && before.cardinality === after.cardinality) {
784
+ return [];
785
+ }
786
+ const readers = (0, import_codegen6.listVariants)(scope.screenVariants).filter(
787
+ (variant) => (0, import_codegen6.readsHeldField)(variant, /* @__PURE__ */ new Set([id]))
788
+ );
789
+ if (!readers.length) return [];
790
+ const candidate = { ...controlMap, [id]: { ...control, configs: merged } };
791
+ const properties = {
792
+ ...scope.pathRoots,
793
+ ...(0, import_codegen6.screenPropertiesWithComputeds)(
794
+ scope.inputs,
795
+ scope.screenComputeds,
796
+ scope.functionsInScope,
797
+ scope.constants,
798
+ scope.variables,
799
+ scope.formModels
800
+ )
801
+ };
802
+ const shapes = (0, import_codegen6.withFormShapes)(scope.shapes, (0, import_codegen6.formShapeMap)(candidate));
803
+ return readers.filter(
804
+ (variant) => !!(0, import_codegen6.ruleError)(variant.rule, properties, shapes, scope.functionsInScope)
805
+ );
806
+ }
807
+ function newFieldKeyClashes(controlMap, id, configs) {
808
+ const control = controlMap[id];
809
+ if (!control || control.type !== import_codegen6.ControlType.FIELD) return [];
810
+ const before = new Set((0, import_codegen6.fieldKeyClashes)(controlMap, id, control.configs));
811
+ return (0, import_codegen6.fieldKeyClashes)(
812
+ controlMap,
813
+ id,
814
+ mergeConfigs(control.configs, configs)
815
+ ).filter((other) => !before.has(other));
816
+ }
817
+ function applyControlConfigs(controlMap, id, configs, translations) {
818
+ const updatedControlMap = { ...controlMap };
819
+ const control = updatedControlMap[id];
820
+ if (!control) return void 0;
821
+ updatedControlMap[id] = (0, import_codegen6.pruneOrphanMessageBindings)(
822
+ { ...control, configs: mergeConfigs(control.configs, configs) },
823
+ translations
824
+ );
825
+ let droppedSelection = false;
826
+ if (control.type === import_codegen6.ControlType.SECTION_ACTION && updatedControlMap[id].configs?.["variant"] !== "toggle") {
827
+ const without2 = withoutActionSelection(updatedControlMap[id]);
828
+ droppedSelection = JSON.stringify(without2) !== JSON.stringify(updatedControlMap[id]);
829
+ updatedControlMap[id] = without2;
830
+ }
831
+ const formId = control.type === import_codegen6.ControlType.FIELD ? (0, import_codegen6.owningFormId)(id, updatedControlMap) : void 0;
832
+ const from = (0, import_codegen6.resolveFieldName)({ id, configs: control.configs });
833
+ const to = (0, import_codegen6.resolveFieldName)({ id, configs: updatedControlMap[id].configs });
834
+ let renamedFormMember;
835
+ if (formId && from !== to && !(0, import_codegen6.formEventMembers)(updatedControlMap, formId).includes(from)) {
836
+ updatedControlMap[formId] = (0, import_codegen6.renameFormEventMember)(
837
+ updatedControlMap[formId],
838
+ from,
839
+ to
840
+ );
841
+ renamedFormMember = { from, to };
842
+ }
843
+ return {
844
+ controlMap: updatedControlMap,
845
+ droppedSelection,
846
+ ...renamedFormMember ? { renamedFormMember } : {}
847
+ };
848
+ }
849
+ function embedTargetsFor(host, screens, allMaps, hostControlMap, exceptControlId) {
850
+ const maps = { ...allMaps };
851
+ if (exceptControlId) {
852
+ maps[host.id] = { ...maps[host.id] ?? {} };
853
+ delete maps[host.id][exceptControlId];
854
+ }
855
+ const featureEdges = featureReachEdges(maps, screens);
856
+ const targets = screens.filter(
857
+ (target) => (0, import_codegen6.canEmbedScreen)(host, target) && !wouldCycle(host.id, target.id, maps) && !((0, import_codegen6.isFeatureScreen)(host) && (0, import_codegen6.isFeatureScreen)(target) && wouldCycleFeatures(host.featureId, target.featureId, featureEdges))
858
+ );
859
+ if (!exceptControlId) return targets;
860
+ const control = hostControlMap[exceptControlId];
861
+ if (!control || !isScreenControl(control)) return [];
862
+ const existingDuplicates = new Map(
863
+ screens.map((screen) => [
864
+ screen.id,
865
+ new Set(duplicateFeatureEmbeds(screen.id, maps, screens))
866
+ ])
867
+ );
868
+ return targets.filter((target) => {
869
+ const replaced = {
870
+ ...maps,
871
+ [host.id]: {
872
+ ...maps[host.id],
873
+ [exceptControlId]: { ...control, screenId: target.id }
874
+ }
875
+ };
876
+ return screens.every(
877
+ (screen) => duplicateFeatureEmbeds(screen.id, replaced, screens).every(
878
+ (id) => existingDuplicates.get(screen.id)?.has(id)
879
+ )
880
+ );
881
+ });
882
+ }
883
+ var retargetedControl = (control, screenId) => ({
884
+ ...control,
885
+ screenId,
886
+ handRef: void 0,
887
+ screenInputs: void 0,
888
+ ...CLEARED_OUTPUT_WIRING
889
+ });
890
+ var refuse2 = (reason, detail) => ({
891
+ ok: false,
892
+ notes: [],
893
+ refusal: detail ? { reason, detail } : { reason }
894
+ });
895
+ var controlConfigs = {
896
+ name: "control-configs",
897
+ summary: "Set a Control\u2019s configs (a `null` value unsets a key)",
898
+ args: {
899
+ screenId: { type: "string", required: true, doc: "Screen holding it" },
900
+ controlId: { type: "string", required: true, doc: "Control to edit" },
901
+ configs: { type: "object", required: true, doc: "Keys to set; `null` unsets" }
902
+ },
903
+ run: (ctx, { screenId, controlId, configs }) => {
904
+ const slot = ctx.screenOf(screenId);
905
+ if (!slot) return refuse2("screen-missing");
906
+ const controlMap = slot.state.controlMap;
907
+ if (!controlMap[controlId]) return refuse2("control-missing");
908
+ const incoming = Object.fromEntries(
909
+ Object.entries(configs).map(([key, value]) => [key, value === null ? void 0 : value])
910
+ );
911
+ const scope = screenScopeOf(ctx.source, slot);
912
+ const blockers = fieldRetypeBlockers(controlMap, controlId, incoming, {
913
+ screenVariants: slot.meta.variants ?? {},
914
+ pathRoots: scope.pathRoots,
915
+ inputs: slot.meta.inputs ?? {},
916
+ screenComputeds: slot.meta.computeds ?? {},
917
+ functionsInScope: scope.functionsInScope,
918
+ constants: slot.meta.constants ?? {},
919
+ variables: scope.meta.variables ?? {},
920
+ formModels: slot.meta.formModels ?? {},
921
+ shapes: scope.shapes
922
+ });
923
+ if (blockers.length)
924
+ return refuse2("field-retype-blocked", {
925
+ variants: blockers.map(({ id, name }) => ({ id, name }))
926
+ });
927
+ const clashes = newFieldKeyClashes(controlMap, controlId, incoming);
928
+ if (clashes.length) return refuse2("field-key-clash", { fields: clashes });
929
+ const applied = applyControlConfigs(
930
+ controlMap,
931
+ controlId,
932
+ incoming,
933
+ ctx.source.translations ?? {}
934
+ );
935
+ if (!applied) return refuse2("control-missing");
936
+ return {
937
+ ok: true,
938
+ notes: [
939
+ ...applied.droppedSelection ? ["dropped the SectionAction pick (no longer a toggle)"] : [],
940
+ ...applied.renamedFormMember ? [`carried form $event rows ${applied.renamedFormMember.from} \u2192 ${applied.renamedFormMember.to}`] : []
941
+ ],
942
+ patch: {
943
+ screens: {
944
+ [screenId]: { ...slot, state: { ...slot.state, controlMap: applied.controlMap } }
945
+ }
946
+ }
947
+ };
948
+ }
949
+ };
950
+ var screenControlTarget = {
951
+ name: "screen-control-target",
952
+ summary: "Point a ScreenControl at the Screen it embeds (clears its bindings)",
953
+ args: {
954
+ screenId: { type: "string", required: true, doc: "Host Screen" },
955
+ controlId: { type: "string", required: true, doc: "The ScreenControl" },
956
+ targetScreenId: { type: "string", required: true, doc: "Screen to embed" }
957
+ },
958
+ run: (ctx, { screenId, controlId, targetScreenId }) => {
959
+ const slot = ctx.screenOf(screenId);
960
+ if (!slot) return refuse2("screen-missing");
961
+ const control = slot.state.controlMap[controlId];
962
+ if (!control || control.type !== import_codegen6.ControlType.SCREEN)
963
+ return refuse2("not-a-screen-control");
964
+ const target = ctx.screenOf(targetScreenId);
965
+ if (!target) return refuse2("target-missing");
966
+ if (control.screenId === targetScreenId) return refuse2("target-unchanged");
967
+ if ((0, import_codegen6.embedShapeBlocked)(slot.meta, target.meta))
968
+ return refuse2("embed-shape-blocked");
969
+ const screens = ctx.source.screens.map(({ meta }) => meta);
970
+ const maps = Object.fromEntries(
971
+ ctx.source.screens.map(({ meta, state }) => [meta.id, state.controlMap])
972
+ );
973
+ const except = isScreenControl(control) ? controlId : void 0;
974
+ const allowed = embedTargetsFor(slot.meta, screens, maps, slot.state.controlMap, except);
975
+ if (!allowed.some(({ id }) => id === targetScreenId))
976
+ return refuse2("embed-refused", {
977
+ why: (0, import_codegen6.canEmbedScreen)(slot.meta, target.meta) ? "cycle-or-duplicate" : "direction"
978
+ });
979
+ return {
980
+ ok: true,
981
+ notes: isScreenControl(control) ? ["cleared the old target\u2019s input and output bindings"] : [],
982
+ patch: {
983
+ screens: {
984
+ [screenId]: {
985
+ ...slot,
986
+ state: {
987
+ ...slot.state,
988
+ controlMap: {
989
+ ...slot.state.controlMap,
990
+ [controlId]: retargetedControl(control, targetScreenId)
991
+ }
992
+ }
993
+ }
994
+ }
995
+ }
996
+ };
997
+ }
998
+ };
999
+
1000
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/bind-gestures.ts
1001
+ var import_codegen8 = require("./index.js");
1002
+
1003
+ // apps/m-one-ui/src/app/pages/design/lib/binding-want.ts
1004
+ var import_codegen7 = require("./index.js");
1005
+ var wants = (want, dataType, cardinality, shapes, controlId = "") => {
1006
+ if (want === "options")
1007
+ return (0, import_codegen7.isOptionRowShape)(dataType, cardinality, shapes);
1008
+ if (want === "audience")
1009
+ return cardinality === "one" && dataType?.type === "audience";
1010
+ if (want === "action") {
1011
+ if (cardinality !== "one" || dataType?.type !== "string") return false;
1012
+ return !dataType.actionEnumId || dataType.actionEnumId === controlId;
1013
+ }
1014
+ if (want === "collection") return cardinality === "many";
1015
+ if (want === "repeatable") {
1016
+ return cardinality === "many" || (0, import_codegen7.isMapCardinality)(cardinality) || dataType?.type === "shape";
1017
+ }
1018
+ if (cardinality !== "one") return false;
1019
+ return want === "shape" ? dataType?.type === "shape" : dataType?.type !== "shape";
1020
+ };
1021
+
1022
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/bind-gestures.ts
1023
+ var NO_FEATURE2 = (0, import_codegen8.emptyFeature)("", "");
1024
+ function bindingScopesOf(source, slot, controlId) {
1025
+ const scope = screenScopeOf(source, slot);
1026
+ const { meta, state } = slot;
1027
+ const formModels = meta.formModels ? (0, import_codegen8.reconcileFormModels)(meta.formModels, state.controlMap, {
1028
+ inputs: meta.inputs ?? {},
1029
+ computeds: meta.computeds ?? {},
1030
+ constants: meta.constants ?? {},
1031
+ functions: scope.functionsInScope,
1032
+ shapes: scope.shapes,
1033
+ ...(0, import_codegen8.hasStore)(meta.kind) ? { properties: scope.feature?.properties ?? {} } : {}
1034
+ }) : {};
1035
+ const bindingShapes = (0, import_codegen8.withFormShapes)(scope.shapes, (0, import_codegen8.formShapeMap)(state.controlMap));
1036
+ const readable = (0, import_codegen8.readableMembers)(scope.feature ?? NO_FEATURE2, import_codegen8.MAIN_STORE_OWNER);
1037
+ return {
1038
+ options: {
1039
+ controlId,
1040
+ controlMap: state.controlMap,
1041
+ roots: scope.pathRoots,
1042
+ properties: scope.feature?.properties ?? {},
1043
+ shapes: bindingShapes,
1044
+ inputs: meta.inputs,
1045
+ screenComputeds: meta.computeds ?? {},
1046
+ screenVariables: scope.meta.variables ?? {},
1047
+ formModels,
1048
+ functions: scope.functionsInScope,
1049
+ enums: source.enums,
1050
+ allowAlias: true
1051
+ },
1052
+ resolve: {
1053
+ properties: readable.properties,
1054
+ computeds: readable.computeds,
1055
+ shapes: bindingShapes,
1056
+ inputs: meta.inputs,
1057
+ screenComputeds: meta.computeds ?? {},
1058
+ screenVariables: meta.variables,
1059
+ formModels: meta.formModels,
1060
+ functions: scope.functionsInScope,
1061
+ controlMap: state.controlMap
1062
+ }
1063
+ };
1064
+ }
1065
+ function cascadingSlot(control, slot) {
1066
+ if (slot === import_codegen8.BINDING_SLOT.data)
1067
+ return control.type === import_codegen8.ControlType.LIST || control.type === import_codegen8.ControlType.FORM || control.type === import_codegen8.ControlType.SECTION_CHART_SERIES || (0, import_codegen8.isCardHolder)(control);
1068
+ if (slot === import_codegen8.BINDING_SLOT.options) return control.type === import_codegen8.ControlType.CONTEXT_MENU;
1069
+ const halves = import_codegen8.AUDIENCE_PICKER_VALUE_SLOTS;
1070
+ return control.type === import_codegen8.ControlType.AUDIENCE_PICKER && halves.includes(slot);
1071
+ }
1072
+ function slotWant(control, slot) {
1073
+ if (slot === import_codegen8.BINDING_SLOT.source && control.type === import_codegen8.ControlType.REPEAT)
1074
+ return "repeatable";
1075
+ if (slot === import_codegen8.BINDING_SLOT.selection && control.type === import_codegen8.ControlType.SECTION_ACTION)
1076
+ return "action";
1077
+ return "scalar";
1078
+ }
1079
+ var ROOT_ORDER = [
1080
+ "property",
1081
+ "computed",
1082
+ "input",
1083
+ "screen_computed",
1084
+ "screen_variable",
1085
+ "form_model",
1086
+ "alias",
1087
+ "auth"
1088
+ ];
1089
+ var rank = (option) => {
1090
+ const at = ROOT_ORDER.indexOf(option.binding.root.kind);
1091
+ return at === -1 ? ROOT_ORDER.length : at;
1092
+ };
1093
+ function bindingCandidates(source, slot, controlId, slotName) {
1094
+ const control = slot.state.controlMap[controlId];
1095
+ if (!control) return [];
1096
+ const { options } = bindingScopesOf(source, slot, controlId);
1097
+ const want = slotWant(control, slotName);
1098
+ return (0, import_codegen8.bindingOptions)(
1099
+ options,
1100
+ (dataType, cardinality) => wants(want, dataType, cardinality, options.shapes, controlId)
1101
+ ).map((option, index) => ({ option, index })).sort((a, b) => rank(a.option) - rank(b.option) || a.index - b.index).map(({ option }) => option);
1102
+ }
1103
+ function boundControl(control, slot, binding, scope) {
1104
+ const bindings = { ...control.bindings ?? {} };
1105
+ if (binding) bindings[slot] = binding;
1106
+ else delete bindings[slot];
1107
+ const halves = import_codegen8.AUDIENCE_PICKER_VALUE_SLOTS;
1108
+ if (binding && control.type === import_codegen8.ControlType.AUDIENCE_PICKER && halves.includes(slot)) {
1109
+ for (const other of halves) {
1110
+ if (other !== slot) delete bindings[other];
1111
+ }
1112
+ }
1113
+ const { bindings: _dropped, ...rest } = control;
1114
+ const spec = control.repeat;
1115
+ const track = spec?.track;
1116
+ let repeat = spec;
1117
+ if (binding && slot === import_codegen8.BINDING_SLOT.source && control.type === import_codegen8.ControlType.REPEAT && track?.kind === "key" && spec && !(0, import_codegen8.sourceCarriesTrackKey)(binding, track.keyId, scope)) {
1118
+ repeat = { ...spec, track: void 0 };
1119
+ }
1120
+ let next = Object.keys(bindings).length ? { ...rest, bindings } : rest;
1121
+ if (binding && control.type === import_codegen8.ControlType.SECTION_ACTION && slot === import_codegen8.BINDING_SLOT.selection && next.configs?.[import_codegen8.ACTION_SELECTION_KEY] !== void 0) {
1122
+ const { [import_codegen8.ACTION_SELECTION_KEY]: _pick, ...configs } = next.configs;
1123
+ next = { ...next, configs };
1124
+ }
1125
+ return repeat === spec ? next : { ...next, repeat };
1126
+ }
1127
+ var refuse3 = (reason, detail) => ({
1128
+ ok: false,
1129
+ notes: [],
1130
+ refusal: detail ? { reason, detail } : { reason }
1131
+ });
1132
+ var controlBind = {
1133
+ name: "control-bind",
1134
+ summary: "Bind (or clear) one read slot of a Control \u2014 a label, a value, a Repeat source \u2014 to what the Screen reads",
1135
+ args: {
1136
+ screenId: { type: "string", required: true, doc: "Screen holding it" },
1137
+ controlId: { type: "string", required: true, doc: "Control to bind" },
1138
+ slot: { type: "string", required: true, doc: "Binding slot, e.g. `label`, `value`, `source`" },
1139
+ binding: {
1140
+ type: "object",
1141
+ doc: "A DataBinding from the candidates; absent or null clears the slot. A refusal lists the candidates."
1142
+ }
1143
+ },
1144
+ run: (ctx, { screenId, controlId, slot, binding }) => {
1145
+ const screen = ctx.screenOf(screenId);
1146
+ if (!screen) return refuse3("screen-missing");
1147
+ const control = screen.state.controlMap[controlId];
1148
+ if (!control) return refuse3("control-missing");
1149
+ if (cascadingSlot(control, slot))
1150
+ return refuse3("slot-needs-editor", { type: control.type, slot });
1151
+ const { resolve } = bindingScopesOf(ctx.source, screen, controlId);
1152
+ if (binding) {
1153
+ const candidates = bindingCandidates(ctx.source, screen, controlId, slot);
1154
+ const wanted = (0, import_codegen8.encodeBinding)(binding);
1155
+ if (!candidates.some((option) => (0, import_codegen8.encodeBinding)(option.binding) === wanted))
1156
+ return refuse3("binding-unfit", {
1157
+ want: slotWant(control, slot),
1158
+ candidates: candidates.map(({ label, binding: offered }) => ({ label, binding: offered }))
1159
+ });
1160
+ }
1161
+ const next = boundControl(control, slot, binding ?? void 0, resolve);
1162
+ const notes = [
1163
+ ...control.repeat?.track && !next.repeat?.track ? ["dropped the Repeat track key the new source no longer carries"] : [],
1164
+ ...control.configs?.[import_codegen8.ACTION_SELECTION_KEY] !== void 0 && next.configs?.[import_codegen8.ACTION_SELECTION_KEY] === void 0 ? ["dropped the static pick for the bound one"] : []
1165
+ ];
1166
+ return {
1167
+ ok: true,
1168
+ notes,
1169
+ patch: {
1170
+ screens: {
1171
+ [screenId]: {
1172
+ ...screen,
1173
+ state: {
1174
+ ...screen.state,
1175
+ controlMap: { ...screen.state.controlMap, [controlId]: next }
1176
+ }
1177
+ }
1178
+ }
1179
+ }
1180
+ };
1181
+ }
1182
+ };
1183
+
1184
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/function-gestures.ts
1185
+ var import_codegen12 = require("./index.js");
1186
+
1187
+ // apps/m-one-ui/src/app/pages/design/lib/function-holders.ts
1188
+ var import_codegen9 = require("./index.js");
1189
+ function mentionsFunction(value, functionId) {
1190
+ if (Array.isArray(value)) {
1191
+ return value.some((entry) => mentionsFunction(entry, functionId));
1192
+ }
1193
+ if (!value || typeof value !== "object") return false;
1194
+ const record = value;
1195
+ if (record["functionId"] === functionId) return true;
1196
+ return Object.values(record).some(
1197
+ (entry) => mentionsFunction(entry, functionId)
1198
+ );
1199
+ }
1200
+ var without = (value, keys) => Object.fromEntries(
1201
+ Object.entries(value).filter(([key]) => !keys.includes(key))
1202
+ );
1203
+ var membersNaming = (map, functionId) => Object.values(map ?? {}).filter((member) => mentionsFunction(member, functionId)).sort((a, b) => a.name.localeCompare(b.name));
1204
+ function functionHolders(functionId, scope) {
1205
+ const holders = [];
1206
+ for (const feature of Object.values(scope.features)) {
1207
+ const at = { where: feature.name, featureId: feature.id };
1208
+ const stores = [
1209
+ { subStoreId: void 0, store: feature },
1210
+ ...Object.values(feature.subStores ?? {}).map((store) => ({
1211
+ subStoreId: store.id,
1212
+ store
1213
+ }))
1214
+ ];
1215
+ for (const { subStoreId, store } of stores) {
1216
+ const on = subStoreId ? { ...at, subStoreId } : at;
1217
+ membersNaming(store.computeds, functionId).forEach(
1218
+ (member) => holders.push({ kind: "state-computed", name: member.name, ...on })
1219
+ );
1220
+ membersNaming(store.methods, functionId).forEach(
1221
+ (member) => holders.push({ kind: "store-method", name: member.name, ...on })
1222
+ );
1223
+ }
1224
+ const rest = without(feature, [
1225
+ "functions",
1226
+ "shapes",
1227
+ "computeds",
1228
+ "methods",
1229
+ "subStores"
1230
+ ]);
1231
+ const restOfSubStores = Object.values(feature.subStores ?? {}).map(
1232
+ (store) => without(store, ["computeds", "methods"])
1233
+ );
1234
+ if (mentionsFunction([rest, restOfSubStores], functionId)) {
1235
+ holders.push({ kind: "feature", name: feature.name, ...at });
1236
+ }
1237
+ }
1238
+ const screenById = new Map(
1239
+ scope.screens.map((screen) => [screen.id, screen])
1240
+ );
1241
+ for (const screen of scope.screens) {
1242
+ const at = {
1243
+ where: screen.name,
1244
+ screenId: screen.id,
1245
+ ...screen.featureId ? { featureId: screen.featureId } : {}
1246
+ };
1247
+ membersNaming(screen.computeds, functionId).forEach(
1248
+ (member) => holders.push({ kind: "screen-computed", name: member.name, ...at })
1249
+ );
1250
+ membersNaming(screen.methods, functionId).forEach(
1251
+ (member) => holders.push({ kind: "screen-method", name: member.name, ...at })
1252
+ );
1253
+ if (mentionsFunction(without(screen, ["computeds", "methods"]), functionId)) {
1254
+ holders.push({ kind: "screen", name: screen.name, ...at });
1255
+ }
1256
+ }
1257
+ for (const { screenId, controlMap } of scope.controlMaps) {
1258
+ const screen = screenById.get(screenId);
1259
+ if (!screen) continue;
1260
+ for (const [controlId, control] of Object.entries(controlMap)) {
1261
+ if (!mentionsFunction(control, functionId)) continue;
1262
+ const checks = (0, import_codegen9.fieldChecks)(control).some(
1263
+ (check) => check.functionId === functionId
1264
+ );
1265
+ holders.push({
1266
+ kind: checks ? "field-check" : "control",
1267
+ name: (0, import_codegen9.resolveFieldName)({ id: controlId, configs: control.configs }),
1268
+ where: screen.name,
1269
+ screenId,
1270
+ controlId,
1271
+ ...screen.featureId ? { featureId: screen.featureId } : {}
1272
+ });
1273
+ }
1274
+ }
1275
+ for (const nav of Object.values(scope.navMap)) {
1276
+ const at = { name: nav.navId, where: nav.navId, navId: nav.navId };
1277
+ const visibility = nav.visibilitySource;
1278
+ const instance = nav.instanceSource;
1279
+ if (visibility && mentionsFunction(visibility, functionId)) {
1280
+ holders.push({
1281
+ kind: "nav-visibility",
1282
+ ...at,
1283
+ ...visibility.featureId ? { featureId: visibility.featureId } : {}
1284
+ });
1285
+ }
1286
+ if (instance && mentionsFunction(instance, functionId)) {
1287
+ holders.push({
1288
+ kind: "nav-instance",
1289
+ ...at,
1290
+ ...instance.featureId ? { featureId: instance.featureId } : {}
1291
+ });
1292
+ }
1293
+ const rest = without(nav, ["visibilitySource", "instanceSource"]);
1294
+ if (mentionsFunction(rest, functionId)) {
1295
+ holders.push({ kind: "nav", ...at });
1296
+ }
1297
+ }
1298
+ return holders;
1299
+ }
1300
+ function rebindFunction(value, from, to, paramIds) {
1301
+ if (Array.isArray(value)) {
1302
+ let changed = false;
1303
+ const next2 = value.map((entry) => {
1304
+ const rebound = rebindFunction(entry, from, to, paramIds);
1305
+ if (rebound !== entry) changed = true;
1306
+ return rebound;
1307
+ });
1308
+ return changed ? next2 : value;
1309
+ }
1310
+ if (!value || typeof value !== "object") return value;
1311
+ const record = value;
1312
+ let next;
1313
+ for (const [key, entry] of Object.entries(record)) {
1314
+ const rebound = rebindFunction(entry, from, to, paramIds);
1315
+ if (rebound === entry) continue;
1316
+ next ??= { ...record };
1317
+ next[key] = rebound;
1318
+ }
1319
+ if (record["functionId"] === from) {
1320
+ next ??= { ...record };
1321
+ next["functionId"] = to;
1322
+ const args = next["args"];
1323
+ if (args && typeof args === "object" && !Array.isArray(args)) {
1324
+ next["args"] = Object.fromEntries(
1325
+ Object.entries(args).map(([paramId, source]) => [
1326
+ paramIds.get(paramId) ?? paramId,
1327
+ source
1328
+ ])
1329
+ );
1330
+ }
1331
+ }
1332
+ return next ?? value;
1333
+ }
1334
+
1335
+ // apps/m-one-ui/src/app/pages/design/lib/function-register.ts
1336
+ var import_codegen11 = require("./index.js");
1337
+
1338
+ // apps/m-one-ui/src/app/pages/design/lib/code-tree.ts
1339
+ var import_codegen10 = require("./index.js");
1340
+ var CODE_AREA_ROOTS = [
1341
+ ["pages", `${import_codegen10.PAGES_ROOT}/`],
1342
+ ["features", `${import_codegen10.FEATURES_ROOT}/`],
1343
+ ["widgets", `${import_codegen10.WIDGETS_ROOT}/`],
1344
+ ["shared", "src/app/shared/"],
1345
+ ["mag_assets", "mag_assets/"],
1346
+ ["magmonium", ".magmonium/"]
1347
+ ];
1348
+
1349
+ // apps/m-one-ui/src/app/pages/design/lib/function-register.ts
1350
+ var canonical = (value) => {
1351
+ if (Array.isArray(value)) return value.map(canonical);
1352
+ if (!value || typeof value !== "object") return value;
1353
+ return Object.fromEntries(
1354
+ Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, canonical(entry)])
1355
+ );
1356
+ };
1357
+ var looseSignatureKey = (fn) => JSON.stringify(
1358
+ canonical([
1359
+ fn.params.map((param) => [param.dataType, param.cardinality]),
1360
+ fn.returnType,
1361
+ fn.returnCardinality,
1362
+ fn.returnUndefined === true,
1363
+ fn.returnAsync === true
1364
+ ])
1365
+ );
1366
+ var standsInFor = (candidate, target) => looseSignatureKey(candidate) === looseSignatureKey(target) && target.params.every(
1367
+ (param, index) => param.acceptsUndefined !== true || candidate.params[index]?.acceptsUndefined === true
1368
+ );
1369
+ var reachesHolders = (candidate, holders) => !candidate.featureId || holders.every((holder) => holder.featureId === candidate.featureId);
1370
+ var paramIdMap = (from, to) => new Map(
1371
+ from.params.flatMap((param, index) => {
1372
+ const next = to.params[index];
1373
+ return next ? [[param.id, next.id]] : [];
1374
+ })
1375
+ );
1376
+
1377
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/function-gestures.ts
1378
+ var functionFeatureOf = (homes, id) => Object.values(homes.features).find((feature) => !!feature.functions?.[id])?.id;
1379
+ var storedFunction = (homes, id) => {
1380
+ const onApp = homes.functions[id];
1381
+ if (onApp) return onApp;
1382
+ const owner = functionFeatureOf(homes, id);
1383
+ return owner ? homes.features[owner]?.functions?.[id] : void 0;
1384
+ };
1385
+ var functionHomeOf = (homes, fn) => {
1386
+ const stored = functionFeatureOf(homes, fn.id);
1387
+ if (stored) return stored;
1388
+ const shapeIds = (0, import_codegen12.featureShapeIds)(fn);
1389
+ if (!shapeIds.length) return void 0;
1390
+ return Object.values(homes.features).find(
1391
+ (feature) => shapeIds.some((shapeId) => !!feature.shapes[shapeId])
1392
+ )?.id;
1393
+ };
1394
+ function functionNameClash(homes, fn, featureId, except) {
1395
+ const holds = (map) => Object.values(map ?? {}).some(
1396
+ (entry) => entry.name === fn.name && entry.id !== fn.id && entry.id !== except
1397
+ );
1398
+ if (featureId) {
1399
+ if (holds(homes.features[featureId]?.functions)) return "function-name-taken";
1400
+ return holds(homes.functions) ? "function-name-shadows-app" : void 0;
1401
+ }
1402
+ if (holds(homes.functions)) return "function-name-taken";
1403
+ return Object.values(homes.features).some((feature) => holds(feature.functions)) ? "function-name-shadowed" : void 0;
1404
+ }
1405
+ function functionLanding(homes, fn, featureId, fallbackFeatureId) {
1406
+ const home = featureId === void 0 ? functionHomeOf(homes, fn) ?? fallbackFeatureId : featureId;
1407
+ const feature = home ? homes.features[home] : void 0;
1408
+ const wasFeature = !!feature?.functions?.[fn.id];
1409
+ const wasApp = !!homes.functions[fn.id];
1410
+ const nowFeature = (0, import_codegen12.tierOf)(fn) === "feature";
1411
+ const landing = { feature, wasFeature, wasApp, nowFeature };
1412
+ if (!(0, import_codegen12.isPureFunctionComplete)(fn)) return { ...landing, refusal: "function-incomplete" };
1413
+ if (nowFeature && !feature) return { ...landing, refusal: "function-no-feature" };
1414
+ const moving = nowFeature ? wasApp : wasFeature;
1415
+ const clash = moving ? functionNameClash(homes, fn, nowFeature ? feature?.id : void 0) : void 0;
1416
+ return clash ? { ...landing, refusal: clash } : landing;
1417
+ }
1418
+ function savedFunctionHomes(homes, fn, landing) {
1419
+ const { feature, wasFeature, wasApp, nowFeature } = landing;
1420
+ const functions = { ...homes.functions };
1421
+ const features = { ...homes.features };
1422
+ if (wasApp && nowFeature) delete functions[fn.id];
1423
+ if (wasFeature && !nowFeature && feature) {
1424
+ const remaining = { ...feature.functions ?? {} };
1425
+ delete remaining[fn.id];
1426
+ features[feature.id] = { ...feature, functions: remaining };
1427
+ }
1428
+ if (nowFeature && feature) {
1429
+ features[feature.id] = { ...feature, functions: { ...feature.functions ?? {}, [fn.id]: fn } };
1430
+ } else {
1431
+ functions[fn.id] = fn;
1432
+ }
1433
+ return { functions, features };
1434
+ }
1435
+ function deletedFunctionHomes(homes, id) {
1436
+ const ownerId = functionFeatureOf(homes, id);
1437
+ const feature = ownerId ? homes.features[ownerId] : void 0;
1438
+ if (feature?.functions?.[id]) {
1439
+ const functions2 = { ...feature.functions };
1440
+ delete functions2[id];
1441
+ return { functions: homes.functions, features: { ...homes.features, [feature.id]: { ...feature, functions: functions2 } } };
1442
+ }
1443
+ const functions = { ...homes.functions };
1444
+ delete functions[id];
1445
+ return { functions, features: homes.features };
1446
+ }
1447
+ var holderScopeOf = (source) => ({
1448
+ features: source.features,
1449
+ screens: source.screens.map(({ meta }) => meta),
1450
+ controlMaps: source.screens.map(({ meta, state }) => ({ screenId: meta.id, controlMap: state.controlMap })),
1451
+ navMap: source.navMap
1452
+ });
1453
+ function planFunctionReplace(homes, fromId, toId, holders) {
1454
+ const from = storedFunction(homes, fromId);
1455
+ const to = storedFunction(homes, toId);
1456
+ if (!from || !to || from.id === to.id) return { refusal: "function-missing" };
1457
+ if (!standsInFor(to, from)) return { refusal: "signature-differs" };
1458
+ const fromFeatureId = functionFeatureOf(homes, fromId);
1459
+ const toFeatureId = functionFeatureOf(homes, toId);
1460
+ if (!reachesHolders({ fn: to, featureId: toFeatureId }, holders))
1461
+ return { refusal: "holders-unreached" };
1462
+ const survivor = { ...to, name: from.name };
1463
+ const clash = functionNameClash(homes, survivor, toFeatureId, fromId);
1464
+ if (clash) return { refusal: clash };
1465
+ const paramIds = paramIdMap(from, to);
1466
+ const rebind = (value) => rebindFunction(value, fromId, toId, paramIds);
1467
+ const features = Object.fromEntries(
1468
+ Object.entries(rebind(homes.features)).map(([id, feature]) => {
1469
+ let functions2 = feature.functions ?? {};
1470
+ if (id === fromFeatureId) {
1471
+ functions2 = { ...functions2 };
1472
+ delete functions2[fromId];
1473
+ }
1474
+ if (id === toFeatureId) functions2 = { ...functions2, [toId]: survivor };
1475
+ return [id, { ...feature, functions: functions2 }];
1476
+ })
1477
+ );
1478
+ const functions = { ...homes.functions };
1479
+ if (!fromFeatureId) delete functions[fromId];
1480
+ if (!toFeatureId) functions[toId] = survivor;
1481
+ return { rebind, homes: { functions, features } };
1482
+ }
1483
+ var bodyCheck;
1484
+ var setFunctionBodyCheck = (check) => {
1485
+ const previous = bodyCheck;
1486
+ bodyCheck = check;
1487
+ return previous;
1488
+ };
1489
+ var refuse4 = (reason, detail) => ({
1490
+ ok: false,
1491
+ notes: [],
1492
+ refusal: detail ? { reason, detail } : { reason }
1493
+ });
1494
+ var homesOf = (source) => ({
1495
+ functions: source.functions,
1496
+ features: source.features
1497
+ });
1498
+ var functionSave = {
1499
+ name: "function-save",
1500
+ summary: "Write one PureFunction whole \u2014 create, edit, rename \u2014 landing on the tier its signature names",
1501
+ args: {
1502
+ fn: {
1503
+ type: "object",
1504
+ required: true,
1505
+ doc: "The whole PureFunction (id, name, params, returnType, returnCardinality, body, \u2026); a new one carries a fresh id"
1506
+ },
1507
+ featureId: {
1508
+ type: "string",
1509
+ doc: "Feature a Feature-tier function lands on; absent = its own home"
1510
+ }
1511
+ },
1512
+ run: (ctx, { fn, featureId }) => {
1513
+ const homes = homesOf(ctx.source);
1514
+ const nameError = (0, import_codegen12.isValidFunctionName)(fn.name) ? void 0 : "function-name-invalid";
1515
+ if (nameError) return refuse4(nameError);
1516
+ const landing = functionLanding(homes, fn, featureId);
1517
+ if (landing.refusal) return refuse4(landing.refusal);
1518
+ const home = landing.nowFeature ? landing.feature?.id : void 0;
1519
+ const clash = functionNameClash(homes, fn, home);
1520
+ if (clash) return refuse4(clash);
1521
+ const problems = bodyCheck?.(ctx.source, fn, home);
1522
+ if (problems?.length) return refuse4("function-body-invalid", { problems });
1523
+ const moved = landing.nowFeature ? landing.wasApp : landing.wasFeature;
1524
+ const next = savedFunctionHomes(homes, fn, landing);
1525
+ return {
1526
+ ok: true,
1527
+ notes: [
1528
+ ...moved ? [`moved to ${landing.nowFeature ? `Feature ${home}` : "shared"}`] : [],
1529
+ ...bodyCheck ? [] : ["body not compiled \u2014 no TypeScript checker registered"]
1530
+ ],
1531
+ patch: next
1532
+ };
1533
+ }
1534
+ };
1535
+ var functionDelete = {
1536
+ name: "function-delete",
1537
+ summary: "Delete a PureFunction nothing uses (refused while Used-by holds anything)",
1538
+ args: { functionId: { type: "string", required: true, doc: "The PureFunction" } },
1539
+ run: (ctx, { functionId }) => {
1540
+ const homes = homesOf(ctx.source);
1541
+ if (!storedFunction(homes, functionId)) return refuse4("function-missing");
1542
+ const holders = functionHolders(functionId, holderScopeOf(ctx.source));
1543
+ if (holders.length) return refuse4("function-in-use", { holders });
1544
+ return { ok: true, notes: [], patch: deletedFunctionHomes(homes, functionId) };
1545
+ }
1546
+ };
1547
+ var functionReplace = {
1548
+ name: "function-replace",
1549
+ summary: "Retire a PureFunction into another of the same signature: every holder rebound, the survivor takes the retired name",
1550
+ args: {
1551
+ fromId: { type: "string", required: true, doc: "The function to retire" },
1552
+ toId: { type: "string", required: true, doc: "The function standing in" }
1553
+ },
1554
+ run: (ctx, { fromId, toId }) => {
1555
+ const homes = homesOf(ctx.source);
1556
+ const holders = functionHolders(fromId, holderScopeOf(ctx.source));
1557
+ const plan = planFunctionReplace(homes, fromId, toId, holders);
1558
+ if (plan.refusal || !plan.rebind || !plan.homes) return refuse4(plan.refusal ?? "function-missing");
1559
+ const rebind = plan.rebind;
1560
+ return {
1561
+ ok: true,
1562
+ notes: [`rebound ${holders.length} holder(s)`],
1563
+ patch: {
1564
+ ...plan.homes,
1565
+ navMap: rebind(ctx.source.navMap),
1566
+ screens: Object.fromEntries(
1567
+ ctx.source.screens.map((slot) => [
1568
+ slot.meta.id,
1569
+ {
1570
+ meta: rebind(slot.meta),
1571
+ state: { ...slot.state, controlMap: rebind(slot.state.controlMap) }
1572
+ }
1573
+ ])
1574
+ )
1575
+ }
1576
+ };
1577
+ }
1578
+ };
1579
+
1580
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/screen-gestures.ts
1581
+ var import_codegen14 = require("./index.js");
1582
+
1583
+ // apps/m-one-ui/src/app/pages/design/lib/screen-move-helper.ts
1584
+ var import_codegen13 = require("./index.js");
1585
+ var isMovableScreen = (screen) => screen.kind === "page" || screen.kind === "app_widget";
1586
+ function screenMoveBlockers(screen, featureId, maps, screens, navMap) {
1587
+ if (!isMovableScreen(screen)) return [];
1588
+ const blockers = [];
1589
+ const moved = { ...screen, kind: "feature", featureId };
1590
+ const byId = new Map(screens.map((entry) => [entry.id, entry]));
1591
+ const navIds = (0, import_codegen13.navsReferencingScreen)(navMap, screen.id, "component");
1592
+ if (navIds.length) blockers.push({ kind: "nav-bound", navIds });
1593
+ const embeds = embeddedScreenIds(maps[screen.id] ?? {}).filter((id) => {
1594
+ const target = byId.get(id);
1595
+ return !!target && !(0, import_codegen13.canEmbedScreen)(moved, target);
1596
+ });
1597
+ if (embeds.length) {
1598
+ blockers.push({ kind: "embeds", screenIds: [...new Set(embeds)].sort() });
1599
+ }
1600
+ const hosts = screensEmbedding(screen.id, maps).filter((hostId) => {
1601
+ const host = byId.get(hostId);
1602
+ return !!host && !(0, import_codegen13.canEmbedScreen)(host, moved);
1603
+ });
1604
+ if (hosts.length) blockers.push({ kind: "embedded-by", screenIds: hosts });
1605
+ const movedEdges = featureReachEdges(
1606
+ maps,
1607
+ screens.map((entry) => entry.id === screen.id ? moved : entry)
1608
+ );
1609
+ const cycled = [...featuresReachedBy(featureId, movedEdges)].filter(
1610
+ (reached) => featuresReachedBy(reached, movedEdges).has(reached)
1611
+ );
1612
+ if (cycled.length) {
1613
+ blockers.push({ kind: "feature-cycle", featureIds: cycled.sort() });
1614
+ }
1615
+ if ((0, import_codegen13.validateScreenName)(
1616
+ screen.name,
1617
+ { kind: "feature", featureId },
1618
+ screens,
1619
+ screen.id
1620
+ ) === "page-name-taken") {
1621
+ blockers.push({ kind: "name-taken" });
1622
+ }
1623
+ return blockers;
1624
+ }
1625
+
1626
+ // apps/m-one-ui/src/app/pages/design/lib/gestures/screen-gestures.ts
1627
+ function pruneEmptyFeatures(features, screens) {
1628
+ const used = new Set(
1629
+ screens.filter(import_codegen14.isFeatureScreen).map((screen) => screen.featureId)
1630
+ );
1631
+ return Object.fromEntries(
1632
+ Object.entries(features).filter(([id]) => used.has(id))
1633
+ );
1634
+ }
1635
+ function stripUnknownVariants(controlMap, variants) {
1636
+ return Object.values(controlMap).reduce((map, control) => {
1637
+ const kept = (control.variants ?? []).filter(
1638
+ (entry) => (0, import_codegen14.isKnownVariantId)(entry.id, variants)
1639
+ );
1640
+ map[control.id] = kept.length === (control.variants ?? []).length ? control : {
1641
+ ...control,
1642
+ ...kept.length ? { variants: kept } : { variants: void 0 }
1643
+ };
1644
+ return map;
1645
+ }, {});
1646
+ }
1647
+ var screenMove = {
1648
+ name: "screen-move",
1649
+ summary: "File a Page or App Widget under a Feature (Move Screen)",
1650
+ args: {
1651
+ screenId: { type: "string", required: true, doc: "The Page or App Widget" },
1652
+ featureId: { type: "string", required: true, doc: "An existing Feature" }
1653
+ },
1654
+ run: (ctx, { screenId, featureId }) => {
1655
+ const slot = ctx.screenOf(screenId);
1656
+ if (!slot)
1657
+ return { ok: false, notes: [], refusal: { reason: "screen-missing" } };
1658
+ if (!isMovableScreen(slot.meta))
1659
+ return { ok: false, notes: [], refusal: { reason: "screen-not-movable" } };
1660
+ if (!ctx.source.features[featureId])
1661
+ return { ok: false, notes: [], refusal: { reason: "feature-missing" } };
1662
+ const blockers = screenMoveBlockers(
1663
+ slot.meta,
1664
+ featureId,
1665
+ Object.fromEntries(
1666
+ ctx.source.screens.map(({ meta, state }) => [meta.id, state.controlMap])
1667
+ ),
1668
+ ctx.source.screens.map(({ meta }) => meta),
1669
+ ctx.source.navMap
1670
+ );
1671
+ if (blockers.length)
1672
+ return {
1673
+ ok: false,
1674
+ notes: [],
1675
+ refusal: { reason: "screen-move-blocked", detail: { blockers } }
1676
+ };
1677
+ return {
1678
+ ok: true,
1679
+ notes: [],
1680
+ patch: {
1681
+ screens: {
1682
+ [screenId]: {
1683
+ ...slot,
1684
+ meta: { ...slot.meta, kind: "feature", featureId }
1685
+ }
1686
+ }
1687
+ }
1688
+ };
1689
+ }
1690
+ };
1691
+ var screenRefile = {
1692
+ name: "screen-refile",
1693
+ summary: "Rename a Screen, or move a Feature Screen to another Feature",
1694
+ args: {
1695
+ screenId: { type: "string", required: true, doc: "Any Screen" },
1696
+ name: { type: "string", required: true, doc: "Dash-case name" },
1697
+ featureId: {
1698
+ type: "string",
1699
+ doc: "Feature Screens only: the Feature to file it under"
1700
+ }
1701
+ },
1702
+ run: (ctx, { screenId, name, featureId }) => {
1703
+ const slot = ctx.screenOf(screenId);
1704
+ if (!slot)
1705
+ return { ok: false, notes: [], refusal: { reason: "screen-missing" } };
1706
+ const screens = ctx.source.screens.map(({ meta: meta2 }) => meta2);
1707
+ const feature = (0, import_codegen14.isFeatureScreen)(slot.meta);
1708
+ const destination = feature ? featureId ?? slot.meta.featureId : void 0;
1709
+ if (feature && (!destination || !ctx.source.features[destination]))
1710
+ return { ok: false, notes: [], refusal: { reason: "feature-missing" } };
1711
+ const nameError = (0, import_codegen14.validateScreenName)(
1712
+ name,
1713
+ destination ? { kind: "feature", featureId: destination } : { kind: slot.meta.kind },
1714
+ screens,
1715
+ screenId
1716
+ );
1717
+ if (nameError) return { ok: false, notes: [], refusal: { reason: nameError } };
1718
+ if (!feature || destination === slot.meta.featureId)
1719
+ return {
1720
+ ok: true,
1721
+ notes: [],
1722
+ patch: { screens: { [screenId]: { ...slot, meta: { ...slot.meta, name } } } }
1723
+ };
1724
+ const target = destination;
1725
+ const meta = { ...slot.meta, name, featureId: target, kind: "feature" };
1726
+ const nextScreens = screens.map((entry) => entry.id === screenId ? meta : entry);
1727
+ const features = pruneEmptyFeatures(ctx.source.features, nextScreens);
1728
+ const pruned = Object.keys(ctx.source.features).filter((id) => !features[id]);
1729
+ const controlMap = stripUnknownVariants(
1730
+ slot.state.controlMap,
1731
+ ctx.source.features[target].variants ?? {}
1732
+ );
1733
+ const stripped = Object.keys(controlMap).filter(
1734
+ (id) => controlMap[id] !== slot.state.controlMap[id]
1735
+ );
1736
+ return {
1737
+ ok: true,
1738
+ notes: [
1739
+ ...stripped.length ? [`stripped unknown variants from ${stripped.length} Control(s)`] : [],
1740
+ ...pruned.map((id) => `removed emptied Feature ${id}`)
1741
+ ],
1742
+ patch: {
1743
+ screens: { [screenId]: { meta, state: { ...slot.state, controlMap } } },
1744
+ features
1745
+ }
1746
+ };
1747
+ }
1748
+ };
1749
+
1750
+ // apps/m-one-ui/src/app/pages/design/lib/function-check.ts
1751
+ var import_codegen15 = require("./index.js");
1752
+
1753
+ // apps/m-one-ui/src/app/pages/design/lib/pure-lib.ts
1754
+ var PURE_LIB_FILE = "pure.lib.d.ts";
1755
+ var PURE_LIB = `
1756
+ interface Boolean { valueOf(): boolean; }
1757
+ interface Function { readonly length: number; readonly name: string; }
1758
+ interface IArguments {}
1759
+ interface RegExp {
1760
+ test(string: string): boolean;
1761
+ exec(string: string): RegExpExecArray | null;
1762
+ readonly source: string;
1763
+ readonly flags: string;
1764
+ }
1765
+ interface RegExpExecArray extends Array<string> { index: number; input: string; }
1766
+ interface RegExpMatchArray extends Array<string> { index?: number; input?: string; }
1767
+ interface Object {
1768
+ toString(): string;
1769
+ valueOf(): Object;
1770
+ hasOwnProperty(v: string): boolean;
1771
+ }
1772
+ interface ObjectConstructor {
1773
+ keys(o: object): string[];
1774
+ values<T>(o: { [s: string]: T } | ArrayLike<T>): T[];
1775
+ entries<T>(o: { [s: string]: T } | ArrayLike<T>): [string, T][];
1776
+ fromEntries<T>(entries: Iterable<readonly [PropertyKey, T]>): { [k: string]: T };
1777
+ assign<T, U>(target: T, source: U): T & U;
1778
+ freeze<T>(o: T): Readonly<T>;
1779
+ }
1780
+ declare var Object: ObjectConstructor;
1781
+
1782
+ interface String {
1783
+ readonly length: number;
1784
+ charAt(pos: number): string;
1785
+ charCodeAt(index: number): number;
1786
+ codePointAt(pos: number): number | undefined;
1787
+ concat(...strings: string[]): string;
1788
+ endsWith(searchString: string, endPosition?: number): boolean;
1789
+ includes(searchString: string, position?: number): boolean;
1790
+ indexOf(searchString: string, position?: number): number;
1791
+ lastIndexOf(searchString: string, position?: number): number;
1792
+ localeCompare(that: string): number;
1793
+ match(regexp: string | RegExp): RegExpMatchArray | null;
1794
+ normalize(form?: string): string;
1795
+ padEnd(maxLength: number, fillString?: string): string;
1796
+ padStart(maxLength: number, fillString?: string): string;
1797
+ repeat(count: number): string;
1798
+ replace(searchValue: string | RegExp, replaceValue: string): string;
1799
+ replaceAll(searchValue: string | RegExp, replaceValue: string): string;
1800
+ search(regexp: string | RegExp): number;
1801
+ slice(start?: number, end?: number): string;
1802
+ split(separator: string | RegExp, limit?: number): string[];
1803
+ startsWith(searchString: string, position?: number): boolean;
1804
+ substring(start: number, end?: number): string;
1805
+ toLowerCase(): string;
1806
+ toUpperCase(): string;
1807
+ toLocaleLowerCase(locales?: string | string[]): string;
1808
+ toLocaleUpperCase(locales?: string | string[]): string;
1809
+ trim(): string;
1810
+ trimStart(): string;
1811
+ trimEnd(): string;
1812
+ toString(): string;
1813
+ valueOf(): string;
1814
+ readonly [index: number]: string;
1815
+ }
1816
+ interface StringConstructor {
1817
+ (value?: unknown): string;
1818
+ fromCharCode(...codes: number[]): string;
1819
+ raw(template: { raw: readonly string[] | ArrayLike<string> }, ...substitutions: unknown[]): string;
1820
+ }
1821
+ declare var String: StringConstructor;
1822
+
1823
+ interface Number {
1824
+ toExponential(fractionDigits?: number): string;
1825
+ toFixed(digits?: number): string;
1826
+ toPrecision(precision?: number): string;
1827
+ toString(radix?: number): string;
1828
+ toLocaleString(locales?: string | string[], options?: object): string;
1829
+ valueOf(): number;
1830
+ }
1831
+ interface NumberConstructor {
1832
+ (value?: unknown): number;
1833
+ readonly MAX_SAFE_INTEGER: number;
1834
+ readonly MIN_SAFE_INTEGER: number;
1835
+ readonly MAX_VALUE: number;
1836
+ readonly MIN_VALUE: number;
1837
+ readonly EPSILON: number;
1838
+ readonly POSITIVE_INFINITY: number;
1839
+ readonly NEGATIVE_INFINITY: number;
1840
+ readonly NaN: number;
1841
+ isFinite(number: unknown): boolean;
1842
+ isInteger(number: unknown): boolean;
1843
+ isNaN(number: unknown): boolean;
1844
+ isSafeInteger(number: unknown): boolean;
1845
+ parseFloat(string: string): number;
1846
+ parseInt(string: string, radix?: number): number;
1847
+ }
1848
+ declare var Number: NumberConstructor;
1849
+
1850
+ interface BooleanConstructor { (value?: unknown): boolean; }
1851
+ declare var Boolean: BooleanConstructor;
1852
+
1853
+ interface Math {
1854
+ readonly E: number;
1855
+ readonly LN10: number;
1856
+ readonly LN2: number;
1857
+ readonly PI: number;
1858
+ readonly SQRT2: number;
1859
+ abs(x: number): number;
1860
+ ceil(x: number): number;
1861
+ floor(x: number): number;
1862
+ round(x: number): number;
1863
+ trunc(x: number): number;
1864
+ sign(x: number): number;
1865
+ max(...values: number[]): number;
1866
+ min(...values: number[]): number;
1867
+ pow(x: number, y: number): number;
1868
+ sqrt(x: number): number;
1869
+ cbrt(x: number): number;
1870
+ log(x: number): number;
1871
+ log2(x: number): number;
1872
+ log10(x: number): number;
1873
+ exp(x: number): number;
1874
+ hypot(...values: number[]): number;
1875
+ }
1876
+ /**
1877
+ * No \`random\`. A pure function returning a different value on each call is not
1878
+ * one, and a \`Math.random()\` inside a \`computed()\` would not recompute anyway
1879
+ * \u2014 signals track dependencies and entropy is not one.
1880
+ */
1881
+ declare var Math: Math;
1882
+
1883
+ /**
1884
+ * Reading the clock is admitted (ADR 0199): \`today()\` is impure by nature and
1885
+ * that is accepted. Only reads and formatting are declared \u2014 no setters.
1886
+ */
1887
+ interface Date {
1888
+ getTime(): number;
1889
+ getFullYear(): number;
1890
+ getMonth(): number;
1891
+ getDate(): number;
1892
+ getDay(): number;
1893
+ getHours(): number;
1894
+ getMinutes(): number;
1895
+ getSeconds(): number;
1896
+ getMilliseconds(): number;
1897
+ getUTCFullYear(): number;
1898
+ getUTCMonth(): number;
1899
+ getUTCDate(): number;
1900
+ getUTCDay(): number;
1901
+ getUTCHours(): number;
1902
+ getUTCMinutes(): number;
1903
+ getUTCSeconds(): number;
1904
+ getTimezoneOffset(): number;
1905
+ toISOString(): string;
1906
+ toJSON(): string;
1907
+ toDateString(): string;
1908
+ toTimeString(): string;
1909
+ toLocaleDateString(locales?: string | string[]): string;
1910
+ toLocaleTimeString(locales?: string | string[]): string;
1911
+ toLocaleString(locales?: string | string[]): string;
1912
+ valueOf(): number;
1913
+ }
1914
+ interface DateConstructor {
1915
+ new (value?: number | string | Date): Date;
1916
+ new (year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;
1917
+ now(): number;
1918
+ parse(s: string): number;
1919
+ UTC(year: number, monthIndex?: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;
1920
+ }
1921
+ declare var Date: DateConstructor;
1922
+
1923
+ interface JSON {
1924
+ parse(text: string): unknown;
1925
+ stringify(value: unknown): string;
1926
+ }
1927
+ declare var JSON: JSON;
1928
+
1929
+ interface ArrayLike<T> { readonly length: number; readonly [n: number]: T; }
1930
+ interface ConcatArray<T> { readonly length: number; readonly [n: number]: T; join(separator?: string): string; slice(start?: number, end?: number): T[]; }
1931
+ interface Array<T> {
1932
+ length: number;
1933
+ [n: number]: T;
1934
+ concat(...items: ConcatArray<T>[]): T[];
1935
+ every(predicate: (value: T, index: number, array: T[]) => unknown): boolean;
1936
+ filter(predicate: (value: T, index: number, array: T[]) => unknown): T[];
1937
+ find(predicate: (value: T, index: number, obj: T[]) => unknown): T | undefined;
1938
+ findIndex(predicate: (value: T, index: number, obj: T[]) => unknown): number;
1939
+ flat<D extends number = 1>(depth?: D): unknown[];
1940
+ flatMap<U>(callback: (value: T, index: number, array: T[]) => U | U[]): U[];
1941
+ forEach(callbackfn: (value: T, index: number, array: T[]) => void): void;
1942
+ includes(searchElement: T, fromIndex?: number): boolean;
1943
+ indexOf(searchElement: T, fromIndex?: number): number;
1944
+ join(separator?: string): string;
1945
+ lastIndexOf(searchElement: T, fromIndex?: number): number;
1946
+ map<U>(callbackfn: (value: T, index: number, array: T[]) => U): U[];
1947
+ reduce(callbackfn: (prev: T, cur: T, index: number, array: T[]) => T): T;
1948
+ reduce<U>(callbackfn: (prev: U, cur: T, index: number, array: T[]) => U, initialValue: U): U;
1949
+ reduceRight<U>(callbackfn: (prev: U, cur: T, index: number, array: T[]) => U, initialValue: U): U;
1950
+ reverse(): T[];
1951
+ slice(start?: number, end?: number): T[];
1952
+ some(predicate: (value: T, index: number, array: T[]) => unknown): boolean;
1953
+ sort(compareFn?: (a: T, b: T) => number): this;
1954
+ at(index: number): T | undefined;
1955
+ }
1956
+ interface ReadonlyArray<T> {
1957
+ readonly length: number;
1958
+ readonly [n: number]: T;
1959
+ every(predicate: (value: T, index: number, array: readonly T[]) => unknown): boolean;
1960
+ filter(predicate: (value: T, index: number, array: readonly T[]) => unknown): T[];
1961
+ find(predicate: (value: T, index: number, obj: readonly T[]) => unknown): T | undefined;
1962
+ includes(searchElement: T, fromIndex?: number): boolean;
1963
+ indexOf(searchElement: T, fromIndex?: number): number;
1964
+ join(separator?: string): string;
1965
+ map<U>(callbackfn: (value: T, index: number, array: readonly T[]) => U): U[];
1966
+ reduce<U>(callbackfn: (prev: U, cur: T, index: number, array: readonly T[]) => U, initialValue: U): U;
1967
+ slice(start?: number, end?: number): T[];
1968
+ some(predicate: (value: T, index: number, array: readonly T[]) => unknown): boolean;
1969
+ }
1970
+ interface ArrayConstructor {
1971
+ isArray(arg: unknown): arg is unknown[];
1972
+ from<T>(arrayLike: ArrayLike<T>): T[];
1973
+ from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U): U[];
1974
+ of<T>(...items: T[]): T[];
1975
+ }
1976
+ declare var Array: ArrayConstructor;
1977
+
1978
+ interface PromiseLike<T> {
1979
+ then<R1 = T, R2 = never>(
1980
+ onfulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,
1981
+ onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null
1982
+ ): PromiseLike<R1 | R2>;
1983
+ }
1984
+ interface Promise<T> {
1985
+ then<R1 = T, R2 = never>(
1986
+ onfulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,
1987
+ onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null
1988
+ ): Promise<R1 | R2>;
1989
+ catch<R = never>(
1990
+ onrejected?: ((reason: unknown) => R | PromiseLike<R>) | null
1991
+ ): Promise<T | R>;
1992
+ finally(onfinally?: (() => void) | null): Promise<T>;
1993
+ }
1994
+ interface PromiseConstructor {
1995
+ readonly prototype: Promise<unknown>;
1996
+ new <T>(
1997
+ executor: (
1998
+ resolve: (value: T | PromiseLike<T>) => void,
1999
+ reject: (reason?: unknown) => void
2000
+ ) => void
2001
+ ): Promise<T>;
2002
+ all<T>(values: readonly (T | PromiseLike<T>)[]): Promise<T[]>;
2003
+ race<T>(values: readonly (T | PromiseLike<T>)[]): Promise<T>;
2004
+ reject<T = never>(reason?: unknown): Promise<T>;
2005
+ resolve(): Promise<void>;
2006
+ resolve<T>(value: T | PromiseLike<T>): Promise<T>;
2007
+ }
2008
+ declare var Promise: PromiseConstructor;
2009
+ interface SymbolConstructor { readonly iterator: unique symbol; }
2010
+ declare var Symbol: SymbolConstructor;
2011
+ interface IteratorYieldResult<TYield> { done?: false; value: TYield; }
2012
+ interface IteratorReturnResult<TReturn> { done: true; value: TReturn; }
2013
+ type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
2014
+ interface Iterator<T, TReturn = any, TNext = any> {
2015
+ next(...[value]: [] | [TNext]): IteratorResult<T, TReturn>;
2016
+ return?(value?: TReturn): IteratorResult<T, TReturn>;
2017
+ throw?(e?: any): IteratorResult<T, TReturn>;
2018
+ }
2019
+ interface Iterable<T, TReturn = any, TNext = any> { [Symbol.iterator](): Iterator<T, TReturn, TNext>; }
2020
+ interface IterableIterator<T, TReturn = any, TNext = any> extends Iterator<T, TReturn, TNext> {
2021
+ [Symbol.iterator](): IterableIterator<T, TReturn, TNext>;
2022
+ }
2023
+ interface IteratorObject<T, TReturn = unknown, TNext = unknown> extends Iterator<T, TReturn, TNext> {
2024
+ [Symbol.iterator](): IteratorObject<T, TReturn, TNext>;
2025
+ }
2026
+ type BuiltinIteratorReturn = any;
2027
+ interface ArrayIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> { [Symbol.iterator](): ArrayIterator<T>; }
2028
+ interface MapIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> { [Symbol.iterator](): MapIterator<T>; }
2029
+ interface SetIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> { [Symbol.iterator](): SetIterator<T>; }
2030
+ interface StringIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> { [Symbol.iterator](): StringIterator<T>; }
2031
+ interface Array<T> { [Symbol.iterator](): ArrayIterator<T>; entries(): ArrayIterator<[number, T]>; keys(): ArrayIterator<number>; values(): ArrayIterator<T>; }
2032
+ interface ReadonlyArray<T> { [Symbol.iterator](): ArrayIterator<T>; }
2033
+ interface String { [Symbol.iterator](): StringIterator<string>; }
2034
+ interface ReadonlyMap<K, V> {
2035
+ readonly size: number;
2036
+ get(key: K): V | undefined;
2037
+ has(key: K): boolean;
2038
+ forEach(callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void): void;
2039
+ keys(): MapIterator<K>;
2040
+ values(): MapIterator<V>;
2041
+ entries(): MapIterator<[K, V]>;
2042
+ [Symbol.iterator](): MapIterator<[K, V]>;
2043
+ }
2044
+ interface Map<K, V> extends ReadonlyMap<K, V> {
2045
+ set(key: K, value: V): this;
2046
+ delete(key: K): boolean;
2047
+ clear(): void;
2048
+ forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void): void;
2049
+ }
2050
+ interface MapConstructor {
2051
+ new <K, V>(entries?: Iterable<readonly [K, V]> | null): Map<K, V>;
2052
+ readonly prototype: Map<unknown, unknown>;
2053
+ }
2054
+ declare var Map: MapConstructor;
2055
+ interface ReadonlySet<T> {
2056
+ readonly size: number;
2057
+ has(value: T): boolean;
2058
+ forEach(callbackfn: (value: T, value2: T, set: ReadonlySet<T>) => void): void;
2059
+ keys(): SetIterator<T>;
2060
+ values(): SetIterator<T>;
2061
+ entries(): SetIterator<[T, T]>;
2062
+ [Symbol.iterator](): SetIterator<T>;
2063
+ }
2064
+ interface Set<T> extends ReadonlySet<T> {
2065
+ add(value: T): this;
2066
+ delete(value: T): boolean;
2067
+ clear(): void;
2068
+ forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void): void;
2069
+ }
2070
+ interface SetConstructor {
2071
+ new <T>(values?: Iterable<T> | null): Set<T>;
2072
+ readonly prototype: Set<unknown>;
2073
+ }
2074
+ declare var Set: SetConstructor;
2075
+ type PropertyKey = string | number | symbol;
2076
+ type Record<K extends PropertyKey, T> = { [P in K]: T };
2077
+ type Partial<T> = { [P in keyof T]?: T[P] };
2078
+ type Required<T> = { [P in keyof T]-?: T[P] };
2079
+ type Readonly<T> = { readonly [P in keyof T]: T[P] };
2080
+ type Pick<T, K extends keyof T> = { [P in K]: T[P] };
2081
+ type Omit<T, K extends PropertyKey> = Pick<T, Exclude<keyof T, K>>;
2082
+ type Exclude<T, U> = T extends U ? never : T;
2083
+ type Extract<T, U> = T extends U ? T : never;
2084
+ type NonNullable<T> = T & {};
2085
+
2086
+ declare function isNaN(number: number): boolean;
2087
+ declare function isFinite(number: number): boolean;
2088
+ declare function parseInt(string: string, radix?: number): number;
2089
+ declare function parseFloat(string: string): number;
2090
+ declare var NaN: number;
2091
+ declare var Infinity: number;
2092
+ declare var undefined: undefined;
2093
+ `;
2094
+
2095
+ // apps/m-one-ui/src/app/pages/design/lib/function-check.ts
2096
+ var FILE = "pure.fn.ts";
2097
+ var APP_STRICTNESS = {
2098
+ strict: true,
2099
+ noImplicitOverride: true,
2100
+ noPropertyAccessFromIndexSignature: true,
2101
+ noImplicitReturns: true,
2102
+ noFallthroughCasesInSwitch: true
2103
+ };
2104
+ function closedShapeIds(shapes, rootIds) {
2105
+ const seen = /* @__PURE__ */ new Set();
2106
+ const walk = (id) => {
2107
+ const shape = shapes[id];
2108
+ if (!shape || seen.has(id)) return;
2109
+ seen.add(id);
2110
+ (0, import_codegen15.referencedShapeIds)(shape).forEach(walk);
2111
+ };
2112
+ rootIds.forEach(walk);
2113
+ return Array.from(seen);
2114
+ }
2115
+ function ambientTypes(shapes, fn, enums) {
2116
+ const shapeSource = closedShapeIds(shapes, (0, import_codegen15.signatureShapeIds)(fn)).map((id) => shapes[id]).filter((shape) => !!shape).map((shape) => (0, import_codegen15.generateShapeInterface)(shapes, shape, { imports: false })).join("\n");
2117
+ const formSource = (0, import_codegen15.signatureFormIds)(fn).map((id) => shapes[id]).filter((shape) => !!shape).map((shape) => (0, import_codegen15.generateFormInterface)(shape)).join("\n");
2118
+ const optionSource = (0, import_codegen15.signatureNamesOptionRow)(fn) ? `interface ${import_codegen15.OPTION_ROW_TYPE_NAME} { value: string; label: string; }` : "";
2119
+ const enumSource = (0, import_codegen15.signatureEnums)(fn, enums).map(
2120
+ (entry) => `enum ${entry.name} { ${entry.values.map((value, i) => `${(0, import_codegen15.enumMemberName)(entry, i)} = '${value}'`).join(", ")} }`
2121
+ ).join("\n");
2122
+ const source = [enumSource, shapeSource, formSource, optionSource].filter(Boolean).join("\n");
2123
+ return source && !source.endsWith("\n") ? `${source}
2124
+ ` : source;
2125
+ }
2126
+ function checkFunctionBody(ts, shapes, fn, allowlist = {}, enums) {
2127
+ const early = [];
2128
+ if (/\bimport\b/.test(fn.body)) {
2129
+ early.push({
2130
+ message: "Imports belong above the signature \u2014 approve a package first, do not type import into the body.",
2131
+ line: 1,
2132
+ column: 1,
2133
+ kind: "type"
2134
+ });
2135
+ }
2136
+ for (const entry of fn.imports ?? []) {
2137
+ if (!allowlist[entry.package]) {
2138
+ early.push({
2139
+ message: `Package \`${entry.package}\` is not on the workspace allowlist \u2014 approve it before importing.`,
2140
+ line: 1,
2141
+ column: 1,
2142
+ kind: "type"
2143
+ });
2144
+ }
2145
+ }
2146
+ const source = wrap(shapes, fn, enums);
2147
+ const named = fn.name.trim() ? fn : { ...fn, name: "name" };
2148
+ const shapeSource = ambientTypes(shapes, fn, enums);
2149
+ const stubSource = (fn.imports ?? []).filter((entry) => allowlist[entry.package]).flatMap(
2150
+ (entry) => entry.names.map((name) => `declare const ${name}: any;`)
2151
+ ).join("\n");
2152
+ const stubBlock = stubSource ? `${stubSource}
2153
+ ` : "";
2154
+ const files = {
2155
+ [PURE_LIB_FILE]: PURE_LIB,
2156
+ [FILE]: `${stubBlock}${shapeSource}${source}`
2157
+ };
2158
+ const prependLines = (stubBlock ? stubBlock.split("\n").length - 1 : 0) + (shapeSource ? shapeSource.split("\n").length - 1 : 0);
2159
+ const bodyLineOffset = 1;
2160
+ const host = compilerHost(ts, files);
2161
+ const program = ts.createProgram({
2162
+ rootNames: [FILE],
2163
+ options: {
2164
+ noEmit: true,
2165
+ ...APP_STRICTNESS,
2166
+ target: ts.ScriptTarget.ES2020,
2167
+ noLib: false,
2168
+ types: [],
2169
+ skipLibCheck: false
2170
+ },
2171
+ host
2172
+ });
2173
+ const file = program.getSourceFile(FILE);
2174
+ const problems = [...early];
2175
+ [
2176
+ ...program.getSyntacticDiagnostics(file),
2177
+ ...program.getSemanticDiagnostics(file)
2178
+ ].forEach((diagnostic) => {
2179
+ const flat = ts.flattenDiagnosticMessageText(diagnostic.messageText, " ");
2180
+ if (diagnostic.start === void 0 || !diagnostic.file) {
2181
+ problems.push({ message: flat, line: 1, column: 1, kind: "type" });
2182
+ return;
2183
+ }
2184
+ const at = diagnostic.file.getLineAndCharacterOfPosition(
2185
+ diagnostic.start
2186
+ );
2187
+ problems.push({
2188
+ message: flat,
2189
+ line: Math.max(1, at.line + 1 - prependLines - bodyLineOffset),
2190
+ column: at.character + 1,
2191
+ kind: "type"
2192
+ });
2193
+ });
2194
+ if (file) {
2195
+ const bodyStart = stubBlock.length + shapeSource.length + (0, import_codegen15.signatureText)(shapes, named, enums).length + 1;
2196
+ problems.push(
2197
+ ...purity(ts, file, prependLines, bodyStart, bodyLineOffset)
2198
+ );
2199
+ }
2200
+ return problems;
2201
+ }
2202
+ function wrap(shapes, fn, enums) {
2203
+ const named = fn.name.trim() ? fn : { ...fn, name: "name" };
2204
+ return `${(0, import_codegen15.signatureText)(shapes, named, enums)}
2205
+ ${fn.body}
2206
+ };
2207
+ `;
2208
+ }
2209
+ function compilerHost(ts, files) {
2210
+ return {
2211
+ fileExists: (name) => name in files,
2212
+ readFile: (name) => files[name],
2213
+ getSourceFile: (name, languageVersion) => name in files ? ts.createSourceFile(name, files[name], languageVersion, true) : void 0,
2214
+ getDefaultLibFileName: () => PURE_LIB_FILE,
2215
+ writeFile: () => void 0,
2216
+ getCurrentDirectory: () => "",
2217
+ getDirectories: () => [],
2218
+ getCanonicalFileName: (name) => name,
2219
+ useCaseSensitiveFileNames: () => true,
2220
+ getNewLine: () => "\n"
2221
+ };
2222
+ }
2223
+ function purity(ts, file, prependLines, bodyStart, bodyLineOffset) {
2224
+ const found = [];
2225
+ const banned = new Set(
2226
+ import_codegen15.IMPURE_TOKENS.filter((token) => /^[a-zA-Z]+$/.test(token))
2227
+ );
2228
+ const report = (node, name) => {
2229
+ const at = file.getLineAndCharacterOfPosition(node.getStart(file));
2230
+ found.push({
2231
+ message: `\`${name}\` is not available in a PureFunction \u2014 a body reaches nothing but its parameters.`,
2232
+ line: Math.max(1, at.line + 1 - prependLines - bodyLineOffset),
2233
+ column: at.character + 1,
2234
+ kind: "purity"
2235
+ });
2236
+ };
2237
+ const walk = (node) => {
2238
+ if (node.getEnd() <= bodyStart) {
2239
+ ts.forEachChild(node, walk);
2240
+ return;
2241
+ }
2242
+ if (ts.isIdentifier(node) && banned.has(node.text)) {
2243
+ const parent = node.parent;
2244
+ const isMember = parent && ts.isPropertyAccessExpression(parent) && parent.name === node;
2245
+ if (!isMember) report(node, node.text);
2246
+ }
2247
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "Math" && node.name.text === "random") {
2248
+ report(node, `${node.expression.text}.${node.name.text}`);
2249
+ }
2250
+ ts.forEachChild(node, walk);
2251
+ };
2252
+ ts.forEachChild(file, walk);
2253
+ return found;
2254
+ }
2255
+ var functionBodyCheckFor = (ts) => (source, fn, featureId) => {
2256
+ const shapes = { ...source.sharedShapes };
2257
+ Object.values(source.features).forEach((feature) => Object.assign(shapes, feature.shapes));
2258
+ source.screens.forEach(({ state }) => Object.assign(shapes, (0, import_codegen15.formShapeMap)(state.controlMap)));
2259
+ const enums = featureId ? (() => {
2260
+ const found = (0, import_codegen15.controlEnums)(
2261
+ source.screens.filter(({ meta }) => (0, import_codegen15.isFeatureScreen)(meta) && meta.featureId === featureId).map(({ state }) => ({
2262
+ tree: (0, import_codegen15.buildTree)(state.controlMap, state.rootControlIds),
2263
+ controlMap: state.controlMap
2264
+ }))
2265
+ );
2266
+ return found.some((entry) => entry.library) ? found : [...found, import_codegen15.SORT_DIRECTION_ENUM];
2267
+ })() : [import_codegen15.SORT_DIRECTION_ENUM];
2268
+ return checkFunctionBody(ts, shapes, fn, source.npmAllowlist ?? {}, enums);
2269
+ };
2270
+
2271
+ // apps/m-one-ui/src/app/pages/design/lib/gesture-catalog.ts
2272
+ var GESTURES = [
2273
+ screenMove,
2274
+ screenRefile,
2275
+ controlAdd,
2276
+ controlMove,
2277
+ controlDelete,
2278
+ controlConfigs,
2279
+ screenControlTarget,
2280
+ controlBind,
2281
+ functionSave,
2282
+ functionDelete,
2283
+ functionReplace
2284
+ ];
2285
+ var gestureByName = (name) => GESTURES.find((gesture) => gesture.name === name);
2286
+ var applyGesture = (source, patch) => {
2287
+ const { screens, ...maps } = patch;
2288
+ if (!screens) return { ...source, ...maps };
2289
+ const known = new Set(source.screens.map(({ meta }) => meta.id));
2290
+ const kept = source.screens.filter(({ meta }) => screens[meta.id] !== null).map((slot) => screens[slot.meta.id] ?? slot);
2291
+ const added = Object.entries(screens).filter(([id, slot]) => slot && !known.has(id)).map(([, slot]) => slot);
2292
+ return { ...source, ...maps, screens: [...kept, ...added] };
2293
+ };
2294
+ var argsProblem = (gesture, args) => {
2295
+ const missing = Object.entries(gesture.args).filter(([key, arg]) => arg.required && args[key] === void 0).map(([key]) => key);
2296
+ return missing.length ? { reason: "args-invalid", detail: { missing } } : void 0;
2297
+ };
2298
+ var runGesture = (source, gesture, args) => {
2299
+ const problem = argsProblem(gesture, args);
2300
+ if (problem) return { ok: false, notes: [], refusal: problem };
2301
+ const result = gesture.run(gestureContextOf(source), args);
2302
+ if (!result.ok || !result.patch)
2303
+ return { ok: false, notes: result.notes, refusal: result.refusal };
2304
+ return {
2305
+ ok: true,
2306
+ notes: result.notes,
2307
+ source: applyGesture(source, result.patch)
2308
+ };
2309
+ };
2310
+ var runBatch = (source, steps) => {
2311
+ let at = source;
2312
+ const notes = [];
2313
+ for (const [index, step] of steps.entries()) {
2314
+ const run = runGesture(at, step.gesture, step.args);
2315
+ notes.push(...run.notes);
2316
+ if (!run.ok || !run.source)
2317
+ return { ok: false, notes, refusal: run.refusal, failedAt: index };
2318
+ at = run.source;
2319
+ }
2320
+ return { ok: true, notes, source: at };
2321
+ };
2322
+ // Annotate the CommonJS export names for ESM import in node:
2323
+ 0 && (module.exports = {
2324
+ GESTURES,
2325
+ applyGesture,
2326
+ functionBodyCheckFor,
2327
+ gestureByName,
2328
+ runBatch,
2329
+ runGesture,
2330
+ setFunctionBodyCheck
2331
+ });