@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
package/dist/plugin.js ADDED
@@ -0,0 +1,1099 @@
1
+ var capgoWidgetKit = (function (exports, core) {
2
+ 'use strict';
3
+
4
+ const TOKEN_PATTERN = /{{\s*([^{}]+?)\s*}}/g;
5
+ const EXACT_TOKEN_PATTERN = /^{{\s*([^{}]+?)\s*}}$/;
6
+ function cloneJson$1(value) {
7
+ return JSON.parse(JSON.stringify(value));
8
+ }
9
+ function toJsonValue(value) {
10
+ return cloneJson$1(value);
11
+ }
12
+ function toJsonObject(value) {
13
+ return cloneJson$1(value);
14
+ }
15
+ function isObject(value) {
16
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
17
+ }
18
+ function isArray(value) {
19
+ return Array.isArray(value);
20
+ }
21
+ function isNumber(value) {
22
+ return typeof value === 'number' && Number.isFinite(value);
23
+ }
24
+ function isBoolean(value) {
25
+ return typeof value === 'boolean';
26
+ }
27
+ function stringifyValue(value) {
28
+ if (value == null) {
29
+ return '';
30
+ }
31
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
32
+ return String(value);
33
+ }
34
+ return JSON.stringify(value);
35
+ }
36
+ function splitPath(path) {
37
+ return path
38
+ .split('.')
39
+ .map((segment) => segment.trim())
40
+ .filter(Boolean);
41
+ }
42
+ function isIndexSegment(segment) {
43
+ return /^\d+$/.test(segment);
44
+ }
45
+ function getValueAtPath(root, path) {
46
+ const segments = splitPath(path);
47
+ let current = root;
48
+ for (const segment of segments) {
49
+ if (isObject(current)) {
50
+ current = current[segment];
51
+ continue;
52
+ }
53
+ if (isArray(current) && isIndexSegment(segment)) {
54
+ current = current[Number(segment)];
55
+ continue;
56
+ }
57
+ return undefined;
58
+ }
59
+ return current;
60
+ }
61
+ function ensureContainer(parent, segment, nextSegment) {
62
+ const createArray = nextSegment != null && isIndexSegment(nextSegment);
63
+ if (isArray(parent) && isIndexSegment(segment)) {
64
+ const index = Number(segment);
65
+ if (parent[index] == null) {
66
+ parent[index] = createArray ? [] : {};
67
+ }
68
+ return parent[index];
69
+ }
70
+ if (isObject(parent)) {
71
+ if (parent[segment] == null) {
72
+ parent[segment] = createArray ? [] : {};
73
+ }
74
+ return parent[segment];
75
+ }
76
+ return {};
77
+ }
78
+ function setValueAtPath(root, path, value) {
79
+ const segments = splitPath(path);
80
+ if (segments.length === 0) {
81
+ return;
82
+ }
83
+ let current = root;
84
+ for (let index = 0; index < segments.length - 1; index += 1) {
85
+ const segment = segments[index];
86
+ const next = ensureContainer(current, segment, segments[index + 1]);
87
+ if (!isObject(next) && !isArray(next)) {
88
+ const replacement = isIndexSegment(segments[index + 1]) ? [] : {};
89
+ if (isArray(current) && isIndexSegment(segment)) {
90
+ current[Number(segment)] = replacement;
91
+ }
92
+ else if (isObject(current)) {
93
+ current[segment] = replacement;
94
+ }
95
+ current = replacement;
96
+ }
97
+ else {
98
+ current = next;
99
+ }
100
+ }
101
+ const lastSegment = segments[segments.length - 1];
102
+ if (isArray(current) && isIndexSegment(lastSegment)) {
103
+ current[Number(lastSegment)] = cloneJson$1(value);
104
+ return;
105
+ }
106
+ if (isObject(current)) {
107
+ current[lastSegment] = cloneJson$1(value);
108
+ }
109
+ }
110
+ function deleteValueAtPath(root, path) {
111
+ const segments = splitPath(path);
112
+ if (segments.length === 0) {
113
+ return;
114
+ }
115
+ let current = root;
116
+ for (let index = 0; index < segments.length - 1; index += 1) {
117
+ const segment = segments[index];
118
+ if (isObject(current)) {
119
+ current = current[segment];
120
+ continue;
121
+ }
122
+ if (isArray(current) && isIndexSegment(segment)) {
123
+ current = current[Number(segment)];
124
+ continue;
125
+ }
126
+ return;
127
+ }
128
+ const lastSegment = segments[segments.length - 1];
129
+ if (isObject(current)) {
130
+ delete current[lastSegment];
131
+ }
132
+ else if (isArray(current) && isIndexSegment(lastSegment)) {
133
+ current.splice(Number(lastSegment), 1);
134
+ }
135
+ }
136
+ function coerceInt(value) {
137
+ if (isNumber(value)) {
138
+ return Math.round(value);
139
+ }
140
+ if (typeof value === 'string' && value.trim() !== '') {
141
+ const parsed = Number(value);
142
+ return Number.isFinite(parsed) ? Math.round(parsed) : undefined;
143
+ }
144
+ return undefined;
145
+ }
146
+ function timerElapsedMs(timer, nowMs) {
147
+ var _a;
148
+ const savedElapsedMs = Math.max(0, Math.round((_a = timer.elapsedMs) !== null && _a !== void 0 ? _a : 0));
149
+ if (timer.status === 'finished' && timer.durationMs > 0) {
150
+ return timer.durationMs;
151
+ }
152
+ if (timer.status === 'running' && timer.startedAt != null) {
153
+ return savedElapsedMs + Math.max(0, nowMs - timer.startedAt);
154
+ }
155
+ return savedElapsedMs;
156
+ }
157
+ function timerStatus(timer, nowMs) {
158
+ if (timer.status === 'stopped') {
159
+ return 'stopped';
160
+ }
161
+ const elapsedMs = timerElapsedMs(timer, nowMs);
162
+ if (timer.durationMs <= 0) {
163
+ return 'idle';
164
+ }
165
+ if (elapsedMs >= timer.durationMs) {
166
+ return 'finished';
167
+ }
168
+ if (timer.status === 'paused') {
169
+ return 'paused';
170
+ }
171
+ if (timer.startedAt != null) {
172
+ return 'running';
173
+ }
174
+ return elapsedMs > 0 ? 'paused' : 'idle';
175
+ }
176
+ function buildTimerBinding(timer, nowMs) {
177
+ var _a, _b;
178
+ const status = timerStatus(timer, nowMs);
179
+ const startedAt = status === 'running' ? ((_a = timer.startedAt) !== null && _a !== void 0 ? _a : null) : null;
180
+ const durationMs = timer.durationMs;
181
+ const elapsedMs = Math.min(timerElapsedMs(timer, nowMs), durationMs > 0 ? durationMs : Number.MAX_SAFE_INTEGER);
182
+ const remainingMs = durationMs > 0 ? Math.max(0, durationMs - elapsedMs) : 0;
183
+ const progress = durationMs > 0 ? Math.min(Math.max(elapsedMs / durationMs, 0), 1) : 0;
184
+ const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
185
+ const minutes = Math.floor(totalSeconds / 60);
186
+ const seconds = totalSeconds % 60;
187
+ return {
188
+ id: timer.id,
189
+ startedAtMs: startedAt,
190
+ durationMs,
191
+ status,
192
+ elapsedMs,
193
+ remainingMs,
194
+ progress,
195
+ progressPct: Math.round(progress * 10000) / 100,
196
+ isActive: status === 'running',
197
+ isPaused: status === 'paused',
198
+ remainingText: `${minutes}:${String(seconds).padStart(2, '0')}`,
199
+ endsAtMs: startedAt == null ? null : startedAt + Math.max(0, durationMs - ((_b = timer.elapsedMs) !== null && _b !== void 0 ? _b : 0)),
200
+ };
201
+ }
202
+ function buildMeta(activity, nowMs) {
203
+ var _a, _b, _c;
204
+ return {
205
+ nowMs,
206
+ activityId: activity.activityId,
207
+ status: activity.status,
208
+ openUrl: (_a = activity.openUrl) !== null && _a !== void 0 ? _a : null,
209
+ revision: activity.revision,
210
+ updatedAt: activity.updatedAt,
211
+ template: {
212
+ id: activity.definition.id,
213
+ version: (_b = activity.definition.version) !== null && _b !== void 0 ? _b : null,
214
+ metadata: cloneJson$1((_c = activity.definition.metadata) !== null && _c !== void 0 ? _c : {}),
215
+ },
216
+ };
217
+ }
218
+ function buildRuntimeScope(activity, nowMs, action) {
219
+ var _a, _b;
220
+ const timers = {};
221
+ for (const [timerId, timerState] of Object.entries(activity.timers)) {
222
+ timers[timerId] = buildTimerBinding(timerState, nowMs);
223
+ }
224
+ const scope = {
225
+ state: cloneJson$1(activity.state),
226
+ timers,
227
+ meta: buildMeta(activity, nowMs),
228
+ };
229
+ if (action) {
230
+ scope.action = {
231
+ id: action.actionId,
232
+ sourceId: (_a = action.sourceId) !== null && _a !== void 0 ? _a : null,
233
+ payload: cloneJson$1((_b = action.payload) !== null && _b !== void 0 ? _b : null),
234
+ };
235
+ }
236
+ return scope;
237
+ }
238
+ function normalizeStatePath(path) {
239
+ return path.startsWith('state.') ? path.slice('state.'.length) : path;
240
+ }
241
+ function resolveReference(expression, activity, nowMs, action) {
242
+ const scope = buildRuntimeScope(activity, nowMs, action);
243
+ if (expression.startsWith('state.') ||
244
+ expression.startsWith('timers.') ||
245
+ expression.startsWith('meta.') ||
246
+ expression.startsWith('action.')) {
247
+ return getValueAtPath(scope, expression);
248
+ }
249
+ return getValueAtPath(activity.state, expression);
250
+ }
251
+ function exactTokenValue(template, activity, nowMs, action) {
252
+ const match = template.trim().match(EXACT_TOKEN_PATTERN);
253
+ if (!match) {
254
+ return undefined;
255
+ }
256
+ return resolveReference(match[1], activity, nowMs, action);
257
+ }
258
+ function resolveTemplateString(template, activity, nowMs, action) {
259
+ return template.replace(TOKEN_PATTERN, (_match, expression) => {
260
+ return stringifyValue(resolveReference(expression.trim(), activity, nowMs, action));
261
+ });
262
+ }
263
+ function resolveRuntimePath(path, activity, nowMs, action) {
264
+ return normalizeStatePath(resolveTemplateString(path, activity, nowMs, action));
265
+ }
266
+ function resolveDuration(definition, activity, nowMs) {
267
+ var _a;
268
+ const explicit = definition.durationMs;
269
+ if (typeof explicit === 'number' && Number.isFinite(explicit)) {
270
+ return Math.max(0, Math.round(explicit));
271
+ }
272
+ if (definition.durationPath) {
273
+ const resolvedValue = resolveReference(resolveTemplateString(definition.durationPath, activity, nowMs), activity, nowMs);
274
+ return Math.max(0, (_a = coerceInt(resolvedValue)) !== null && _a !== void 0 ? _a : 0);
275
+ }
276
+ return 0;
277
+ }
278
+ function resolveStartAt(definition, activity, nowMs) {
279
+ if (definition.startAtPath) {
280
+ const resolvedValue = resolveReference(resolveTemplateString(definition.startAtPath, activity, nowMs), activity, nowMs);
281
+ const startAt = coerceInt(resolvedValue);
282
+ if (typeof startAt === 'number') {
283
+ return startAt;
284
+ }
285
+ }
286
+ if (definition.autoStart) {
287
+ return nowMs;
288
+ }
289
+ return null;
290
+ }
291
+ function reconcileTimerStates(definition, state, existing = {}, activityId = 'preview', status = 'active', nowMs = Date.now()) {
292
+ var _a, _b, _c, _d;
293
+ const activity = {
294
+ activityId,
295
+ definition,
296
+ state,
297
+ timers: cloneJson$1(existing),
298
+ status,
299
+ updatedAt: nowMs,
300
+ revision: 0,
301
+ };
302
+ const nextTimers = {};
303
+ for (const timerDefinition of (_a = definition.timers) !== null && _a !== void 0 ? _a : []) {
304
+ const previous = existing[timerDefinition.id];
305
+ const durationMs = resolveDuration(timerDefinition, activity, nowMs) || (previous === null || previous === void 0 ? void 0 : previous.durationMs) || 0;
306
+ const hasStartAtPath = typeof timerDefinition.startAtPath === 'string' && timerDefinition.startAtPath.length > 0;
307
+ const startedAt = (_b = previous === null || previous === void 0 ? void 0 : previous.startedAt) !== null && _b !== void 0 ? _b : (!previous || hasStartAtPath ? resolveStartAt(timerDefinition, activity, nowMs) : null);
308
+ const timer = {
309
+ id: timerDefinition.id,
310
+ startedAt,
311
+ elapsedMs: Math.max(0, Math.round((_c = previous === null || previous === void 0 ? void 0 : previous.elapsedMs) !== null && _c !== void 0 ? _c : 0)),
312
+ durationMs,
313
+ status: (_d = previous === null || previous === void 0 ? void 0 : previous.status) !== null && _d !== void 0 ? _d : (startedAt == null ? 'idle' : 'running'),
314
+ updatedAt: nowMs,
315
+ };
316
+ timer.status = timerStatus(timer, nowMs);
317
+ if (timer.status === 'finished') {
318
+ timer.startedAt = null;
319
+ timer.elapsedMs = timer.durationMs;
320
+ }
321
+ nextTimers[timer.id] = timer;
322
+ activity.timers[timer.id] = timer;
323
+ }
324
+ return nextTimers;
325
+ }
326
+ function resolvePatchValue(patch, activity, nowMs, action) {
327
+ var _a;
328
+ if (patch.op === 'timestamp') {
329
+ return nowMs;
330
+ }
331
+ if (patch.valuePath) {
332
+ const resolvedPath = resolveTemplateString(patch.valuePath, activity, nowMs, action);
333
+ return cloneJson$1((_a = resolveReference(resolvedPath, activity, nowMs, action)) !== null && _a !== void 0 ? _a : null);
334
+ }
335
+ if (patch.valueTemplate) {
336
+ const exact = exactTokenValue(patch.valueTemplate, activity, nowMs, action);
337
+ if (exact !== undefined) {
338
+ return cloneJson$1(exact);
339
+ }
340
+ return resolveTemplateString(patch.valueTemplate, activity, nowMs, action);
341
+ }
342
+ if (patch.value !== undefined) {
343
+ return cloneJson$1(patch.value);
344
+ }
345
+ return null;
346
+ }
347
+ function applyStatePatch(activity, patch, nowMs, action) {
348
+ var _a, _b;
349
+ const targetPath = resolveRuntimePath(patch.path, activity, nowMs, action);
350
+ if (!targetPath) {
351
+ return;
352
+ }
353
+ switch (patch.op) {
354
+ case 'set':
355
+ case 'timestamp':
356
+ setValueAtPath(activity.state, targetPath, resolvePatchValue(patch, activity, nowMs, action));
357
+ return;
358
+ case 'increment': {
359
+ const current = getValueAtPath(activity.state, targetPath);
360
+ const nextValue = ((_a = coerceInt(current)) !== null && _a !== void 0 ? _a : 0) + ((_b = patch.amount) !== null && _b !== void 0 ? _b : 1);
361
+ setValueAtPath(activity.state, targetPath, nextValue);
362
+ return;
363
+ }
364
+ case 'toggle': {
365
+ const current = getValueAtPath(activity.state, targetPath);
366
+ setValueAtPath(activity.state, targetPath, !isBoolean(current) ? true : !current);
367
+ return;
368
+ }
369
+ case 'unset':
370
+ deleteValueAtPath(activity.state, targetPath);
371
+ return;
372
+ default:
373
+ return;
374
+ }
375
+ }
376
+ function findTimerDefinition(activity, timerId) {
377
+ var _a;
378
+ return (_a = activity.definition.timers) === null || _a === void 0 ? void 0 : _a.find((candidate) => candidate.id === timerId);
379
+ }
380
+ function resolveFrameId(frameIdTemplate, activity, nowMs, action, mode = 'literal') {
381
+ if (!frameIdTemplate) {
382
+ return undefined;
383
+ }
384
+ const exact = exactTokenValue(frameIdTemplate, activity, nowMs, action);
385
+ if (exact !== undefined) {
386
+ return stringifyValue(exact);
387
+ }
388
+ const resolved = resolveTemplateString(frameIdTemplate, activity, nowMs, action);
389
+ if (mode === 'path') {
390
+ const referenced = resolveReference(resolved, activity, nowMs, action);
391
+ if (referenced !== undefined) {
392
+ return stringifyValue(referenced);
393
+ }
394
+ }
395
+ return resolved || undefined;
396
+ }
397
+ function frameIdsForMutation(activity, mutation) {
398
+ var _a, _b, _c;
399
+ if (mutation.frameIds && mutation.frameIds.length > 0) {
400
+ return mutation.frameIds;
401
+ }
402
+ const surface = mutation.surface;
403
+ if (!surface) {
404
+ return [];
405
+ }
406
+ 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 : [];
407
+ }
408
+ function normalizeFrameMutationId(frameId, frameIds) {
409
+ if (!frameId) {
410
+ return undefined;
411
+ }
412
+ return frameIds.length === 0 || frameIds.includes(frameId) ? frameId : undefined;
413
+ }
414
+ function applyFrameMutation(activity, mutation, nowMs, action) {
415
+ var _a, _b, _c;
416
+ const targetPath = resolveRuntimePath(mutation.path, activity, nowMs, action);
417
+ if (!targetPath) {
418
+ return;
419
+ }
420
+ const frameIds = frameIdsForMutation(activity, mutation);
421
+ const currentValue = stringifyValue(getValueAtPath(activity.state, targetPath));
422
+ const currentIndex = frameIds.indexOf(currentValue);
423
+ const wraps = (_a = mutation.wrap) !== null && _a !== void 0 ? _a : true;
424
+ let nextFrameId;
425
+ switch (mutation.op) {
426
+ case 'set':
427
+ nextFrameId = resolveFrameId(mutation.frameId, activity, nowMs, action);
428
+ break;
429
+ case 'toggle': {
430
+ const alternateFrameId = resolveFrameId(mutation.frameId, activity, nowMs, action);
431
+ if (frameIds.length >= 2) {
432
+ nextFrameId = currentValue === frameIds[0] ? frameIds[1] : frameIds[0];
433
+ }
434
+ else if (alternateFrameId) {
435
+ nextFrameId = currentValue === alternateFrameId ? frameIds[0] : alternateFrameId;
436
+ }
437
+ break;
438
+ }
439
+ case 'next': {
440
+ if (frameIds.length === 0) {
441
+ break;
442
+ }
443
+ const nextIndex = currentIndex < 0 ? 0 : currentIndex + 1;
444
+ nextFrameId = (_b = frameIds[nextIndex]) !== null && _b !== void 0 ? _b : (wraps ? frameIds[0] : currentValue);
445
+ break;
446
+ }
447
+ case 'previous': {
448
+ if (frameIds.length === 0) {
449
+ break;
450
+ }
451
+ const nextIndex = currentIndex < 0 ? frameIds.length - 1 : currentIndex - 1;
452
+ nextFrameId = (_c = frameIds[nextIndex]) !== null && _c !== void 0 ? _c : (wraps ? frameIds[frameIds.length - 1] : currentValue);
453
+ break;
454
+ }
455
+ }
456
+ nextFrameId = normalizeFrameMutationId(nextFrameId, frameIds);
457
+ if (nextFrameId) {
458
+ setValueAtPath(activity.state, targetPath, nextFrameId);
459
+ }
460
+ }
461
+ function pauseTimer(timer, nowMs) {
462
+ timer.elapsedMs = Math.min(timer.durationMs, timerElapsedMs(timer, nowMs));
463
+ timer.startedAt = null;
464
+ timer.status = timerStatus(timer, nowMs);
465
+ }
466
+ function resumeTimer(timer, nowMs) {
467
+ if (timer.status === 'stopped') {
468
+ return;
469
+ }
470
+ if (timer.status !== 'paused') {
471
+ timer.elapsedMs = 0;
472
+ }
473
+ timer.startedAt = nowMs;
474
+ timer.status = timer.durationMs > 0 ? 'running' : 'idle';
475
+ }
476
+ function applyTimerMutation(activity, mutation, nowMs, action) {
477
+ var _a, _b, _c, _d, _e;
478
+ const timer = (_a = activity.timers[mutation.timerId]) !== null && _a !== void 0 ? _a : {
479
+ id: mutation.timerId,
480
+ startedAt: null,
481
+ elapsedMs: 0,
482
+ durationMs: 0,
483
+ status: 'idle',
484
+ updatedAt: nowMs,
485
+ };
486
+ const timerDefinition = findTimerDefinition(activity, mutation.timerId);
487
+ const activityWithTimer = Object.assign(Object.assign({}, activity), { timers: Object.assign(Object.assign({}, activity.timers), { [mutation.timerId]: timer }) });
488
+ const resolvedDuration = (_d = (_c = (_b = mutation.durationMs) !== null && _b !== void 0 ? _b : (mutation.durationPath
489
+ ? coerceInt(resolveReference(resolveTemplateString(mutation.durationPath, activityWithTimer, nowMs, action), activityWithTimer, nowMs, action))
490
+ : undefined)) !== null && _c !== void 0 ? _c : (timerDefinition ? resolveDuration(timerDefinition, activityWithTimer, nowMs) : undefined)) !== null && _d !== void 0 ? _d : timer.durationMs;
491
+ timer.durationMs = Math.max(0, Math.round(resolvedDuration));
492
+ timer.elapsedMs = Math.max(0, Math.round((_e = timer.elapsedMs) !== null && _e !== void 0 ? _e : 0));
493
+ timer.updatedAt = nowMs;
494
+ switch (mutation.op) {
495
+ case 'start':
496
+ case 'restart':
497
+ timer.elapsedMs = 0;
498
+ timer.startedAt = nowMs;
499
+ timer.status = timer.durationMs > 0 ? 'running' : 'idle';
500
+ break;
501
+ case 'pause':
502
+ pauseTimer(timer, nowMs);
503
+ break;
504
+ case 'resume':
505
+ resumeTimer(timer, nowMs);
506
+ break;
507
+ case 'toggle':
508
+ if (timerStatus(timer, nowMs) === 'running') {
509
+ pauseTimer(timer, nowMs);
510
+ }
511
+ else {
512
+ resumeTimer(timer, nowMs);
513
+ }
514
+ break;
515
+ case 'stop':
516
+ timer.elapsedMs = 0;
517
+ timer.startedAt = null;
518
+ timer.status = 'stopped';
519
+ break;
520
+ case 'reset':
521
+ timer.elapsedMs = 0;
522
+ timer.startedAt = null;
523
+ timer.status = 'idle';
524
+ break;
525
+ case 'setDuration':
526
+ timer.status = timerStatus(timer, nowMs);
527
+ break;
528
+ }
529
+ timer.status = timerStatus(timer, nowMs);
530
+ if (timer.status === 'finished') {
531
+ timer.elapsedMs = timer.durationMs;
532
+ timer.startedAt = null;
533
+ }
534
+ activity.timers[mutation.timerId] = timer;
535
+ }
536
+ function resolveLayoutFrame(layout, activity, nowMs) {
537
+ var _a, _b, _c, _d, _e, _f;
538
+ const frames = (_a = layout.frames) !== null && _a !== void 0 ? _a : [];
539
+ const requestedFrameId = resolveFrameId(layout.frameIdPath, activity, nowMs, undefined, 'path');
540
+ const requestedFrame = requestedFrameId == null ? undefined : frames.find((frame) => frame.id === requestedFrameId);
541
+ const defaultFrame = layout.defaultFrameId == null ? undefined : frames.find((frame) => frame.id === layout.defaultFrameId);
542
+ const selectedFrame = (_b = requestedFrame !== null && requestedFrame !== void 0 ? requestedFrame : defaultFrame) !== null && _b !== void 0 ? _b : (layout.svg == null ? frames[0] : undefined);
543
+ return {
544
+ frameId: selectedFrame === null || selectedFrame === void 0 ? void 0 : selectedFrame.id,
545
+ svg: (_d = (_c = selectedFrame === null || selectedFrame === void 0 ? void 0 : selectedFrame.svg) !== null && _c !== void 0 ? _c : layout.svg) !== null && _d !== void 0 ? _d : '',
546
+ hotspots: (_f = (_e = selectedFrame === null || selectedFrame === void 0 ? void 0 : selectedFrame.hotspots) !== null && _e !== void 0 ? _e : layout.hotspots) !== null && _f !== void 0 ? _f : [],
547
+ };
548
+ }
549
+ function resolveSvgLayout(layout, activity, nowMs = Date.now()) {
550
+ return resolveTemplateString(resolveLayoutFrame(layout, activity, nowMs).svg, activity, nowMs);
551
+ }
552
+ function getTemplateLayout(activity, surface) {
553
+ var _a;
554
+ return (_a = activity.definition.layouts[surface]) !== null && _a !== void 0 ? _a : null;
555
+ }
556
+ function resolveTemplateSurface(activity, surface, nowMs = Date.now()) {
557
+ var _a;
558
+ const layout = getTemplateLayout(activity, surface);
559
+ if (!layout) {
560
+ return null;
561
+ }
562
+ const resolvedFrame = resolveLayoutFrame(layout, activity, nowMs);
563
+ return {
564
+ surface,
565
+ activityId: activity.activityId,
566
+ templateId: activity.definition.id,
567
+ frameId: resolvedFrame.frameId,
568
+ svg: resolveTemplateString(resolvedFrame.svg, activity, nowMs),
569
+ width: layout.width,
570
+ height: layout.height,
571
+ hotspots: cloneJson$1((_a = resolvedFrame.hotspots) !== null && _a !== void 0 ? _a : []),
572
+ openUrl: activity.openUrl,
573
+ status: activity.status,
574
+ revision: activity.revision,
575
+ updatedAt: activity.updatedAt,
576
+ };
577
+ }
578
+ function createTemplateActivityRecord(definition, state, options = {}) {
579
+ var _a, _b, _c, _d, _e, _f;
580
+ const nowMs = (_a = options.updatedAt) !== null && _a !== void 0 ? _a : Date.now();
581
+ return {
582
+ activityId: (_b = options.activityId) !== null && _b !== void 0 ? _b : createRuntimeId('activity'),
583
+ definition: cloneJson$1(definition),
584
+ state: cloneJson$1(state),
585
+ timers: reconcileTimerStates(definition, cloneJson$1(state), options.timers, (_c = options.activityId) !== null && _c !== void 0 ? _c : 'preview', (_d = options.status) !== null && _d !== void 0 ? _d : 'active', nowMs),
586
+ status: (_e = options.status) !== null && _e !== void 0 ? _e : 'active',
587
+ openUrl: options.openUrl,
588
+ updatedAt: nowMs,
589
+ revision: (_f = options.revision) !== null && _f !== void 0 ? _f : 1,
590
+ };
591
+ }
592
+ function applyTemplateAction(activity, options, nowMs = Date.now()) {
593
+ var _a, _b, _c, _d, _e;
594
+ const definition = (_a = activity.definition.actions) === null || _a === void 0 ? void 0 : _a.find((candidate) => candidate.id === options.actionId);
595
+ if (!definition) {
596
+ throw new Error(`Action ${options.actionId} is not defined on template ${activity.definition.id}.`);
597
+ }
598
+ const actionScope = {
599
+ actionId: definition.id,
600
+ sourceId: options.sourceId,
601
+ payload: (_b = options.payload) !== null && _b !== void 0 ? _b : null,
602
+ };
603
+ const nextActivity = cloneJson$1(activity);
604
+ for (const patch of (_c = definition.patches) !== null && _c !== void 0 ? _c : []) {
605
+ applyStatePatch(nextActivity, patch, nowMs, actionScope);
606
+ }
607
+ for (const mutation of (_d = definition.frameMutations) !== null && _d !== void 0 ? _d : []) {
608
+ applyFrameMutation(nextActivity, mutation, nowMs, actionScope);
609
+ }
610
+ for (const mutation of (_e = definition.timerMutations) !== null && _e !== void 0 ? _e : []) {
611
+ applyTimerMutation(nextActivity, mutation, nowMs, actionScope);
612
+ }
613
+ nextActivity.timers = reconcileTimerStates(nextActivity.definition, nextActivity.state, nextActivity.timers, nextActivity.activityId, nextActivity.status, nowMs);
614
+ nextActivity.updatedAt = nowMs;
615
+ nextActivity.revision += 1;
616
+ const event = {
617
+ eventId: createRuntimeId('event'),
618
+ activityId: nextActivity.activityId,
619
+ actionId: definition.id,
620
+ eventName: definition.eventName,
621
+ sourceId: options.sourceId,
622
+ createdAt: nowMs,
623
+ acknowledgedAt: null,
624
+ payload: options.payload ? cloneJson$1(options.payload) : null,
625
+ state: cloneJson$1(nextActivity.state),
626
+ timers: cloneJson$1(nextActivity.timers),
627
+ };
628
+ return {
629
+ activity: nextActivity,
630
+ event,
631
+ };
632
+ }
633
+ function acknowledgeEvents(events, options) {
634
+ var _a, _b;
635
+ const acknowledgedAt = (_a = options.acknowledgedAt) !== null && _a !== void 0 ? _a : Date.now();
636
+ const eventIds = new Set((_b = options.eventIds) !== null && _b !== void 0 ? _b : []);
637
+ return events.map((event) => {
638
+ const matchesEventId = eventIds.size > 0 && eventIds.has(event.eventId);
639
+ const matchesActivity = options.activityId != null && event.activityId === options.activityId;
640
+ if (!matchesEventId && !matchesActivity) {
641
+ return event;
642
+ }
643
+ return Object.assign(Object.assign({}, event), { acknowledgedAt });
644
+ });
645
+ }
646
+ function createRuntimeId(prefix) {
647
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
648
+ return `${prefix}-${crypto.randomUUID()}`;
649
+ }
650
+ return `${prefix}-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
651
+ }
652
+
653
+ function getCurrentExercise(session) {
654
+ var _a;
655
+ if (session.activeExerciseIndex == null) {
656
+ return null;
657
+ }
658
+ return (_a = session.exercises[session.activeExerciseIndex]) !== null && _a !== void 0 ? _a : null;
659
+ }
660
+ function getCurrentSet(session) {
661
+ var _a;
662
+ const currentExercise = getCurrentExercise(session);
663
+ if (!currentExercise || session.activeSetIndex == null) {
664
+ return null;
665
+ }
666
+ return (_a = currentExercise.sets[session.activeSetIndex]) !== null && _a !== void 0 ? _a : null;
667
+ }
668
+ function createWorkoutTemplateState(session) {
669
+ const currentExercise = getCurrentExercise(session);
670
+ const currentSet = getCurrentSet(session);
671
+ return {
672
+ session: toJsonObject(session),
673
+ currentExercise: currentExercise ? toJsonObject(currentExercise) : null,
674
+ currentSet: currentSet ? toJsonObject(currentSet) : null,
675
+ lastCompleted: null,
676
+ };
677
+ }
678
+ /**
679
+ * Convenience helper that maps the customer workout JSON into the generic SVG activity format.
680
+ *
681
+ * The plugin stays generic. This helper is only an example of how one product flow can be expressed
682
+ * with declarative SVG templates, actions, and timer bindings.
683
+ */
684
+ function createWorkoutTemplateActivity(session) {
685
+ return {
686
+ activityId: session.sessionId,
687
+ openUrl: session.deepLinkUrl,
688
+ state: createWorkoutTemplateState(session),
689
+ definition: {
690
+ id: 'workout-live-activity-example',
691
+ version: '1',
692
+ timers: [
693
+ {
694
+ id: 'rest',
695
+ durationPath: 'state.lastCompleted.timerDurationMs',
696
+ },
697
+ ],
698
+ actions: [
699
+ {
700
+ id: 'complete-set',
701
+ eventName: 'workout.set.completed',
702
+ patches: [
703
+ {
704
+ op: 'set',
705
+ path: 'lastCompleted',
706
+ valuePath: 'state.currentSet',
707
+ },
708
+ {
709
+ op: 'timestamp',
710
+ path: 'session.exercises.{{state.session.activeExerciseIndex}}.sets.{{state.session.activeSetIndex}}.completedAt',
711
+ },
712
+ {
713
+ op: 'set',
714
+ path: 'session.activeExerciseIndex',
715
+ valuePath: 'state.currentSet.nextExerciseIndex',
716
+ },
717
+ {
718
+ op: 'set',
719
+ path: 'session.activeSetIndex',
720
+ valuePath: 'state.currentSet.nextSetIndex',
721
+ },
722
+ {
723
+ op: 'set',
724
+ path: 'currentExercise',
725
+ valuePath: 'state.session.exercises.{{state.session.activeExerciseIndex}}',
726
+ },
727
+ {
728
+ op: 'set',
729
+ path: 'currentSet',
730
+ valuePath: 'state.currentExercise.sets.{{state.session.activeSetIndex}}',
731
+ },
732
+ ],
733
+ timerMutations: [
734
+ {
735
+ op: 'setDuration',
736
+ timerId: 'rest',
737
+ durationPath: 'state.lastCompleted.timerDurationMs',
738
+ },
739
+ {
740
+ op: 'restart',
741
+ timerId: 'rest',
742
+ durationPath: 'state.lastCompleted.timerDurationMs',
743
+ },
744
+ ],
745
+ },
746
+ ],
747
+ layouts: {
748
+ lockScreen: {
749
+ width: 100,
750
+ height: 40,
751
+ hotspots: [
752
+ {
753
+ id: 'complete-button',
754
+ actionId: 'complete-set',
755
+ x: 80,
756
+ y: 24,
757
+ width: 14,
758
+ height: 10,
759
+ label: 'Complete active set',
760
+ role: 'button',
761
+ },
762
+ ],
763
+ svg: `
764
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 40">
765
+ <rect x="0" y="0" width="100" height="40" rx="6" fill="#05070b" />
766
+ <rect x="0" y="0" width="{{timers.rest.progressPct}}" height="40" rx="6" fill="#00d69c" opacity="0.28" />
767
+ <text x="5" y="8" fill="#9fb0c8" font-size="4">{{state.session.title}}</text>
768
+ <text x="5" y="15" fill="#ffffff" font-size="6" font-weight="700">{{state.currentExercise.title}}</text>
769
+ <text x="5" y="21" fill="#7f8da3" font-size="4">{{state.currentExercise.subtitle}}</text>
770
+ <text x="5" y="31" fill="#ffffff" font-size="7" font-weight="700">{{state.currentSet.title}}</text>
771
+ <text x="78" y="12" fill="#00d69c" font-size="6" font-weight="700">{{timers.rest.remainingText}}</text>
772
+ <rect x="80" y="24" width="14" height="10" rx="3" fill="#00d69c" />
773
+ <text x="85" y="31" fill="#ffffff" font-size="7" font-weight="700">✓</text>
774
+ </svg>`.trim(),
775
+ },
776
+ },
777
+ },
778
+ };
779
+ }
780
+
781
+ const CapgoWidgetKit = core.registerPlugin('CapgoWidgetKit', {
782
+ web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapgoWidgetKitWeb()),
783
+ });
784
+
785
+ const STORE_KEY = 'capgo-widget-kit-preview-store-v2';
786
+ function cloneJson(value) {
787
+ return JSON.parse(JSON.stringify(value));
788
+ }
789
+ function loadStore() {
790
+ var _a, _b, _c, _d;
791
+ if (typeof localStorage === 'undefined') {
792
+ return { activities: {}, events: {}, sessions: {}, messages: {} };
793
+ }
794
+ const raw = localStorage.getItem(STORE_KEY);
795
+ if (!raw) {
796
+ return { activities: {}, events: {}, sessions: {}, messages: {} };
797
+ }
798
+ try {
799
+ const parsed = JSON.parse(raw);
800
+ return {
801
+ activities: (_a = parsed.activities) !== null && _a !== void 0 ? _a : {},
802
+ events: (_b = parsed.events) !== null && _b !== void 0 ? _b : {},
803
+ sessions: (_c = parsed.sessions) !== null && _c !== void 0 ? _c : {},
804
+ messages: (_d = parsed.messages) !== null && _d !== void 0 ? _d : {},
805
+ };
806
+ }
807
+ catch (_e) {
808
+ return { activities: {}, events: {}, sessions: {}, messages: {} };
809
+ }
810
+ }
811
+ function saveStore(store) {
812
+ if (typeof localStorage === 'undefined') {
813
+ return;
814
+ }
815
+ localStorage.setItem(STORE_KEY, JSON.stringify(store));
816
+ }
817
+ function sortActivities(activities) {
818
+ return activities.sort((left, right) => right.updatedAt - left.updatedAt);
819
+ }
820
+ function sortEvents(events) {
821
+ return events.sort((left, right) => right.createdAt - left.createdAt);
822
+ }
823
+ function sortSessions(sessions) {
824
+ return sessions.sort((left, right) => right.updatedAt - left.updatedAt);
825
+ }
826
+ function sortMessages(messages) {
827
+ return messages.sort((left, right) => right.createdAt - left.createdAt);
828
+ }
829
+ function mergeJsonObject(base, patch) {
830
+ const merged = cloneJson(base);
831
+ for (const [key, value] of Object.entries(patch)) {
832
+ const current = merged[key];
833
+ if (current &&
834
+ typeof current === 'object' &&
835
+ !Array.isArray(current) &&
836
+ value &&
837
+ typeof value === 'object' &&
838
+ !Array.isArray(value)) {
839
+ merged[key] = mergeJsonObject(current, value);
840
+ }
841
+ else {
842
+ merged[key] = cloneJson(value);
843
+ }
844
+ }
845
+ return merged;
846
+ }
847
+ function getActivityOrThrow(store, activityId) {
848
+ const activity = store.activities[activityId];
849
+ if (!activity) {
850
+ throw new Error(`Activity ${activityId} was not found in the preview store.`);
851
+ }
852
+ return cloneJson(activity);
853
+ }
854
+ class CapgoWidgetKitWeb extends core.WebPlugin {
855
+ async areActivitiesSupported() {
856
+ return {
857
+ supported: false,
858
+ reason: 'WidgetKit preview mode only. The generic template runtime works in the browser, but native ActivityKit support is available on iOS 16.2+.',
859
+ };
860
+ }
861
+ async startTemplateActivity(options) {
862
+ const store = loadStore();
863
+ const activity = createTemplateActivityRecord(options.definition, options.state, {
864
+ activityId: options.activityId,
865
+ openUrl: options.openUrl,
866
+ });
867
+ store.activities[activity.activityId] = activity;
868
+ saveStore(store);
869
+ return { activity: cloneJson(activity) };
870
+ }
871
+ async updateTemplateActivity(options) {
872
+ var _a, _b, _c;
873
+ const store = loadStore();
874
+ const current = getActivityOrThrow(store, options.activityId);
875
+ const now = Date.now();
876
+ const nextActivity = Object.assign(Object.assign({}, current), { definition: cloneJson((_a = options.definition) !== null && _a !== void 0 ? _a : current.definition), state: cloneJson((_b = options.state) !== null && _b !== void 0 ? _b : current.state), openUrl: (_c = options.openUrl) !== null && _c !== void 0 ? _c : current.openUrl, updatedAt: now, revision: current.revision + 1 });
877
+ nextActivity.timers = reconcileTimerStates(nextActivity.definition, nextActivity.state, nextActivity.timers, nextActivity.activityId, nextActivity.status, now);
878
+ store.activities[nextActivity.activityId] = nextActivity;
879
+ saveStore(store);
880
+ return { activity: cloneJson(nextActivity) };
881
+ }
882
+ async endTemplateActivity(options) {
883
+ var _a;
884
+ const store = loadStore();
885
+ const current = getActivityOrThrow(store, options.activityId);
886
+ const now = Date.now();
887
+ const nextActivity = Object.assign(Object.assign({}, current), { state: cloneJson((_a = options.state) !== null && _a !== void 0 ? _a : current.state), status: 'ended', updatedAt: now, revision: current.revision + 1 });
888
+ nextActivity.timers = reconcileTimerStates(nextActivity.definition, nextActivity.state, nextActivity.timers, nextActivity.activityId, nextActivity.status, now);
889
+ store.activities[nextActivity.activityId] = nextActivity;
890
+ saveStore(store);
891
+ }
892
+ async performTemplateAction(options) {
893
+ const store = loadStore();
894
+ const activity = getActivityOrThrow(store, options.activityId);
895
+ const result = applyTemplateAction(activity, options);
896
+ store.activities[result.activity.activityId] = result.activity;
897
+ store.events[result.event.eventId] = result.event;
898
+ saveStore(store);
899
+ return {
900
+ activity: cloneJson(result.activity),
901
+ event: cloneJson(result.event),
902
+ };
903
+ }
904
+ async getTemplateActivity(options) {
905
+ const store = loadStore();
906
+ const activity = store.activities[options.activityId];
907
+ return {
908
+ activity: activity ? cloneJson(activity) : null,
909
+ };
910
+ }
911
+ async listTemplateActivities() {
912
+ const store = loadStore();
913
+ return {
914
+ activities: sortActivities(Object.values(store.activities).map((activity) => cloneJson(activity))),
915
+ };
916
+ }
917
+ async listTemplateEvents(options) {
918
+ const store = loadStore();
919
+ const filtered = Object.values(store.events).filter((event) => {
920
+ if ((options === null || options === void 0 ? void 0 : options.activityId) && event.activityId !== options.activityId) {
921
+ return false;
922
+ }
923
+ if ((options === null || options === void 0 ? void 0 : options.unacknowledgedOnly) && event.acknowledgedAt != null) {
924
+ return false;
925
+ }
926
+ return true;
927
+ });
928
+ return {
929
+ events: sortEvents(filtered.map((event) => cloneJson(event))),
930
+ };
931
+ }
932
+ async acknowledgeTemplateEvents(options) {
933
+ const store = loadStore();
934
+ const nextEvents = acknowledgeEvents(Object.values(store.events), options);
935
+ store.events = Object.fromEntries(nextEvents.map((event) => [event.eventId, event]));
936
+ saveStore(store);
937
+ }
938
+ async startWidgetSession(options) {
939
+ var _a, _b;
940
+ const store = loadStore();
941
+ const now = Date.now();
942
+ const widgetId = options.widgetId && options.widgetId.length > 0 ? options.widgetId : createRuntimeId('widget');
943
+ const session = {
944
+ widgetId,
945
+ kind: options.kind,
946
+ state: cloneJson((_a = options.state) !== null && _a !== void 0 ? _a : {}),
947
+ metadata: cloneJson((_b = options.metadata) !== null && _b !== void 0 ? _b : {}),
948
+ status: 'active',
949
+ createdAt: now,
950
+ updatedAt: now,
951
+ revision: 1,
952
+ };
953
+ store.sessions[widgetId] = session;
954
+ saveStore(store);
955
+ return { session: cloneJson(session) };
956
+ }
957
+ async updateWidgetSession(options) {
958
+ var _a, _b;
959
+ const store = loadStore();
960
+ const current = store.sessions[options.widgetId];
961
+ if (!current) {
962
+ return { session: null };
963
+ }
964
+ const nextSession = Object.assign(Object.assign({}, cloneJson(current)), { state: options.state == null
965
+ ? cloneJson(current.state)
966
+ : options.merge
967
+ ? mergeJsonObject(current.state, options.state)
968
+ : cloneJson(options.state), metadata: options.metadata == null
969
+ ? cloneJson((_a = current.metadata) !== null && _a !== void 0 ? _a : {})
970
+ : options.merge
971
+ ? mergeJsonObject((_b = current.metadata) !== null && _b !== void 0 ? _b : {}, options.metadata)
972
+ : cloneJson(options.metadata), status: 'active', updatedAt: Date.now(), revision: current.revision + 1 });
973
+ store.sessions[nextSession.widgetId] = nextSession;
974
+ saveStore(store);
975
+ return { session: cloneJson(nextSession) };
976
+ }
977
+ async stopWidgetSession(options) {
978
+ var _a;
979
+ const store = loadStore();
980
+ const current = store.sessions[options.widgetId];
981
+ if (!current) {
982
+ return;
983
+ }
984
+ const nextSession = Object.assign(Object.assign({}, cloneJson(current)), { state: cloneJson((_a = options.state) !== null && _a !== void 0 ? _a : current.state), status: 'stopped', updatedAt: Date.now(), revision: current.revision + 1 });
985
+ store.sessions[nextSession.widgetId] = nextSession;
986
+ saveStore(store);
987
+ }
988
+ async getWidgetSession(options) {
989
+ const store = loadStore();
990
+ const session = store.sessions[options.widgetId];
991
+ return { session: session ? cloneJson(session) : null };
992
+ }
993
+ async listWidgetSessions() {
994
+ const store = loadStore();
995
+ return { sessions: sortSessions(Object.values(store.sessions).map((session) => cloneJson(session))) };
996
+ }
997
+ async sendWidgetMessage(options) {
998
+ var _a, _b;
999
+ const store = loadStore();
1000
+ const now = Date.now();
1001
+ const message = {
1002
+ messageId: createRuntimeId('message'),
1003
+ widgetId: options.widgetId,
1004
+ direction: (_a = options.direction) !== null && _a !== void 0 ? _a : 'appToWidget',
1005
+ name: options.name,
1006
+ payload: options.payload ? cloneJson(options.payload) : null,
1007
+ expectsResponse: (_b = options.expectsResponse) !== null && _b !== void 0 ? _b : false,
1008
+ status: 'pending',
1009
+ createdAt: now,
1010
+ acknowledgedAt: null,
1011
+ completedAt: null,
1012
+ response: null,
1013
+ error: null,
1014
+ };
1015
+ store.messages[message.messageId] = message;
1016
+ saveStore(store);
1017
+ return { message: cloneJson(message) };
1018
+ }
1019
+ async listWidgetMessages(options) {
1020
+ const store = loadStore();
1021
+ const messages = Object.values(store.messages).filter((message) => {
1022
+ if ((options === null || options === void 0 ? void 0 : options.widgetId) && message.widgetId !== options.widgetId) {
1023
+ return false;
1024
+ }
1025
+ if ((options === null || options === void 0 ? void 0 : options.direction) && message.direction !== options.direction) {
1026
+ return false;
1027
+ }
1028
+ if ((options === null || options === void 0 ? void 0 : options.unacknowledgedOnly) && message.acknowledgedAt != null) {
1029
+ return false;
1030
+ }
1031
+ if ((options === null || options === void 0 ? void 0 : options.pendingOnly) && message.status !== 'pending') {
1032
+ return false;
1033
+ }
1034
+ return true;
1035
+ });
1036
+ return { messages: sortMessages(messages.map((message) => cloneJson(message))) };
1037
+ }
1038
+ async acknowledgeWidgetMessages(options) {
1039
+ var _a;
1040
+ const store = loadStore();
1041
+ const now = Date.now();
1042
+ const messageIds = new Set((_a = options.messageIds) !== null && _a !== void 0 ? _a : []);
1043
+ for (const message of Object.values(store.messages)) {
1044
+ const matchesMessageId = messageIds.size > 0 && messageIds.has(message.messageId);
1045
+ const matchesWidget = options.widgetId != null && message.widgetId === options.widgetId;
1046
+ const matchesDirection = !options.direction || message.direction === options.direction;
1047
+ if ((matchesMessageId || matchesWidget) && matchesDirection) {
1048
+ message.acknowledgedAt = now;
1049
+ }
1050
+ }
1051
+ saveStore(store);
1052
+ }
1053
+ async completeWidgetMessage(options) {
1054
+ var _a;
1055
+ const store = loadStore();
1056
+ const message = store.messages[options.messageId];
1057
+ if (!message) {
1058
+ return { message: null };
1059
+ }
1060
+ if (message.status !== 'pending' || message.completedAt != null) {
1061
+ return { message: cloneJson(message) };
1062
+ }
1063
+ const nextMessage = Object.assign(Object.assign({}, cloneJson(message)), { status: options.error ? 'failed' : 'completed', completedAt: Date.now(), response: options.response ? cloneJson(options.response) : null, error: (_a = options.error) !== null && _a !== void 0 ? _a : null });
1064
+ store.messages[nextMessage.messageId] = nextMessage;
1065
+ saveStore(store);
1066
+ return { message: cloneJson(nextMessage) };
1067
+ }
1068
+ async getPluginVersion() {
1069
+ return {
1070
+ version: 'web-preview',
1071
+ };
1072
+ }
1073
+ }
1074
+
1075
+ var web = /*#__PURE__*/Object.freeze({
1076
+ __proto__: null,
1077
+ CapgoWidgetKitWeb: CapgoWidgetKitWeb
1078
+ });
1079
+
1080
+ exports.CapgoWidgetKit = CapgoWidgetKit;
1081
+ exports.acknowledgeEvents = acknowledgeEvents;
1082
+ exports.applyTemplateAction = applyTemplateAction;
1083
+ exports.createRuntimeId = createRuntimeId;
1084
+ exports.createTemplateActivityRecord = createTemplateActivityRecord;
1085
+ exports.createWorkoutTemplateActivity = createWorkoutTemplateActivity;
1086
+ exports.deleteValueAtPath = deleteValueAtPath;
1087
+ exports.getTemplateLayout = getTemplateLayout;
1088
+ exports.getValueAtPath = getValueAtPath;
1089
+ exports.reconcileTimerStates = reconcileTimerStates;
1090
+ exports.resolveSvgLayout = resolveSvgLayout;
1091
+ exports.resolveTemplateSurface = resolveTemplateSurface;
1092
+ exports.setValueAtPath = setValueAtPath;
1093
+ exports.toJsonObject = toJsonObject;
1094
+ exports.toJsonValue = toJsonValue;
1095
+
1096
+ return exports;
1097
+
1098
+ })({}, capacitorExports);
1099
+ //# sourceMappingURL=plugin.js.map