@capgo/capacitor-widget-kit 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CapgoCapacitorWidgetKit.podspec +17 -0
  2. package/LICENSE +373 -0
  3. package/Package.swift +28 -0
  4. package/README.md +1119 -0
  5. package/android/build.gradle +59 -0
  6. package/android/src/main/AndroidManifest.xml +8 -0
  7. package/android/src/main/java/app/capgo/widgetkit/CapgoNativeWidgetBridge.java +311 -0
  8. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateActionReceiver.java +36 -0
  9. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateSvgBitmapRenderer.java +25 -0
  10. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateWidgetBridge.java +31 -0
  11. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKit.java +218 -0
  12. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKitConstants.java +18 -0
  13. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKitPlugin.java +370 -0
  14. package/android/src/main/java/app/capgo/widgetkit/TemplateActivityStore.java +167 -0
  15. package/android/src/main/java/app/capgo/widgetkit/TemplateJsonUtils.java +369 -0
  16. package/android/src/main/java/app/capgo/widgetkit/TemplateRuntime.java +676 -0
  17. package/android/src/main/res/.gitkeep +0 -0
  18. package/dist/docs.json +2223 -0
  19. package/dist/esm/definitions.d.ts +1117 -0
  20. package/dist/esm/definitions.js +2 -0
  21. package/dist/esm/definitions.js.map +1 -0
  22. package/dist/esm/helpers/workout.d.ts +32 -0
  23. package/dist/esm/helpers/workout.js +129 -0
  24. package/dist/esm/helpers/workout.js.map +1 -0
  25. package/dist/esm/index.d.ts +6 -0
  26. package/dist/esm/index.js +9 -0
  27. package/dist/esm/index.js.map +1 -0
  28. package/dist/esm/runtime.d.ts +25 -0
  29. package/dist/esm/runtime.js +653 -0
  30. package/dist/esm/runtime.js.map +1 -0
  31. package/dist/esm/web.d.ts +23 -0
  32. package/dist/esm/web.js +292 -0
  33. package/dist/esm/web.js.map +1 -0
  34. package/dist/plugin.cjs.js +1096 -0
  35. package/dist/plugin.cjs.js.map +1 -0
  36. package/dist/plugin.js +1099 -0
  37. package/dist/plugin.js.map +1 -0
  38. package/ios/Sources/CapgoWidgetKitPlugin/CapgoNativeWidgetBridge.swift +372 -0
  39. package/ios/Sources/CapgoWidgetKitPlugin/CapgoTemplateWidgetBridge.swift +199 -0
  40. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKit.swift +218 -0
  41. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKitPlugin.swift +322 -0
  42. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKitSharedStore.swift +47 -0
  43. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWorkoutLiveActivityComponents.swift +246 -0
  44. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWorkoutLiveActivityWidget.swift +257 -0
  45. package/ios/Sources/CapgoWidgetKitPlugin/CompleteSetIntent.swift +24 -0
  46. package/ios/Sources/CapgoWidgetKitPlugin/TemplateActionIntent.swift +56 -0
  47. package/ios/Sources/CapgoWidgetKitPlugin/TemplateActivityStore.swift +239 -0
  48. package/ios/Sources/CapgoWidgetKitPlugin/TemplateLiveActivityManager.swift +251 -0
  49. package/ios/Sources/CapgoWidgetKitPlugin/TemplateRuntime.swift +1067 -0
  50. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutActivityStore.swift +111 -0
  51. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutLiveActivityManager.swift +263 -0
  52. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutSession.swift +271 -0
  53. package/ios/Tests/CapgoWidgetKitPluginTests/CapgoWidgetKitPluginTests.swift +130 -0
  54. package/package.json +93 -0
@@ -0,0 +1,653 @@
1
+ const TOKEN_PATTERN = /{{\s*([^{}]+?)\s*}}/g;
2
+ const EXACT_TOKEN_PATTERN = /^{{\s*([^{}]+?)\s*}}$/;
3
+ function cloneJson(value) {
4
+ return JSON.parse(JSON.stringify(value));
5
+ }
6
+ export function toJsonValue(value) {
7
+ return cloneJson(value);
8
+ }
9
+ export function toJsonObject(value) {
10
+ return cloneJson(value);
11
+ }
12
+ function isObject(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ function isArray(value) {
16
+ return Array.isArray(value);
17
+ }
18
+ function isNumber(value) {
19
+ return typeof value === 'number' && Number.isFinite(value);
20
+ }
21
+ function isBoolean(value) {
22
+ return typeof value === 'boolean';
23
+ }
24
+ function stringifyValue(value) {
25
+ if (value == null) {
26
+ return '';
27
+ }
28
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
29
+ return String(value);
30
+ }
31
+ return JSON.stringify(value);
32
+ }
33
+ function splitPath(path) {
34
+ return path
35
+ .split('.')
36
+ .map((segment) => segment.trim())
37
+ .filter(Boolean);
38
+ }
39
+ function isIndexSegment(segment) {
40
+ return /^\d+$/.test(segment);
41
+ }
42
+ export function getValueAtPath(root, path) {
43
+ const segments = splitPath(path);
44
+ let current = root;
45
+ for (const segment of segments) {
46
+ if (isObject(current)) {
47
+ current = current[segment];
48
+ continue;
49
+ }
50
+ if (isArray(current) && isIndexSegment(segment)) {
51
+ current = current[Number(segment)];
52
+ continue;
53
+ }
54
+ return undefined;
55
+ }
56
+ return current;
57
+ }
58
+ function ensureContainer(parent, segment, nextSegment) {
59
+ const createArray = nextSegment != null && isIndexSegment(nextSegment);
60
+ if (isArray(parent) && isIndexSegment(segment)) {
61
+ const index = Number(segment);
62
+ if (parent[index] == null) {
63
+ parent[index] = createArray ? [] : {};
64
+ }
65
+ return parent[index];
66
+ }
67
+ if (isObject(parent)) {
68
+ if (parent[segment] == null) {
69
+ parent[segment] = createArray ? [] : {};
70
+ }
71
+ return parent[segment];
72
+ }
73
+ return {};
74
+ }
75
+ export function setValueAtPath(root, path, value) {
76
+ const segments = splitPath(path);
77
+ if (segments.length === 0) {
78
+ return;
79
+ }
80
+ let current = root;
81
+ for (let index = 0; index < segments.length - 1; index += 1) {
82
+ const segment = segments[index];
83
+ const next = ensureContainer(current, segment, segments[index + 1]);
84
+ if (!isObject(next) && !isArray(next)) {
85
+ const replacement = isIndexSegment(segments[index + 1]) ? [] : {};
86
+ if (isArray(current) && isIndexSegment(segment)) {
87
+ current[Number(segment)] = replacement;
88
+ }
89
+ else if (isObject(current)) {
90
+ current[segment] = replacement;
91
+ }
92
+ current = replacement;
93
+ }
94
+ else {
95
+ current = next;
96
+ }
97
+ }
98
+ const lastSegment = segments[segments.length - 1];
99
+ if (isArray(current) && isIndexSegment(lastSegment)) {
100
+ current[Number(lastSegment)] = cloneJson(value);
101
+ return;
102
+ }
103
+ if (isObject(current)) {
104
+ current[lastSegment] = cloneJson(value);
105
+ }
106
+ }
107
+ export function deleteValueAtPath(root, path) {
108
+ const segments = splitPath(path);
109
+ if (segments.length === 0) {
110
+ return;
111
+ }
112
+ let current = root;
113
+ for (let index = 0; index < segments.length - 1; index += 1) {
114
+ const segment = segments[index];
115
+ if (isObject(current)) {
116
+ current = current[segment];
117
+ continue;
118
+ }
119
+ if (isArray(current) && isIndexSegment(segment)) {
120
+ current = current[Number(segment)];
121
+ continue;
122
+ }
123
+ return;
124
+ }
125
+ const lastSegment = segments[segments.length - 1];
126
+ if (isObject(current)) {
127
+ delete current[lastSegment];
128
+ }
129
+ else if (isArray(current) && isIndexSegment(lastSegment)) {
130
+ current.splice(Number(lastSegment), 1);
131
+ }
132
+ }
133
+ function coerceInt(value) {
134
+ if (isNumber(value)) {
135
+ return Math.round(value);
136
+ }
137
+ if (typeof value === 'string' && value.trim() !== '') {
138
+ const parsed = Number(value);
139
+ return Number.isFinite(parsed) ? Math.round(parsed) : undefined;
140
+ }
141
+ return undefined;
142
+ }
143
+ function timerElapsedMs(timer, nowMs) {
144
+ var _a;
145
+ const savedElapsedMs = Math.max(0, Math.round((_a = timer.elapsedMs) !== null && _a !== void 0 ? _a : 0));
146
+ if (timer.status === 'finished' && timer.durationMs > 0) {
147
+ return timer.durationMs;
148
+ }
149
+ if (timer.status === 'running' && timer.startedAt != null) {
150
+ return savedElapsedMs + Math.max(0, nowMs - timer.startedAt);
151
+ }
152
+ return savedElapsedMs;
153
+ }
154
+ function timerStatus(timer, nowMs) {
155
+ if (timer.status === 'stopped') {
156
+ return 'stopped';
157
+ }
158
+ const elapsedMs = timerElapsedMs(timer, nowMs);
159
+ if (timer.durationMs <= 0) {
160
+ return 'idle';
161
+ }
162
+ if (elapsedMs >= timer.durationMs) {
163
+ return 'finished';
164
+ }
165
+ if (timer.status === 'paused') {
166
+ return 'paused';
167
+ }
168
+ if (timer.startedAt != null) {
169
+ return 'running';
170
+ }
171
+ return elapsedMs > 0 ? 'paused' : 'idle';
172
+ }
173
+ function buildTimerBinding(timer, nowMs) {
174
+ var _a, _b;
175
+ const status = timerStatus(timer, nowMs);
176
+ const startedAt = status === 'running' ? ((_a = timer.startedAt) !== null && _a !== void 0 ? _a : null) : null;
177
+ const durationMs = timer.durationMs;
178
+ const elapsedMs = Math.min(timerElapsedMs(timer, nowMs), durationMs > 0 ? durationMs : Number.MAX_SAFE_INTEGER);
179
+ const remainingMs = durationMs > 0 ? Math.max(0, durationMs - elapsedMs) : 0;
180
+ const progress = durationMs > 0 ? Math.min(Math.max(elapsedMs / durationMs, 0), 1) : 0;
181
+ const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
182
+ const minutes = Math.floor(totalSeconds / 60);
183
+ const seconds = totalSeconds % 60;
184
+ return {
185
+ id: timer.id,
186
+ startedAtMs: startedAt,
187
+ durationMs,
188
+ status,
189
+ elapsedMs,
190
+ remainingMs,
191
+ progress,
192
+ progressPct: Math.round(progress * 10000) / 100,
193
+ isActive: status === 'running',
194
+ isPaused: status === 'paused',
195
+ remainingText: `${minutes}:${String(seconds).padStart(2, '0')}`,
196
+ endsAtMs: startedAt == null ? null : startedAt + Math.max(0, durationMs - ((_b = timer.elapsedMs) !== null && _b !== void 0 ? _b : 0)),
197
+ };
198
+ }
199
+ function buildMeta(activity, nowMs) {
200
+ var _a, _b, _c;
201
+ return {
202
+ nowMs,
203
+ activityId: activity.activityId,
204
+ status: activity.status,
205
+ openUrl: (_a = activity.openUrl) !== null && _a !== void 0 ? _a : null,
206
+ revision: activity.revision,
207
+ updatedAt: activity.updatedAt,
208
+ template: {
209
+ id: activity.definition.id,
210
+ version: (_b = activity.definition.version) !== null && _b !== void 0 ? _b : null,
211
+ metadata: cloneJson((_c = activity.definition.metadata) !== null && _c !== void 0 ? _c : {}),
212
+ },
213
+ };
214
+ }
215
+ function buildRuntimeScope(activity, nowMs, action) {
216
+ var _a, _b;
217
+ const timers = {};
218
+ for (const [timerId, timerState] of Object.entries(activity.timers)) {
219
+ timers[timerId] = buildTimerBinding(timerState, nowMs);
220
+ }
221
+ const scope = {
222
+ state: cloneJson(activity.state),
223
+ timers,
224
+ meta: buildMeta(activity, nowMs),
225
+ };
226
+ if (action) {
227
+ scope.action = {
228
+ id: action.actionId,
229
+ sourceId: (_a = action.sourceId) !== null && _a !== void 0 ? _a : null,
230
+ payload: cloneJson((_b = action.payload) !== null && _b !== void 0 ? _b : null),
231
+ };
232
+ }
233
+ return scope;
234
+ }
235
+ function normalizeStatePath(path) {
236
+ return path.startsWith('state.') ? path.slice('state.'.length) : path;
237
+ }
238
+ function resolveReference(expression, activity, nowMs, action) {
239
+ const scope = buildRuntimeScope(activity, nowMs, action);
240
+ if (expression.startsWith('state.') ||
241
+ expression.startsWith('timers.') ||
242
+ expression.startsWith('meta.') ||
243
+ expression.startsWith('action.')) {
244
+ return getValueAtPath(scope, expression);
245
+ }
246
+ return getValueAtPath(activity.state, expression);
247
+ }
248
+ function exactTokenValue(template, activity, nowMs, action) {
249
+ const match = template.trim().match(EXACT_TOKEN_PATTERN);
250
+ if (!match) {
251
+ return undefined;
252
+ }
253
+ return resolveReference(match[1], activity, nowMs, action);
254
+ }
255
+ function resolveTemplateString(template, activity, nowMs, action) {
256
+ return template.replace(TOKEN_PATTERN, (_match, expression) => {
257
+ return stringifyValue(resolveReference(expression.trim(), activity, nowMs, action));
258
+ });
259
+ }
260
+ function resolveRuntimePath(path, activity, nowMs, action) {
261
+ return normalizeStatePath(resolveTemplateString(path, activity, nowMs, action));
262
+ }
263
+ function resolveDuration(definition, activity, nowMs) {
264
+ var _a;
265
+ const explicit = definition.durationMs;
266
+ if (typeof explicit === 'number' && Number.isFinite(explicit)) {
267
+ return Math.max(0, Math.round(explicit));
268
+ }
269
+ if (definition.durationPath) {
270
+ const resolvedValue = resolveReference(resolveTemplateString(definition.durationPath, activity, nowMs), activity, nowMs);
271
+ return Math.max(0, (_a = coerceInt(resolvedValue)) !== null && _a !== void 0 ? _a : 0);
272
+ }
273
+ return 0;
274
+ }
275
+ function resolveStartAt(definition, activity, nowMs) {
276
+ if (definition.startAtPath) {
277
+ const resolvedValue = resolveReference(resolveTemplateString(definition.startAtPath, activity, nowMs), activity, nowMs);
278
+ const startAt = coerceInt(resolvedValue);
279
+ if (typeof startAt === 'number') {
280
+ return startAt;
281
+ }
282
+ }
283
+ if (definition.autoStart) {
284
+ return nowMs;
285
+ }
286
+ return null;
287
+ }
288
+ export function reconcileTimerStates(definition, state, existing = {}, activityId = 'preview', status = 'active', nowMs = Date.now()) {
289
+ var _a, _b, _c, _d;
290
+ const activity = {
291
+ activityId,
292
+ definition,
293
+ state,
294
+ timers: cloneJson(existing),
295
+ status,
296
+ updatedAt: nowMs,
297
+ revision: 0,
298
+ };
299
+ const nextTimers = {};
300
+ for (const timerDefinition of (_a = definition.timers) !== null && _a !== void 0 ? _a : []) {
301
+ const previous = existing[timerDefinition.id];
302
+ const durationMs = resolveDuration(timerDefinition, activity, nowMs) || (previous === null || previous === void 0 ? void 0 : previous.durationMs) || 0;
303
+ const hasStartAtPath = typeof timerDefinition.startAtPath === 'string' && timerDefinition.startAtPath.length > 0;
304
+ const startedAt = (_b = previous === null || previous === void 0 ? void 0 : previous.startedAt) !== null && _b !== void 0 ? _b : (!previous || hasStartAtPath ? resolveStartAt(timerDefinition, activity, nowMs) : null);
305
+ const timer = {
306
+ id: timerDefinition.id,
307
+ startedAt,
308
+ elapsedMs: Math.max(0, Math.round((_c = previous === null || previous === void 0 ? void 0 : previous.elapsedMs) !== null && _c !== void 0 ? _c : 0)),
309
+ durationMs,
310
+ status: (_d = previous === null || previous === void 0 ? void 0 : previous.status) !== null && _d !== void 0 ? _d : (startedAt == null ? 'idle' : 'running'),
311
+ updatedAt: nowMs,
312
+ };
313
+ timer.status = timerStatus(timer, nowMs);
314
+ if (timer.status === 'finished') {
315
+ timer.startedAt = null;
316
+ timer.elapsedMs = timer.durationMs;
317
+ }
318
+ nextTimers[timer.id] = timer;
319
+ activity.timers[timer.id] = timer;
320
+ }
321
+ return nextTimers;
322
+ }
323
+ function resolvePatchValue(patch, activity, nowMs, action) {
324
+ var _a;
325
+ if (patch.op === 'timestamp') {
326
+ return nowMs;
327
+ }
328
+ if (patch.valuePath) {
329
+ const resolvedPath = resolveTemplateString(patch.valuePath, activity, nowMs, action);
330
+ return cloneJson((_a = resolveReference(resolvedPath, activity, nowMs, action)) !== null && _a !== void 0 ? _a : null);
331
+ }
332
+ if (patch.valueTemplate) {
333
+ const exact = exactTokenValue(patch.valueTemplate, activity, nowMs, action);
334
+ if (exact !== undefined) {
335
+ return cloneJson(exact);
336
+ }
337
+ return resolveTemplateString(patch.valueTemplate, activity, nowMs, action);
338
+ }
339
+ if (patch.value !== undefined) {
340
+ return cloneJson(patch.value);
341
+ }
342
+ return null;
343
+ }
344
+ function applyStatePatch(activity, patch, nowMs, action) {
345
+ var _a, _b;
346
+ const targetPath = resolveRuntimePath(patch.path, activity, nowMs, action);
347
+ if (!targetPath) {
348
+ return;
349
+ }
350
+ switch (patch.op) {
351
+ case 'set':
352
+ case 'timestamp':
353
+ setValueAtPath(activity.state, targetPath, resolvePatchValue(patch, activity, nowMs, action));
354
+ return;
355
+ case 'increment': {
356
+ const current = getValueAtPath(activity.state, targetPath);
357
+ const nextValue = ((_a = coerceInt(current)) !== null && _a !== void 0 ? _a : 0) + ((_b = patch.amount) !== null && _b !== void 0 ? _b : 1);
358
+ setValueAtPath(activity.state, targetPath, nextValue);
359
+ return;
360
+ }
361
+ case 'toggle': {
362
+ const current = getValueAtPath(activity.state, targetPath);
363
+ setValueAtPath(activity.state, targetPath, !isBoolean(current) ? true : !current);
364
+ return;
365
+ }
366
+ case 'unset':
367
+ deleteValueAtPath(activity.state, targetPath);
368
+ return;
369
+ default:
370
+ return;
371
+ }
372
+ }
373
+ function findTimerDefinition(activity, timerId) {
374
+ var _a;
375
+ return (_a = activity.definition.timers) === null || _a === void 0 ? void 0 : _a.find((candidate) => candidate.id === timerId);
376
+ }
377
+ function resolveFrameId(frameIdTemplate, activity, nowMs, action, mode = 'literal') {
378
+ if (!frameIdTemplate) {
379
+ return undefined;
380
+ }
381
+ const exact = exactTokenValue(frameIdTemplate, activity, nowMs, action);
382
+ if (exact !== undefined) {
383
+ return stringifyValue(exact);
384
+ }
385
+ const resolved = resolveTemplateString(frameIdTemplate, activity, nowMs, action);
386
+ if (mode === 'path') {
387
+ const referenced = resolveReference(resolved, activity, nowMs, action);
388
+ if (referenced !== undefined) {
389
+ return stringifyValue(referenced);
390
+ }
391
+ }
392
+ return resolved || undefined;
393
+ }
394
+ function frameIdsForMutation(activity, mutation) {
395
+ var _a, _b, _c;
396
+ if (mutation.frameIds && mutation.frameIds.length > 0) {
397
+ return mutation.frameIds;
398
+ }
399
+ const surface = mutation.surface;
400
+ if (!surface) {
401
+ return [];
402
+ }
403
+ return (_c = (_b = (_a = activity.definition.layouts[surface]) === null || _a === void 0 ? void 0 : _a.frames) === null || _b === void 0 ? void 0 : _b.map((frame) => frame.id)) !== null && _c !== void 0 ? _c : [];
404
+ }
405
+ function normalizeFrameMutationId(frameId, frameIds) {
406
+ if (!frameId) {
407
+ return undefined;
408
+ }
409
+ return frameIds.length === 0 || frameIds.includes(frameId) ? frameId : undefined;
410
+ }
411
+ function applyFrameMutation(activity, mutation, nowMs, action) {
412
+ var _a, _b, _c;
413
+ const targetPath = resolveRuntimePath(mutation.path, activity, nowMs, action);
414
+ if (!targetPath) {
415
+ return;
416
+ }
417
+ const frameIds = frameIdsForMutation(activity, mutation);
418
+ const currentValue = stringifyValue(getValueAtPath(activity.state, targetPath));
419
+ const currentIndex = frameIds.indexOf(currentValue);
420
+ const wraps = (_a = mutation.wrap) !== null && _a !== void 0 ? _a : true;
421
+ let nextFrameId;
422
+ switch (mutation.op) {
423
+ case 'set':
424
+ nextFrameId = resolveFrameId(mutation.frameId, activity, nowMs, action);
425
+ break;
426
+ case 'toggle': {
427
+ const alternateFrameId = resolveFrameId(mutation.frameId, activity, nowMs, action);
428
+ if (frameIds.length >= 2) {
429
+ nextFrameId = currentValue === frameIds[0] ? frameIds[1] : frameIds[0];
430
+ }
431
+ else if (alternateFrameId) {
432
+ nextFrameId = currentValue === alternateFrameId ? frameIds[0] : alternateFrameId;
433
+ }
434
+ break;
435
+ }
436
+ case 'next': {
437
+ if (frameIds.length === 0) {
438
+ break;
439
+ }
440
+ const nextIndex = currentIndex < 0 ? 0 : currentIndex + 1;
441
+ nextFrameId = (_b = frameIds[nextIndex]) !== null && _b !== void 0 ? _b : (wraps ? frameIds[0] : currentValue);
442
+ break;
443
+ }
444
+ case 'previous': {
445
+ if (frameIds.length === 0) {
446
+ break;
447
+ }
448
+ const nextIndex = currentIndex < 0 ? frameIds.length - 1 : currentIndex - 1;
449
+ nextFrameId = (_c = frameIds[nextIndex]) !== null && _c !== void 0 ? _c : (wraps ? frameIds[frameIds.length - 1] : currentValue);
450
+ break;
451
+ }
452
+ default:
453
+ break;
454
+ }
455
+ nextFrameId = normalizeFrameMutationId(nextFrameId, frameIds);
456
+ if (nextFrameId) {
457
+ setValueAtPath(activity.state, targetPath, nextFrameId);
458
+ }
459
+ }
460
+ function pauseTimer(timer, nowMs) {
461
+ timer.elapsedMs = Math.min(timer.durationMs, timerElapsedMs(timer, nowMs));
462
+ timer.startedAt = null;
463
+ timer.status = timerStatus(timer, nowMs);
464
+ }
465
+ function resumeTimer(timer, nowMs) {
466
+ if (timer.status === 'stopped') {
467
+ return;
468
+ }
469
+ if (timer.status !== 'paused') {
470
+ timer.elapsedMs = 0;
471
+ }
472
+ timer.startedAt = nowMs;
473
+ timer.status = timer.durationMs > 0 ? 'running' : 'idle';
474
+ }
475
+ function applyTimerMutation(activity, mutation, nowMs, action) {
476
+ var _a, _b, _c, _d, _e;
477
+ const timer = (_a = activity.timers[mutation.timerId]) !== null && _a !== void 0 ? _a : {
478
+ id: mutation.timerId,
479
+ startedAt: null,
480
+ elapsedMs: 0,
481
+ durationMs: 0,
482
+ status: 'idle',
483
+ updatedAt: nowMs,
484
+ };
485
+ const timerDefinition = findTimerDefinition(activity, mutation.timerId);
486
+ const activityWithTimer = Object.assign(Object.assign({}, activity), { timers: Object.assign(Object.assign({}, activity.timers), { [mutation.timerId]: timer }) });
487
+ const resolvedDuration = (_d = (_c = (_b = mutation.durationMs) !== null && _b !== void 0 ? _b : (mutation.durationPath
488
+ ? coerceInt(resolveReference(resolveTemplateString(mutation.durationPath, activityWithTimer, nowMs, action), activityWithTimer, nowMs, action))
489
+ : undefined)) !== null && _c !== void 0 ? _c : (timerDefinition ? resolveDuration(timerDefinition, activityWithTimer, nowMs) : undefined)) !== null && _d !== void 0 ? _d : timer.durationMs;
490
+ timer.durationMs = Math.max(0, Math.round(resolvedDuration));
491
+ timer.elapsedMs = Math.max(0, Math.round((_e = timer.elapsedMs) !== null && _e !== void 0 ? _e : 0));
492
+ timer.updatedAt = nowMs;
493
+ switch (mutation.op) {
494
+ case 'start':
495
+ case 'restart':
496
+ timer.elapsedMs = 0;
497
+ timer.startedAt = nowMs;
498
+ timer.status = timer.durationMs > 0 ? 'running' : 'idle';
499
+ break;
500
+ case 'pause':
501
+ pauseTimer(timer, nowMs);
502
+ break;
503
+ case 'resume':
504
+ resumeTimer(timer, nowMs);
505
+ break;
506
+ case 'toggle':
507
+ if (timerStatus(timer, nowMs) === 'running') {
508
+ pauseTimer(timer, nowMs);
509
+ }
510
+ else {
511
+ resumeTimer(timer, nowMs);
512
+ }
513
+ break;
514
+ case 'stop':
515
+ timer.elapsedMs = 0;
516
+ timer.startedAt = null;
517
+ timer.status = 'stopped';
518
+ break;
519
+ case 'reset':
520
+ timer.elapsedMs = 0;
521
+ timer.startedAt = null;
522
+ timer.status = 'idle';
523
+ break;
524
+ case 'setDuration':
525
+ timer.status = timerStatus(timer, nowMs);
526
+ break;
527
+ default:
528
+ break;
529
+ }
530
+ timer.status = timerStatus(timer, nowMs);
531
+ if (timer.status === 'finished') {
532
+ timer.elapsedMs = timer.durationMs;
533
+ timer.startedAt = null;
534
+ }
535
+ activity.timers[mutation.timerId] = timer;
536
+ }
537
+ function resolveLayoutFrame(layout, activity, nowMs) {
538
+ var _a, _b, _c, _d, _e, _f;
539
+ const frames = (_a = layout.frames) !== null && _a !== void 0 ? _a : [];
540
+ const requestedFrameId = resolveFrameId(layout.frameIdPath, activity, nowMs, undefined, 'path');
541
+ const requestedFrame = requestedFrameId == null ? undefined : frames.find((frame) => frame.id === requestedFrameId);
542
+ const defaultFrame = layout.defaultFrameId == null ? undefined : frames.find((frame) => frame.id === layout.defaultFrameId);
543
+ const selectedFrame = (_b = requestedFrame !== null && requestedFrame !== void 0 ? requestedFrame : defaultFrame) !== null && _b !== void 0 ? _b : (layout.svg == null ? frames[0] : undefined);
544
+ return {
545
+ frameId: selectedFrame === null || selectedFrame === void 0 ? void 0 : selectedFrame.id,
546
+ svg: (_d = (_c = selectedFrame === null || selectedFrame === void 0 ? void 0 : selectedFrame.svg) !== null && _c !== void 0 ? _c : layout.svg) !== null && _d !== void 0 ? _d : '',
547
+ hotspots: (_f = (_e = selectedFrame === null || selectedFrame === void 0 ? void 0 : selectedFrame.hotspots) !== null && _e !== void 0 ? _e : layout.hotspots) !== null && _f !== void 0 ? _f : [],
548
+ };
549
+ }
550
+ export function resolveSvgLayout(layout, activity, nowMs = Date.now()) {
551
+ return resolveTemplateString(resolveLayoutFrame(layout, activity, nowMs).svg, activity, nowMs);
552
+ }
553
+ export function getTemplateLayout(activity, surface) {
554
+ var _a;
555
+ return (_a = activity.definition.layouts[surface]) !== null && _a !== void 0 ? _a : null;
556
+ }
557
+ export function resolveTemplateSurface(activity, surface, nowMs = Date.now()) {
558
+ var _a;
559
+ const layout = getTemplateLayout(activity, surface);
560
+ if (!layout) {
561
+ return null;
562
+ }
563
+ const resolvedFrame = resolveLayoutFrame(layout, activity, nowMs);
564
+ return {
565
+ surface,
566
+ activityId: activity.activityId,
567
+ templateId: activity.definition.id,
568
+ frameId: resolvedFrame.frameId,
569
+ svg: resolveTemplateString(resolvedFrame.svg, activity, nowMs),
570
+ width: layout.width,
571
+ height: layout.height,
572
+ hotspots: cloneJson((_a = resolvedFrame.hotspots) !== null && _a !== void 0 ? _a : []),
573
+ openUrl: activity.openUrl,
574
+ status: activity.status,
575
+ revision: activity.revision,
576
+ updatedAt: activity.updatedAt,
577
+ };
578
+ }
579
+ export function createTemplateActivityRecord(definition, state, options = {}) {
580
+ var _a, _b, _c, _d, _e, _f;
581
+ const nowMs = (_a = options.updatedAt) !== null && _a !== void 0 ? _a : Date.now();
582
+ return {
583
+ activityId: (_b = options.activityId) !== null && _b !== void 0 ? _b : createRuntimeId('activity'),
584
+ definition: cloneJson(definition),
585
+ state: cloneJson(state),
586
+ timers: reconcileTimerStates(definition, cloneJson(state), options.timers, (_c = options.activityId) !== null && _c !== void 0 ? _c : 'preview', (_d = options.status) !== null && _d !== void 0 ? _d : 'active', nowMs),
587
+ status: (_e = options.status) !== null && _e !== void 0 ? _e : 'active',
588
+ openUrl: options.openUrl,
589
+ updatedAt: nowMs,
590
+ revision: (_f = options.revision) !== null && _f !== void 0 ? _f : 1,
591
+ };
592
+ }
593
+ export function applyTemplateAction(activity, options, nowMs = Date.now()) {
594
+ var _a, _b, _c, _d, _e;
595
+ const definition = (_a = activity.definition.actions) === null || _a === void 0 ? void 0 : _a.find((candidate) => candidate.id === options.actionId);
596
+ if (!definition) {
597
+ throw new Error(`Action ${options.actionId} is not defined on template ${activity.definition.id}.`);
598
+ }
599
+ const actionScope = {
600
+ actionId: definition.id,
601
+ sourceId: options.sourceId,
602
+ payload: (_b = options.payload) !== null && _b !== void 0 ? _b : null,
603
+ };
604
+ const nextActivity = cloneJson(activity);
605
+ for (const patch of (_c = definition.patches) !== null && _c !== void 0 ? _c : []) {
606
+ applyStatePatch(nextActivity, patch, nowMs, actionScope);
607
+ }
608
+ for (const mutation of (_d = definition.frameMutations) !== null && _d !== void 0 ? _d : []) {
609
+ applyFrameMutation(nextActivity, mutation, nowMs, actionScope);
610
+ }
611
+ for (const mutation of (_e = definition.timerMutations) !== null && _e !== void 0 ? _e : []) {
612
+ applyTimerMutation(nextActivity, mutation, nowMs, actionScope);
613
+ }
614
+ nextActivity.timers = reconcileTimerStates(nextActivity.definition, nextActivity.state, nextActivity.timers, nextActivity.activityId, nextActivity.status, nowMs);
615
+ nextActivity.updatedAt = nowMs;
616
+ nextActivity.revision += 1;
617
+ const event = {
618
+ eventId: createRuntimeId('event'),
619
+ activityId: nextActivity.activityId,
620
+ actionId: definition.id,
621
+ eventName: definition.eventName,
622
+ sourceId: options.sourceId,
623
+ createdAt: nowMs,
624
+ acknowledgedAt: null,
625
+ payload: options.payload ? cloneJson(options.payload) : null,
626
+ state: cloneJson(nextActivity.state),
627
+ timers: cloneJson(nextActivity.timers),
628
+ };
629
+ return {
630
+ activity: nextActivity,
631
+ event,
632
+ };
633
+ }
634
+ export function acknowledgeEvents(events, options) {
635
+ var _a, _b;
636
+ const acknowledgedAt = (_a = options.acknowledgedAt) !== null && _a !== void 0 ? _a : Date.now();
637
+ const eventIds = new Set((_b = options.eventIds) !== null && _b !== void 0 ? _b : []);
638
+ return events.map((event) => {
639
+ const matchesEventId = eventIds.size > 0 && eventIds.has(event.eventId);
640
+ const matchesActivity = options.activityId != null && event.activityId === options.activityId;
641
+ if (!matchesEventId && !matchesActivity) {
642
+ return event;
643
+ }
644
+ return Object.assign(Object.assign({}, event), { acknowledgedAt });
645
+ });
646
+ }
647
+ export function createRuntimeId(prefix) {
648
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
649
+ return `${prefix}-${crypto.randomUUID()}`;
650
+ }
651
+ return `${prefix}-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
652
+ }
653
+ //# sourceMappingURL=runtime.js.map